diff --git a/.venv/Lib/site-packages/TatSu-5.8.3.dist-info/INSTALLER b/.venv/Lib/site-packages/TatSu-5.8.3.dist-info/INSTALLER deleted file mode 100644 index a1b589e..0000000 --- a/.venv/Lib/site-packages/TatSu-5.8.3.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/.venv/Lib/site-packages/TatSu-5.8.3.dist-info/LICENSE.txt b/.venv/Lib/site-packages/TatSu-5.8.3.dist-info/LICENSE.txt deleted file mode 100644 index 376a1d9..0000000 --- a/.venv/Lib/site-packages/TatSu-5.8.3.dist-info/LICENSE.txt +++ /dev/null @@ -1,36 +0,0 @@ -TATSU - A PEG/Packrat parser generator for Python - -Copyright (C) 2017-2022 Juancarlo Añez -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions - are met: - - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the - distribution. - - 3. Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived - from this software without specific prior written permission. - - 4. Redistributions of any form whatsoever must retain the following - acknowledgment: 'This product includes software developed by - "Juancarlo Añez" (https://apalala.bitbucket.io).' - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED - TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/.venv/Lib/site-packages/TatSu-5.8.3.dist-info/METADATA b/.venv/Lib/site-packages/TatSu-5.8.3.dist-info/METADATA deleted file mode 100644 index dadc9ed..0000000 --- a/.venv/Lib/site-packages/TatSu-5.8.3.dist-info/METADATA +++ /dev/null @@ -1,327 +0,0 @@ -Metadata-Version: 2.1 -Name: TatSu -Version: 5.8.3 -Summary: TatSu takes a grammar in a variation of EBNF as input, and outputs a memoizing PEG/Packrat parser in Python. -Home-page: https://github.com/neogeny/tatsu -Author: Juancarlo Añez -Author-email: apalala@gmail.com -Maintainer: Juancarlo Añez -Maintainer-email: apalala@gmail.com -License: BSD-3-Clause-Attribution -Classifier: Development Status :: 5 - Production/Stable -Classifier: License :: OSI Approved :: BSD License -Classifier: Natural Language :: English -Classifier: Intended Audience :: Developers -Classifier: Intended Audience :: Science/Research -Classifier: Environment :: Console -Classifier: Operating System :: OS Independent -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Topic :: Software Development :: Code Generators -Classifier: Topic :: Software Development :: Compilers -Classifier: Topic :: Software Development :: Interpreters -Classifier: Topic :: Text Processing :: General -Requires-Python: >=3.8 -License-File: LICENSE.txt -Provides-Extra: future-regex -Requires-Dist: regex ; extra == 'future-regex' - -.. |dragon| unicode:: 0x7ADC .. unicode dragon -.. |TatSu| replace:: |dragon| **TatSu** - -|license| |pyversions| |fury| |downloads| |actions| |docs| - - *At least for the people who send me mail about a new language that - they're designing, the general advice is: do it to learn about how - to write a compiler. Don't have any expectations that anyone will - use it, unless you hook up with some sort of organization in a - position to push it hard. It's a lottery, and some can buy a lot of - the tickets. There are plenty of beautiful languages (more beautiful - than C) that didn't catch on. But someone does win the lottery, and - doing a language at least teaches you something.* - - `Dennis Ritchie`_ (1941-2011) Creator of the C_ programming - language and of Unix_ - - -|TatSu| -======= - -|TatSu| is a tool that takes grammars in a variation of `EBNF`_ as input, and -outputs `memoizing`_ (`Packrat`_) `PEG`_ parsers in `Python`_. - -Why use a PEG_ parser? Because `regular languages`_ (those parsable with Python's ``re`` package) *"cannot count"*. Any language with nested structures or with balancing of demarcations requires more than regular expressions to be parsed. - -|TatSu| can compile a grammar stored in a string into a -``tatsu.grammars.Grammar`` object that can be used to parse any given -input, much like the `re`_ module does with regular expressions, or it can generate a Python_ module that implements the parser. - -|TatSu| supports `left-recursive`_ rules in PEG_ grammars using the -algorithm_ by *Laurent* and *Mens*. The generated AST_ has the expected left associativity. - -Starting with version 5.8.0 |TatSu| requires Python 3.10 or later. -While no code in |TatSu| yet depends on new language or standard library features, -the authors don't want to be constrained by Python version comaptibility consideration -when developing features that will be part future releases. -Therefore, to simplify version pinning for users of the library, -they decided to proactively bump the Python minimum required version to 3.10. - -|TatSu| releases in the 5.7 series closely track releases in the 5.8 series -while maintaining compatibility with Python 3.8 and later. -Bug fixes are back-ported from 5.8 releases. -Features are back-ported from the 5.8 releases -unless they depend on Python features not available on the supported Python versions. -Refer to the `CHANGELOG`_ for details. - -.. _algorithm: http://norswap.com/pubs/sle2016.pdf - -Installation ------------- - -.. code-block:: bash - - $ pip install TatSu - - -Using the Tool --------------- - -|TatSu| can be used as a library, much like `Python`_'s ``re``, by embedding grammars as strings and generating grammar models instead of generating Python_ code. - -- ``tatsu.compile(grammar, name=None, **kwargs)`` - - Compiles the grammar and generates a *model* that can subsequently be used for parsing input with. - -- ``tatsu.parse(grammar, input, **kwargs)`` - - Compiles the grammar and parses the given input producing an AST_ as result. The result is equivalent to calling:: - - model = compile(grammar) - ast = model.parse(input) - - Compiled grammars are cached for efficiency. - -- ``tatsu.to_python_sourcecode(grammar, name=None, filename=None, **kwargs)`` - - Compiles the grammar to the `Python`_ sourcecode that implements the parser. - -This is an example of how to use |TatSu| as a library: - -.. code-block:: python - - GRAMMAR = ''' - @@grammar::CALC - - - start = expression $ ; - - - expression - = - | expression '+' term - | expression '-' term - | term - ; - - - term - = - | term '*' factor - | term '/' factor - | factor - ; - - - factor - = - | '(' expression ')' - | number - ; - - - number = /\d+/ ; - ''' - - - if __name__ == '__main__': - import json - from tatsu import parse - from tatsu.util import asjson - - ast = parse(GRAMMAR, '3 + 5 * ( 10 - 20 )') - print(json.dumps(asjson(ast), indent=2)) -.. - -|TatSu| will use the first rule defined in the grammar as the *start* rule. - -This is the output: - -.. code-block:: console - - [ - "3", - "+", - [ - "5", - "*", - [ - "10", - "-", - "20" - ] - ] - ] - -Documentation -------------- - -For a detailed explanation of what |TatSu| is capable of, please see the -documentation_. - -.. _documentation: http://tatsu.readthedocs.io/ - - -Questions? ----------- - -Please use the `[tatsu]`_ tag on `StackOverflow`_ for general Q&A, and limit -Github issues to bugs, enhancement proposals, and feature requests. - -.. _[tatsu]: https://stackoverflow.com/tags/tatsu/info - - -Changes -------- - -See the `CHANGELOG`_ for details. - - -License -------- - -You may use |TatSu| under the terms of the `BSD`_-style license -described in the enclosed `LICENSE.txt`_ file. *If your project -requires different licensing* please `email`_. - - -.. _ANTLR: http://www.antlr.org/ -.. _AST: http://en.wikipedia.org/wiki/Abstract_syntax_tree -.. _Abstract Syntax Tree: http://en.wikipedia.org/wiki/Abstract_syntax_tree -.. _Algol W: http://en.wikipedia.org/wiki/Algol_W -.. _Algorithms + Data Structures = Programs: http://www.amazon.com/Algorithms-Structures-Prentice-Hall-Automatic-Computation/dp/0130224189/ -.. _BSD: http://en.wikipedia.org/wiki/BSD_licenses#2-clause_license_.28.22Simplified_BSD_License.22_or_.22FreeBSD_License.22.29 -.. _Basel Shishani: https://bitbucket.org/basel-shishani -.. _C: http://en.wikipedia.org/wiki/C_language -.. _CHANGELOG: https://github.com/neogeny/TatSu/releases -.. _CSAIL at MIT: http://www.csail.mit.edu/ -.. _Cyclomatic complexity: http://en.wikipedia.org/wiki/Cyclomatic_complexity -.. _David Röthlisberger: https://bitbucket.org/drothlis/ -.. _Dennis Ritchie: http://en.wikipedia.org/wiki/Dennis_Ritchie -.. _EBNF: http://en.wikipedia.org/wiki/Ebnf -.. _English: http://en.wikipedia.org/wiki/English_grammar -.. _Euler: http://en.wikipedia.org/wiki/Euler_programming_language -.. _Grako: https://bitbucket.org/neogeny/grako/ -.. _Jack: http://en.wikipedia.org/wiki/Javacc -.. _Japanese: http://en.wikipedia.org/wiki/Japanese_grammar -.. _KLOC: http://en.wikipedia.org/wiki/KLOC -.. _Kathryn Long: https://bitbucket.org/starkat -.. _Keywords: https://en.wikipedia.org/wiki/Reserved_word -.. _`left-recursive`: https://en.wikipedia.org/wiki/Left_recursion -.. _LL(1): http://en.wikipedia.org/wiki/LL(1) -.. _Marcus Brinkmann: http://blog.marcus-brinkmann.de/ -.. _MediaWiki: http://www.mediawiki.org/wiki/MediaWiki -.. _Modula-2: http://en.wikipedia.org/wiki/Modula-2 -.. _Modula: http://en.wikipedia.org/wiki/Modula -.. _Oberon-2: http://en.wikipedia.org/wiki/Oberon-2 -.. _Oberon: http://en.wikipedia.org/wiki/Oberon_(programming_language) -.. _PEG and Packrat parsing mailing list: https://lists.csail.mit.edu/mailman/listinfo/peg -.. _PEG.js: http://pegjs.majda.cz/ -.. _PEG: http://en.wikipedia.org/wiki/Parsing_expression_grammar -.. _PL/0: http://en.wikipedia.org/wiki/PL/0 -.. _Packrat: http://bford.info/packrat/ -.. _Pascal: http://en.wikipedia.org/wiki/Pascal_programming_language -.. _Paul Sargent: https://bitbucket.org/PaulS/ -.. _Perl: http://www.perl.org/ -.. _PyPy team: http://pypy.org/people.html -.. _PyPy: http://pypy.org/ -.. _Python Weekly: http://www.pythonweekly.com/ -.. _Python: http://python.org -.. _Reserved Words: https://en.wikipedia.org/wiki/Reserved_word -.. _Robert Speer: https://bitbucket.org/r_speer -.. _Ruby: http://www.ruby-lang.org/ -.. _Semantic Graph: http://en.wikipedia.org/wiki/Abstract_semantic_graph -.. _StackOverflow: http://stackoverflow.com/tags/tatsu/info -.. _Sublime Text: https://www.sublimetext.com -.. _TatSu Forum: https://groups.google.com/forum/?fromgroups#!forum/tatsu -.. _UCAB: http://www.ucab.edu.ve/ -.. _USB: http://www.usb.ve/ -.. _Unix: http://en.wikipedia.org/wiki/Unix -.. _VIM: http://www.vim.org/ -.. _WTK: http://en.wikipedia.org/wiki/Well-known_text -.. _Warth et al: http://www.vpri.org/pdf/tr2007002_packrat.pdf -.. _Well-known text: http://en.wikipedia.org/wiki/Well-known_text -.. _Wirth: http://en.wikipedia.org/wiki/Niklaus_Wirth -.. _`LICENSE.txt`: LICENSE.txt -.. _basel-shishani: https://bitbucket.org/basel-shishani -.. _blog post: http://dietbuddha.blogspot.com/2012/12/52python-encapsulating-exceptions-with.html -.. _colorama: https://pypi.python.org/pypi/colorama/ -.. _context managers: http://docs.python.org/2/library/contextlib.html -.. _declensions: http://en.wikipedia.org/wiki/Declension -.. _drothlis: https://bitbucket.org/drothlis -.. _email: mailto:apalala@gmail.com -.. _exceptions: http://www.jeffknupp.com/blog/2013/02/06/write-cleaner-python-use-exceptions/ -.. _franz\_g: https://bitbucket.org/franz_g -.. _gapag: https://bitbucket.org/gapag -.. _gegenschall: https://bitbucket.org/gegenschall -.. _gkimbar: https://bitbucket.org/gkimbar -.. _introduced: http://dl.acm.org/citation.cfm?id=964001.964011 -.. _jimon: https://bitbucket.org/jimon -.. _keyword: https://en.wikipedia.org/wiki/Reserved_word -.. _keywords: https://en.wikipedia.org/wiki/Reserved_word -.. _lambdafu: http://blog.marcus-brinkmann.de/ -.. _leewz: https://bitbucket.org/leewz -.. _linkdd: https://bitbucket.org/linkdd -.. _make a donation: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=P9PV7ZACB669J -.. _memoizing: http://en.wikipedia.org/wiki/Memoization -.. _nehz: https://bitbucket.org/nehz -.. _neumond: https://bitbucket.org/neumond -.. _parsewkt: https://github.com/cleder/parsewkt -.. _pauls: https://bitbucket.org/pauls -.. _pgebhard: https://bitbucket.org/pgebhard -.. _pygraphviz: https://pypi.python.org/pypi/pygraphviz -.. _r\_speer: https://bitbucket.org/r_speer -.. _raw string literal: https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals -.. _re: https://docs.python.org/3.7/library/re.html -.. _regular languages: https://en.wikipedia.org/wiki/Regular_language -.. _regex: https://pypi.python.org/pypi/regex -.. _siemer: https://bitbucket.org/siemer -.. _sjbrownBitbucket: https://bitbucket.org/sjbrownBitbucket -.. _smc.mw: https://github.com/lambdafu/smc.mw -.. _starkat: https://bitbucket.org/starkat -.. _tonico\_strasser: https://bitbucket.org/tonico_strasser -.. _vinay.sajip: https://bitbucket.org/vinay.sajip -.. _vmuriart: https://bitbucket.org/vmuriart - -.. |fury| image:: https://badge.fury.io/py/TatSu.svg - :target: https://badge.fury.io/py/TatSu -.. |license| image:: https://img.shields.io/badge/license-BSD-blue.svg - :target: https://raw.githubusercontent.com/neogeny/tatsu/master/LICENSE.txt -.. |pyversions| image:: https://img.shields.io/pypi/pyversions/tatsu.svg - :target: https://pypi.python.org/pypi/tatsu -.. |travis| image:: https://secure.travis-ci.org/neogeny/TatSu.svg - :target: http://travis-ci.org/neogeny/TatSu -.. |actions| image:: https://github.com/neogeny/TatSu/workflows/tests/badge.svg - :target: https://github.com/neogeny/TatSu/actions -.. |circleci| image:: https://circleci.com/gh/neogeny/TatSu.svg?style=shield - :target: https://circleci.com/gh/neogeny/TatSu -.. |landscape| image:: https://landscape.io/github/apalala/TatSu/master/landscape.png - :target: https://landscape.io/github/apalala/TatSu/master -.. |donate| image:: https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif - :target: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=2TW56SV6WNJV6 -.. |quantifiedcode| image:: https://www.quantifiedcode.com/api/v1/project/f60bbd94ae2d4bd5b2e04c241c9d47ff/badge.svg - :target: https://www.quantifiedcode.com/app/project/f60bbd94ae2d4bd5b2e04c241c9d47ff - :alt: Code issues -.. |docs| image:: https://readthedocs.org/projects/tatsu/badge/?version=stable - :target: http://tatsu.readthedocs.io/en/stable/ -.. |downloads| image:: https://img.shields.io/pypi/dm/TatSu.svg - :target: http://tatsu.readthedocs.io/en/stable/ diff --git a/.venv/Lib/site-packages/TatSu-5.8.3.dist-info/RECORD b/.venv/Lib/site-packages/TatSu-5.8.3.dist-info/RECORD deleted file mode 100644 index 3363e99..0000000 --- a/.venv/Lib/site-packages/TatSu-5.8.3.dist-info/RECORD +++ /dev/null @@ -1,160 +0,0 @@ -../../Scripts/g2e.exe,sha256=UXNQeghEGTauoEU3Kg6guARxIuzQzteR_yMlueWE7ew,107903 -../../Scripts/tatsu.exe,sha256=xnv218Hag72aV7mRoCBFCTqlBholc7z6-WaI2cnvi_g,107899 -TatSu-5.8.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -TatSu-5.8.3.dist-info/LICENSE.txt,sha256=DwpeBhODt1UIjv1mSWkaFABPws9OPb26RkLQHhm0f8s,1770 -TatSu-5.8.3.dist-info/METADATA,sha256=zQjzCp7E-ICn_rjOMYlEe-QkXLEvBvBo93hi9cIX4io,13003 -TatSu-5.8.3.dist-info/RECORD,, -TatSu-5.8.3.dist-info/WHEEL,sha256=WzZ8cwjh8l0jtULNjYq1Hpr-WCqCRgPr--TX4P5I1Wo,110 -TatSu-5.8.3.dist-info/entry_points.txt,sha256=-wLm5mbjL8w73RvvuWvTVZqUNGnpVFQVLpEhzd7Sxus,58 -TatSu-5.8.3.dist-info/top_level.txt,sha256=WV9fOhQiVcph8aj6y-Ax-n2ZKvnwFkzYy-X1hewV2zY,11 -tatsu/__init__.py,sha256=ARTI4F_QHBRo3tiWmo9CJstyKiTYAerkB4vIlj8RycY,405 -tatsu/__main__.py,sha256=UovWsgLNmd13AJYw-JurZ8BNvaAZCng8cneUEp7H3g4,93 -tatsu/__pycache__/__init__.cpython-38.pyc,, -tatsu/__pycache__/__main__.cpython-38.pyc,, -tatsu/__pycache__/_config.cpython-38.pyc,, -tatsu/__pycache__/_version.cpython-38.pyc,, -tatsu/__pycache__/ast.cpython-38.pyc,, -tatsu/__pycache__/bootstrap.cpython-38.pyc,, -tatsu/__pycache__/buffering.cpython-38.pyc,, -tatsu/__pycache__/color.cpython-38.pyc,, -tatsu/__pycache__/contexts.cpython-38.pyc,, -tatsu/__pycache__/diagrams.cpython-38.pyc,, -tatsu/__pycache__/exceptions.cpython-38.pyc,, -tatsu/__pycache__/grammars.cpython-38.pyc,, -tatsu/__pycache__/infos.cpython-38.pyc,, -tatsu/__pycache__/leftrec.cpython-38.pyc,, -tatsu/__pycache__/model.cpython-38.pyc,, -tatsu/__pycache__/objectmodel.cpython-38.pyc,, -tatsu/__pycache__/parser.cpython-38.pyc,, -tatsu/__pycache__/parser_semantics.cpython-38.pyc,, -tatsu/__pycache__/parsing.cpython-38.pyc,, -tatsu/__pycache__/rendering.cpython-38.pyc,, -tatsu/__pycache__/semantics.cpython-38.pyc,, -tatsu/__pycache__/symtables.cpython-38.pyc,, -tatsu/__pycache__/synth.cpython-38.pyc,, -tatsu/__pycache__/tokenizing.cpython-38.pyc,, -tatsu/__pycache__/tool.cpython-38.pyc,, -tatsu/__pycache__/walkers.cpython-38.pyc,, -tatsu/_config.py,sha256=3xqZO0rNE4CqorUxQglpbCqiL3paDWcgpV5XehDKpDw,66 -tatsu/_version.py,sha256=UhDxQPykajmIu-a0zhzHNwz4uZ_X8XEnXc2qe4Z2T6o,22 -tatsu/ast.py,sha256=yf07pTpgqXDsAe2zm2dVzEtTfIHRNeLAYLn6YpBU9W8,3446 -tatsu/bootstrap.py,sha256=ukQ8kgwS9VZa4zmty7AFiBcP2gULx60o7TAuo_5lKUw,40093 -tatsu/buffering.py,sha256=Y07aSjHetOd1hYM7thxVOkUxGnxd37hHudbJh3u0DRk,11111 -tatsu/codegen/__init__.py,sha256=ETDSoqud24E7xZcb7z7TjY7SQxwvwt9L4BqrYspcMro,447 -tatsu/codegen/__pycache__/__init__.cpython-38.pyc,, -tatsu/codegen/__pycache__/cgbase.cpython-38.pyc,, -tatsu/codegen/__pycache__/objectmodel.cpython-38.pyc,, -tatsu/codegen/__pycache__/python.cpython-38.pyc,, -tatsu/codegen/cgbase.py,sha256=vB3qXcY_AzEz3-jz8KIdIQub_4dl9W5L0mTOfNS66bc,4392 -tatsu/codegen/objectmodel.py,sha256=RvaH1Bk43I96s36422oVKx8mZ5V8svIdWFHFVCpiQpw,6695 -tatsu/codegen/python.py,sha256=vjgqZrj-wSGuEOYTED3mOGvm-nbkYMYlCKQbULPcUVo,16073 -tatsu/collections/__init__.py,sha256=xrA2wUUgf-jNtm4CLw6HQ4uVU88AOCRNgiZuVg4lCWc,74 -tatsu/collections/__pycache__/__init__.cpython-38.pyc,, -tatsu/collections/__pycache__/orderedset.cpython-38.pyc,, -tatsu/collections/__pycache__/tail.cpython-38.pyc,, -tatsu/collections/orderedset.py,sha256=IVHRiqpJL6En6NtRvjdqPZNXaOyNBrznQBjzYUa-xKw,3919 -tatsu/collections/tail.py,sha256=A2mR1e6kjTdBhQWbIXu22GAj9ZrcSBx262zMvnjRXIM,958 -tatsu/color.py,sha256=fFYvhMSrejNruS-G8lWrtL4M9X5kMoztvMk6ihdp_fY,799 -tatsu/contexts.py,sha256=6Tu0DRz9lckyp1YmBTJYRO5M_N1WYD3bpwrXymTr9IY,26538 -tatsu/diagrams.py,sha256=GoXMXR_ByXhqBv9Q1hwtnoWTp3ywUOzSUPhCwrzOTwQ,7306 -tatsu/exceptions.py,sha256=lKKkZF0bLvRhYHQXcjGt9bDZ0MldskIwDK3nclZkOi8,3186 -tatsu/g2e/__init__.py,sha256=ilN9zQf3hOeQLSMm89Eyo2BO2G9Uvy6aBOV07QCVYB8,1305 -tatsu/g2e/__main__.py,sha256=dacWXTVRNvxNq7cX5aMqonYWFEg2s1L9INr9DN3BTO0,94 -tatsu/g2e/__pycache__/__init__.cpython-38.pyc,, -tatsu/g2e/__pycache__/__main__.cpython-38.pyc,, -tatsu/g2e/__pycache__/semantics.cpython-38.pyc,, -tatsu/g2e/antlr.ebnf,sha256=b-ipRPv1fpWrNXZaBBZb3s56PGCAipDmvGOYCEis_iI,5035 -tatsu/g2e/semantics.py,sha256=8gCZlNi8bQ6XXovriLXJwHhoQAr_mdtAdNZzVh9csUU,5199 -tatsu/grammars.py,sha256=-_cwRCkIt_tmJK1x7GegzHkm2Elej-HTUxMqr4ley28,29628 -tatsu/infos.py,sha256=v2pRSdzah6I4z5DhGM2metigO1qiRTSDxc38R8ykSts,5722 -tatsu/leftrec.py,sha256=JmJW7Xz7zg74hMHdxSmZQASCGV5OlUXbaQfNevXvJ8A,5410 -tatsu/mixins/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -tatsu/mixins/__pycache__/__init__.cpython-38.pyc,, -tatsu/mixins/__pycache__/indent.cpython-38.pyc,, -tatsu/mixins/indent.py,sha256=onvz5xI-UDBId1Wz65MsGXwKGBcMSU-o5x-wwVYR22U,1638 -tatsu/model.py,sha256=x2UD5ZzbNe5kHUPQJVTqjRu2IaBIr_h0iSwaf6qTaNk,426 -tatsu/objectmodel.py,sha256=TiOutkOVACk2RdDcS0RTflHLvSpZsk1hmFC7Kgqq64E,5426 -tatsu/parser.py,sha256=pv8RySibLq0TgS1Tgq7g3LrtRKchhnoQ1GQGqrUgRv4,816 -tatsu/parser_semantics.py,sha256=FyY2A3Yb7XMpkjqXqhwMXDZnkt3Iw-I4pZ0Qt6GFVcY,3938 -tatsu/parsing.py,sha256=I7ouCVzDWSzNthc9xJA2T3x-HOuNNjBDXzmmpunnoKI,1032 -tatsu/rendering.py,sha256=FuZDCxDZsbNKCyiJeKyt0bxdkpFKW1SJVar0Eqx154c,3890 -tatsu/semantics.py,sha256=gXO59UI_4ercRe4-K1V-5u3_74mIE9Bc6uQpvybnjGs,3024 -tatsu/symtables.py,sha256=pk4FkynHlUW_Awpz_OeUKw8UrcbOmD2sdsdWTUgmGP0,8632 -tatsu/synth.py,sha256=6EOA4okurFGrhxQNktPZGTG2Aw6iwQujZ6DVUVC5AFA,671 -tatsu/tokenizing.py,sha256=VU0-CihPlrhyUvZGniuu2CCmpQmshxqENqG2MQsVq3A,1500 -tatsu/tool.py,sha256=8AY6VMRy0Nfyx9usFolZDjrhFgwLci7YgeZAwO0BYRM,8596 -tatsu/util/__init__.py,sha256=41CuQNtOWPHkq-JT-Pp07djNYziJXyY4pBtmMrpHJQ4,31 -tatsu/util/__pycache__/__init__.cpython-38.pyc,, -tatsu/util/__pycache__/_common.cpython-38.pyc,, -tatsu/util/__pycache__/misc.cpython-38.pyc,, -tatsu/util/__pycache__/parproc.cpython-38.pyc,, -tatsu/util/__pycache__/testing.cpython-38.pyc,, -tatsu/util/__pycache__/unicode_characters.cpython-38.pyc,, -tatsu/util/_common.py,sha256=80Pq57ZDx2e5AKOeVNGfDj0qip9S9DYPT5X9Hpia0Kk,12370 -tatsu/util/misc.py,sha256=93zTwz3rUqPeHrsiEvFWnj3WGe5wsADaIkBXC5ABFHw,2433 -tatsu/util/parproc.py,sha256=gzXokJ5rScGwXn-kyEgKbN97iT3Kwwc0nCascyhKTVw,8025 -tatsu/util/testing.py,sha256=QXnRQPdr4i_3F4uocVbIWa-9-nN5CGAL9MZ4rhToI_8,2319 -tatsu/util/unicode_characters.py,sha256=8_YoRY2Y5-FXq8Q3KRGTqAln5hpfPtSsDAzPG1zthyw,1184 -tatsu/walkers.py,sha256=jnLoxS9MrMLFYKvL5BHYeekK1BrPwFrsBcd4WkAkieo,4798 -test/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -test/__main__.py,sha256=DsLm8-H6Ced413Se4HYtpoepdr_5vgbmT6_J7Yf796o,114 -test/__pycache__/__init__.cpython-38.pyc,, -test/__pycache__/__main__.cpython-38.pyc,, -test/__pycache__/ast_test.cpython-38.pyc,, -test/__pycache__/buffering_test.cpython-38.pyc,, -test/__pycache__/codegen_test.cpython-38.pyc,, -test/__pycache__/diagram_test.cpython-38.pyc,, -test/__pycache__/misc_test.cpython-38.pyc,, -test/__pycache__/model_test.cpython-38.pyc,, -test/__pycache__/parser_equivalence_test.cpython-38.pyc,, -test/__pycache__/parsing_test.cpython-38.pyc,, -test/__pycache__/pickle_test.cpython-38.pyc,, -test/__pycache__/walker_test.cpython-38.pyc,, -test/ast_test.py,sha256=UW7nPzj7O_iqMXzTyvDAzzOFGVGMaEGBq_iLdEm1zMI,1469 -test/buffering_test.py,sha256=OlGaVM1bn2-HKr-fBA69OceQ6PYnhOwhYMe7xK0bMFQ,3425 -test/codegen_test.py,sha256=uicMxexBV-gxkrYpeenAt8hqGM2OpQ0_-Qoiwcu7UaA,905 -test/diagram_test.py,sha256=VYARgg60eOhFo-Nkoa2sV6B5C1KZAY9DgUPvbSozB6Q,746 -test/grammar/__init__.py,sha256=iwhKnzeBJLKxpRVjvzwiRE63_zNpIBfaKLITauVph-0,24 -test/grammar/__pycache__/__init__.cpython-38.pyc,, -test/grammar/__pycache__/alerts_test.cpython-38.pyc,, -test/grammar/__pycache__/constants_test.cpython-38.pyc,, -test/grammar/__pycache__/defines_test.cpython-38.pyc,, -test/grammar/__pycache__/directive_test.cpython-38.pyc,, -test/grammar/__pycache__/error_test.cpython-38.pyc,, -test/grammar/__pycache__/firstfollow_test.cpython-38.pyc,, -test/grammar/__pycache__/join_test.cpython-38.pyc,, -test/grammar/__pycache__/keyword_test.cpython-38.pyc,, -test/grammar/__pycache__/left_recursion_test.cpython-38.pyc,, -test/grammar/__pycache__/lookahead_test.cpython-38.pyc,, -test/grammar/__pycache__/parameter_test.cpython-38.pyc,, -test/grammar/__pycache__/pattern_test.cpython-38.pyc,, -test/grammar/__pycache__/pretty_test.cpython-38.pyc,, -test/grammar/__pycache__/semantics_test.cpython-38.pyc,, -test/grammar/__pycache__/stateful_test.cpython-38.pyc,, -test/grammar/__pycache__/syntax_test.cpython-38.pyc,, -test/grammar/alerts_test.py,sha256=1zrtCIlR5mI1CM_f1mTpTKGWQd-c_IGkWqZBtdBR1Hc,319 -test/grammar/constants_test.py,sha256=DkG3YmKC8v97nrGUYWaOWpa3KxIN6hRJ87vAsWzVaMg,951 -test/grammar/defines_test.py,sha256=WLizoTV3Fx2EAy833CBUeH7hwfJ1kgjtiQxFSF63Er8,1706 -test/grammar/directive_test.py,sha256=eDO-rY3dCWPyEjNDl66TiIJSuMEsyH5o1Z07Xdh0uAw,4499 -test/grammar/error_test.py,sha256=1jtiyErDMJh8jgj5b0x1Ks0xRc7jDvFf1uROIDMig78,616 -test/grammar/firstfollow_test.py,sha256=0DzRWtcZg00hhkFg5vQhQ8AaJCBD-8tTPFtXLjmsNgI,2805 -test/grammar/join_test.py,sha256=7hqidL0b6mOn42_O61GJnjWMnaDFCwe0ImyqRp5B5To,5719 -test/grammar/keyword_test.py,sha256=YgO_sBD9zuJ8BkP0gcIxTWxGr6dC5Hi1zT2NonNTohw,3800 -test/grammar/left_recursion_test.py,sha256=zajJuZhG-oHAPR2D-UbQZzxhPqrd5e_OU6WNSysco98,15500 -test/grammar/lookahead_test.py,sha256=J25uO_D-YTxOZKpE18KEEziVF6PrPY6MJy3Nft4iMQI,762 -test/grammar/parameter_test.py,sha256=eEoncHe-L0wKmK5LiSwcu3LPXMo1Udwyn95WgzcAjhs,5931 -test/grammar/pattern_test.py,sha256=CbYJlfeasdy5mhCQBxXgGdK3T7KH6YzB2gh8mmna9qU,3090 -test/grammar/pretty_test.py,sha256=YA8liATTxOsybcgjpx4ujKA_meCvvJweiEYi8Lz3puU,1999 -test/grammar/semantics_test.py,sha256=9Bcq_f5istrKm5Asf6bt_l41nWI55fp0AxS-8fwo0MM,3118 -test/grammar/stateful_test.py,sha256=6qvTEO71nBY1MbqJq9A0Pzhrklt7oSoICeeqtFet0XE,3567 -test/grammar/syntax_test.py,sha256=4SDWZxzK2Otk__6vpBcX-Pl3nz_7mDenpkjjoiKPoWw,9912 -test/misc_test.py,sha256=TlXYFXhlCjS0gGm0n3RGnuTZ57Ci5hZU7_nJkQGWALk,440 -test/model_test.py,sha256=7xFIDGne2k6oXTTrm0W15yM4aXxAHhAMX4MUYb0uMI4,758 -test/parser_equivalence_test.py,sha256=Py2VNMlX3c887ddL8WRyWGmoxGFNWkCg2E5mrzPN6Jw,3638 -test/parsing_test.py,sha256=yMNslgjF_B28jJba-LriljFXfDlBMeIE-0WL3dfmbJE,4305 -test/pickle_test.py,sha256=lqJQ6oAXcyHvAijLP-s5vzVpYPWmMnVTgoheoAxNfIs,1478 -test/walker_test.py,sha256=vQ3qODQfb0EWWbGeCPlzoRT3sigJfCC14qYvyENfZ88,1840 -test/zzz_bootstrap/__init__.py,sha256=iwhKnzeBJLKxpRVjvzwiRE63_zNpIBfaKLITauVph-0,24 -test/zzz_bootstrap/__pycache__/__init__.cpython-38.pyc,, -test/zzz_bootstrap/__pycache__/bootstrap_test.cpython-38.pyc,, -test/zzz_bootstrap/bootstrap_test.py,sha256=ioV5_274Ijwh1LtdcaO9yU4ylSqBRjW0ymOQ-iV9zd8,6238 diff --git a/.venv/Lib/site-packages/TatSu-5.8.3.dist-info/WHEEL b/.venv/Lib/site-packages/TatSu-5.8.3.dist-info/WHEEL deleted file mode 100644 index b733a60..0000000 --- a/.venv/Lib/site-packages/TatSu-5.8.3.dist-info/WHEEL +++ /dev/null @@ -1,6 +0,0 @@ -Wheel-Version: 1.0 -Generator: bdist_wheel (0.37.0) -Root-Is-Purelib: true -Tag: py2-none-any -Tag: py3-none-any - diff --git a/.venv/Lib/site-packages/TatSu-5.8.3.dist-info/entry_points.txt b/.venv/Lib/site-packages/TatSu-5.8.3.dist-info/entry_points.txt deleted file mode 100644 index 03db6d9..0000000 --- a/.venv/Lib/site-packages/TatSu-5.8.3.dist-info/entry_points.txt +++ /dev/null @@ -1,3 +0,0 @@ -[console_scripts] -g2e = tatsu.g2e:main -tatsu = tatsu:main diff --git a/.venv/Lib/site-packages/TatSu-5.8.3.dist-info/top_level.txt b/.venv/Lib/site-packages/TatSu-5.8.3.dist-info/top_level.txt deleted file mode 100644 index 041a112..0000000 --- a/.venv/Lib/site-packages/TatSu-5.8.3.dist-info/top_level.txt +++ /dev/null @@ -1,2 +0,0 @@ -tatsu -test diff --git a/.venv/Lib/site-packages/__pycache__/six.cpython-38.pyc b/.venv/Lib/site-packages/__pycache__/six.cpython-38.pyc deleted file mode 100644 index 0157cc2..0000000 Binary files a/.venv/Lib/site-packages/__pycache__/six.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/_distutils_hack/__init__.py b/.venv/Lib/site-packages/_distutils_hack/__init__.py deleted file mode 100644 index 47ce249..0000000 --- a/.venv/Lib/site-packages/_distutils_hack/__init__.py +++ /dev/null @@ -1,128 +0,0 @@ -import sys -import os -import re -import importlib -import warnings - - -is_pypy = '__pypy__' in sys.builtin_module_names - - -warnings.filterwarnings('ignore', - '.+ distutils .+ deprecated', - DeprecationWarning) - - -def warn_distutils_present(): - if 'distutils' not in sys.modules: - return - if is_pypy and sys.version_info < (3, 7): - # PyPy for 3.6 unconditionally imports distutils, so bypass the warning - # https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250 - return - warnings.warn( - "Distutils was imported before Setuptools, but importing Setuptools " - "also replaces the `distutils` module in `sys.modules`. This may lead " - "to undesirable behaviors or errors. To avoid these issues, avoid " - "using distutils directly, ensure that setuptools is installed in the " - "traditional way (e.g. not an editable install), and/or make sure " - "that setuptools is always imported before distutils.") - - -def clear_distutils(): - if 'distutils' not in sys.modules: - return - warnings.warn("Setuptools is replacing distutils.") - mods = [name for name in sys.modules if re.match(r'distutils\b', name)] - for name in mods: - del sys.modules[name] - - -def enabled(): - """ - Allow selection of distutils by environment variable. - """ - which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'stdlib') - return which == 'local' - - -def ensure_local_distutils(): - clear_distutils() - distutils = importlib.import_module('setuptools._distutils') - distutils.__name__ = 'distutils' - sys.modules['distutils'] = distutils - - # sanity check that submodules load as expected - core = importlib.import_module('distutils.core') - assert '_distutils' in core.__file__, core.__file__ - - -def do_override(): - """ - Ensure that the local copy of distutils is preferred over stdlib. - - See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401 - for more motivation. - """ - if enabled(): - warn_distutils_present() - ensure_local_distutils() - - -class DistutilsMetaFinder: - def find_spec(self, fullname, path, target=None): - if path is not None: - return - - method_name = 'spec_for_{fullname}'.format(**locals()) - method = getattr(self, method_name, lambda: None) - return method() - - def spec_for_distutils(self): - import importlib.abc - import importlib.util - - class DistutilsLoader(importlib.abc.Loader): - - def create_module(self, spec): - return importlib.import_module('setuptools._distutils') - - def exec_module(self, module): - pass - - return importlib.util.spec_from_loader('distutils', DistutilsLoader()) - - def spec_for_pip(self): - """ - Ensure stdlib distutils when running under pip. - See pypa/pip#8761 for rationale. - """ - if self.pip_imported_during_build(): - return - clear_distutils() - self.spec_for_distutils = lambda: None - - @staticmethod - def pip_imported_during_build(): - """ - Detect if pip is being imported in a build script. Ref #2355. - """ - import traceback - return any( - frame.f_globals['__file__'].endswith('setup.py') - for frame, line in traceback.walk_stack(None) - ) - - -DISTUTILS_FINDER = DistutilsMetaFinder() - - -def add_shim(): - sys.meta_path.insert(0, DISTUTILS_FINDER) - - -def remove_shim(): - try: - sys.meta_path.remove(DISTUTILS_FINDER) - except ValueError: - pass diff --git a/.venv/Lib/site-packages/_distutils_hack/__pycache__/__init__.cpython-38.pyc b/.venv/Lib/site-packages/_distutils_hack/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index 8fd8fda..0000000 Binary files a/.venv/Lib/site-packages/_distutils_hack/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/_distutils_hack/__pycache__/override.cpython-38.pyc b/.venv/Lib/site-packages/_distutils_hack/__pycache__/override.cpython-38.pyc deleted file mode 100644 index 36b6ef7..0000000 Binary files a/.venv/Lib/site-packages/_distutils_hack/__pycache__/override.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/_distutils_hack/override.py b/.venv/Lib/site-packages/_distutils_hack/override.py deleted file mode 100644 index 2cc433a..0000000 --- a/.venv/Lib/site-packages/_distutils_hack/override.py +++ /dev/null @@ -1 +0,0 @@ -__import__('_distutils_hack').do_override() diff --git a/.venv/Lib/site-packages/aiohttp-3.8.1.dist-info/INSTALLER b/.venv/Lib/site-packages/aiohttp-3.8.1.dist-info/INSTALLER deleted file mode 100644 index a1b589e..0000000 --- a/.venv/Lib/site-packages/aiohttp-3.8.1.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/.venv/Lib/site-packages/aiohttp-3.8.1.dist-info/LICENSE.txt b/.venv/Lib/site-packages/aiohttp-3.8.1.dist-info/LICENSE.txt deleted file mode 100644 index 054102f..0000000 --- a/.venv/Lib/site-packages/aiohttp-3.8.1.dist-info/LICENSE.txt +++ /dev/null @@ -1,13 +0,0 @@ - Copyright 2013-2020 aio-libs collaboration. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/.venv/Lib/site-packages/aiohttp-3.8.1.dist-info/METADATA b/.venv/Lib/site-packages/aiohttp-3.8.1.dist-info/METADATA deleted file mode 100644 index c2f6bef..0000000 --- a/.venv/Lib/site-packages/aiohttp-3.8.1.dist-info/METADATA +++ /dev/null @@ -1,255 +0,0 @@ -Metadata-Version: 2.1 -Name: aiohttp -Version: 3.8.1 -Summary: Async http client/server framework (asyncio) -Home-page: https://github.com/aio-libs/aiohttp -Maintainer: aiohttp team -Maintainer-email: team@aiohttp.org -License: Apache 2 -Project-URL: Chat: Gitter, https://gitter.im/aio-libs/Lobby -Project-URL: CI: GitHub Actions, https://github.com/aio-libs/aiohttp/actions?query=workflow%3ACI -Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/aiohttp -Project-URL: Docs: Changelog, https://docs.aiohttp.org/en/stable/changes.html -Project-URL: Docs: RTD, https://docs.aiohttp.org -Project-URL: GitHub: issues, https://github.com/aio-libs/aiohttp/issues -Project-URL: GitHub: repo, https://github.com/aio-libs/aiohttp -Platform: UNKNOWN -Classifier: Development Status :: 5 - Production/Stable -Classifier: Framework :: AsyncIO -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: Apache Software License -Classifier: Operating System :: POSIX -Classifier: Operating System :: MacOS :: MacOS X -Classifier: Operating System :: Microsoft :: Windows -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.6 -Classifier: Programming Language :: Python :: 3.7 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Topic :: Internet :: WWW/HTTP -Requires-Python: >=3.6 -Description-Content-Type: text/x-rst -License-File: LICENSE.txt -Requires-Dist: attrs (>=17.3.0) -Requires-Dist: charset-normalizer (<3.0,>=2.0) -Requires-Dist: multidict (<7.0,>=4.5) -Requires-Dist: async-timeout (<5.0,>=4.0.0a3) -Requires-Dist: yarl (<2.0,>=1.0) -Requires-Dist: frozenlist (>=1.1.1) -Requires-Dist: aiosignal (>=1.1.2) -Requires-Dist: idna-ssl (>=1.0) ; python_version < "3.7" -Requires-Dist: asynctest (==0.13.0) ; python_version < "3.8" -Requires-Dist: typing-extensions (>=3.7.4) ; python_version < "3.8" -Provides-Extra: speedups -Requires-Dist: aiodns ; extra == 'speedups' -Requires-Dist: Brotli ; extra == 'speedups' -Requires-Dist: cchardet ; extra == 'speedups' - -================================== -Async http client/server framework -================================== - -.. image:: https://raw.githubusercontent.com/aio-libs/aiohttp/master/docs/aiohttp-plain.svg - :height: 64px - :width: 64px - :alt: aiohttp logo - -| - -.. image:: https://github.com/aio-libs/aiohttp/workflows/CI/badge.svg - :target: https://github.com/aio-libs/aiohttp/actions?query=workflow%3ACI - :alt: GitHub Actions status for master branch - -.. image:: https://codecov.io/gh/aio-libs/aiohttp/branch/master/graph/badge.svg - :target: https://codecov.io/gh/aio-libs/aiohttp - :alt: codecov.io status for master branch - -.. image:: https://badge.fury.io/py/aiohttp.svg - :target: https://pypi.org/project/aiohttp - :alt: Latest PyPI package version - -.. image:: https://readthedocs.org/projects/aiohttp/badge/?version=latest - :target: https://docs.aiohttp.org/ - :alt: Latest Read The Docs - -.. image:: https://img.shields.io/discourse/status?server=https%3A%2F%2Faio-libs.discourse.group - :target: https://aio-libs.discourse.group - :alt: Discourse status - -.. image:: https://badges.gitter.im/Join%20Chat.svg - :target: https://gitter.im/aio-libs/Lobby - :alt: Chat on Gitter - - -Key Features -============ - -- Supports both client and server side of HTTP protocol. -- Supports both client and server Web-Sockets out-of-the-box and avoids - Callback Hell. -- Provides Web-server with middlewares and plugable routing. - - -Getting started -=============== - -Client ------- - -To get something from the web: - -.. code-block:: python - - import aiohttp - import asyncio - - async def main(): - - async with aiohttp.ClientSession() as session: - async with session.get('http://python.org') as response: - - print("Status:", response.status) - print("Content-type:", response.headers['content-type']) - - html = await response.text() - print("Body:", html[:15], "...") - - loop = asyncio.get_event_loop() - loop.run_until_complete(main()) - -This prints: - -.. code-block:: - - Status: 200 - Content-type: text/html; charset=utf-8 - Body: ... - -Coming from `requests `_ ? Read `why we need so many lines `_. - -Server ------- - -An example using a simple server: - -.. code-block:: python - - # examples/server_simple.py - from aiohttp import web - - async def handle(request): - name = request.match_info.get('name', "Anonymous") - text = "Hello, " + name - return web.Response(text=text) - - async def wshandle(request): - ws = web.WebSocketResponse() - await ws.prepare(request) - - async for msg in ws: - if msg.type == web.WSMsgType.text: - await ws.send_str("Hello, {}".format(msg.data)) - elif msg.type == web.WSMsgType.binary: - await ws.send_bytes(msg.data) - elif msg.type == web.WSMsgType.close: - break - - return ws - - - app = web.Application() - app.add_routes([web.get('/', handle), - web.get('/echo', wshandle), - web.get('/{name}', handle)]) - - if __name__ == '__main__': - web.run_app(app) - - -Documentation -============= - -https://aiohttp.readthedocs.io/ - - -Demos -===== - -https://github.com/aio-libs/aiohttp-demos - - -External links -============== - -* `Third party libraries - `_ -* `Built with aiohttp - `_ -* `Powered by aiohttp - `_ - -Feel free to make a Pull Request for adding your link to these pages! - - -Communication channels -====================== - -*aio-libs discourse group*: https://aio-libs.discourse.group - -*gitter chat* https://gitter.im/aio-libs/Lobby - -We support `Stack Overflow -`_. -Please add *aiohttp* tag to your question there. - -Requirements -============ - -- Python >= 3.6 -- async-timeout_ -- attrs_ -- charset-normalizer_ -- multidict_ -- yarl_ - -Optionally you may install the cChardet_ and aiodns_ libraries (highly -recommended for sake of speed). - -.. _charset-normalizer: https://pypi.org/project/charset-normalizer -.. _aiodns: https://pypi.python.org/pypi/aiodns -.. _attrs: https://github.com/python-attrs/attrs -.. _multidict: https://pypi.python.org/pypi/multidict -.. _yarl: https://pypi.python.org/pypi/yarl -.. _async-timeout: https://pypi.python.org/pypi/async_timeout -.. _cChardet: https://pypi.python.org/pypi/cchardet - -License -======= - -``aiohttp`` is offered under the Apache 2 license. - - -Keepsafe -======== - -The aiohttp community would like to thank Keepsafe -(https://www.getkeepsafe.com) for its support in the early days of -the project. - - -Source code -=========== - -The latest developer version is available in a GitHub repository: -https://github.com/aio-libs/aiohttp - -Benchmarks -========== - -If you are interested in efficiency, the AsyncIO community maintains a -list of benchmarks on the official wiki: -https://github.com/python/asyncio/wiki/Benchmarks - - diff --git a/.venv/Lib/site-packages/aiohttp-3.8.1.dist-info/RECORD b/.venv/Lib/site-packages/aiohttp-3.8.1.dist-info/RECORD deleted file mode 100644 index ef05bc1..0000000 --- a/.venv/Lib/site-packages/aiohttp-3.8.1.dist-info/RECORD +++ /dev/null @@ -1,123 +0,0 @@ -aiohttp-3.8.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -aiohttp-3.8.1.dist-info/LICENSE.txt,sha256=CbjEGhGLCTtscH6PL7yug73to6It6fLb8uojWPX1VSs,612 -aiohttp-3.8.1.dist-info/METADATA,sha256=leqF7e_6a-kaeZYF95OmGuHmBJSrszA1eeLyVjzT9t4,7322 -aiohttp-3.8.1.dist-info/RECORD,, -aiohttp-3.8.1.dist-info/WHEEL,sha256=P24hRDQapckAvHvgBBzlH5uw6rQ_oZQtKbG6drGrqOM,100 -aiohttp-3.8.1.dist-info/top_level.txt,sha256=iv-JIaacmTl-hSho3QmphcKnbRRYx1st47yjz_178Ro,8 -aiohttp/.hash/_cparser.pxd.hash,sha256=1tLMUc3IzMppOVKW99LKG1TD6szTXGSaCfHgiPOL9aA,108 -aiohttp/.hash/_find_header.pxd.hash,sha256=TxG5w4etbVd6sfm5JWbdf5PW6LnuXRQnlMoFBVGKN2E,112 -aiohttp/.hash/_helpers.pyi.hash,sha256=D1pTrCkUaJ3by1XeGH_nE-amt7XdjfRHcm9oRtoGhHQ,108 -aiohttp/.hash/_helpers.pyx.hash,sha256=MA4zlNd5xukP4VDAbnoId0Azv8HxCpwLWie2gSMPLsw,108 -aiohttp/.hash/_http_parser.pyx.hash,sha256=AVrrJ4SFdluXTl9VvGvjt7SkdGSf8PtkKTM8DeneYKk,112 -aiohttp/.hash/_http_writer.pyx.hash,sha256=oqW0CdYfKNwSX0PKREN8Qz_Mi4aaioGCIPbEvsaEgaM,112 -aiohttp/.hash/_websocket.pyx.hash,sha256=8AcsJ5Tb8lZ9_QVXor_1Xbtl5igK1iP5rtEZZ0iA2AE,110 -aiohttp/.hash/hdrs.py.hash,sha256=Vfr7WRlz3YbkgRFBfXksCI8mA7PXUMhs37jnv0kiqWQ,103 -aiohttp/__init__.py,sha256=G_kbDNtxPNUC9qfqDv2MTeuN3WLCRnuqbidkZ7tkVcY,7086 -aiohttp/__pycache__/__init__.cpython-38.pyc,, -aiohttp/__pycache__/abc.cpython-38.pyc,, -aiohttp/__pycache__/base_protocol.cpython-38.pyc,, -aiohttp/__pycache__/client.cpython-38.pyc,, -aiohttp/__pycache__/client_exceptions.cpython-38.pyc,, -aiohttp/__pycache__/client_proto.cpython-38.pyc,, -aiohttp/__pycache__/client_reqrep.cpython-38.pyc,, -aiohttp/__pycache__/client_ws.cpython-38.pyc,, -aiohttp/__pycache__/connector.cpython-38.pyc,, -aiohttp/__pycache__/cookiejar.cpython-38.pyc,, -aiohttp/__pycache__/formdata.cpython-38.pyc,, -aiohttp/__pycache__/hdrs.cpython-38.pyc,, -aiohttp/__pycache__/helpers.cpython-38.pyc,, -aiohttp/__pycache__/http.cpython-38.pyc,, -aiohttp/__pycache__/http_exceptions.cpython-38.pyc,, -aiohttp/__pycache__/http_parser.cpython-38.pyc,, -aiohttp/__pycache__/http_websocket.cpython-38.pyc,, -aiohttp/__pycache__/http_writer.cpython-38.pyc,, -aiohttp/__pycache__/locks.cpython-38.pyc,, -aiohttp/__pycache__/log.cpython-38.pyc,, -aiohttp/__pycache__/multipart.cpython-38.pyc,, -aiohttp/__pycache__/payload.cpython-38.pyc,, -aiohttp/__pycache__/payload_streamer.cpython-38.pyc,, -aiohttp/__pycache__/pytest_plugin.cpython-38.pyc,, -aiohttp/__pycache__/resolver.cpython-38.pyc,, -aiohttp/__pycache__/streams.cpython-38.pyc,, -aiohttp/__pycache__/tcp_helpers.cpython-38.pyc,, -aiohttp/__pycache__/test_utils.cpython-38.pyc,, -aiohttp/__pycache__/tracing.cpython-38.pyc,, -aiohttp/__pycache__/typedefs.cpython-38.pyc,, -aiohttp/__pycache__/web.cpython-38.pyc,, -aiohttp/__pycache__/web_app.cpython-38.pyc,, -aiohttp/__pycache__/web_exceptions.cpython-38.pyc,, -aiohttp/__pycache__/web_fileresponse.cpython-38.pyc,, -aiohttp/__pycache__/web_log.cpython-38.pyc,, -aiohttp/__pycache__/web_middlewares.cpython-38.pyc,, -aiohttp/__pycache__/web_protocol.cpython-38.pyc,, -aiohttp/__pycache__/web_request.cpython-38.pyc,, -aiohttp/__pycache__/web_response.cpython-38.pyc,, -aiohttp/__pycache__/web_routedef.cpython-38.pyc,, -aiohttp/__pycache__/web_runner.cpython-38.pyc,, -aiohttp/__pycache__/web_server.cpython-38.pyc,, -aiohttp/__pycache__/web_urldispatcher.cpython-38.pyc,, -aiohttp/__pycache__/web_ws.cpython-38.pyc,, -aiohttp/__pycache__/worker.cpython-38.pyc,, -aiohttp/_cparser.pxd,sha256=rEtEshtn54wSf_ZCJ0EBjRyVBkIOv_oh17BcaNOd6V8,5188 -aiohttp/_find_header.c,sha256=-d1A3pkkpirVX5CDQaTSSTjdjXekmOjt-bqYcEQWbXc,197440 -aiohttp/_find_header.h,sha256=HistyxY7K3xEJ53Y5xEfwrDVDkfcV0zQ9mkzMgzi_jo,184 -aiohttp/_find_header.pxd,sha256=BFUSmxhemBtblqxzjzH3x03FfxaWlTyuAIOz8YZ5_nM,70 -aiohttp/_headers.pxi,sha256=1MhCe6Un_KI1tpO85HnDfzVO94BhcirLanAOys5FIHA,2090 -aiohttp/_helpers.c,sha256=6o0WiV3O6QP3w7CeIXWnzaDAiXlKzFsede2S_72iXP8,212983 -aiohttp/_helpers.cp38-win_amd64.pyd,sha256=MM-zPJtJ6-1Oz7RrIn-TMr7sX0Rizj6wz7HL0xzKWgY,48640 -aiohttp/_helpers.pyi,sha256=2Hd5IC0Zf4YTEJ412suyyhsh1kVyVDv5g4stgyo2Ksc,208 -aiohttp/_helpers.pyx,sha256=tgl7fZh0QMT6cjf4jSJ8iaO6DdQD3GON2-SH4N5_ETg,1084 -aiohttp/_http_parser.c,sha256=mbsJXw0OQc-RGRss03ciJZCU6-32n_RVnMOgf8cAbVo,978189 -aiohttp/_http_parser.cp38-win_amd64.pyd,sha256=W2SEYsWP7iPpJXWQ52pOPa9hFL3Gp67-Sss2plPQHYA,245248 -aiohttp/_http_parser.pyx,sha256=DPA0SE8XjJwda86m1u3Fyr-WrjU1ngA0TQ0QM8nP9RI,27389 -aiohttp/_http_writer.c,sha256=AEz-QiTHIfIhi7PNrEHU4jXNYfQakG4MCxLmkZyPfrw,221272 -aiohttp/_http_writer.cp38-win_amd64.pyd,sha256=fDCDV1pcnFymz5WhVLukfcNCKFZipSDNa4Jo0ujnDMo,44544 -aiohttp/_http_writer.pyx,sha256=8CBLytO2rx1kdpWe9HYSznhLXdeZWyE-3xI7jaGasag,4738 -aiohttp/_websocket.c,sha256=AGp31tkjXHaLdSFcI_6Cl7wGWqKLmMdk0OwLE0AdJNg,138422 -aiohttp/_websocket.cp38-win_amd64.pyd,sha256=vea7GHAyMvLwA_79hT8UfxOCB8bkxkRmiOSslIARmYY,28672 -aiohttp/_websocket.pyx,sha256=o9J7yi9c2-jTBjE3dUkXxhDWKvRWJz5GZfyLsgJQa38,1617 -aiohttp/abc.py,sha256=ZAnm9bpefUtEZmyn8sq1MSPqYugcKeQpzyuAwKGFXuw,5720 -aiohttp/base_protocol.py,sha256=0v3CthN_KxvGbfM8_FxJ9BPTUqS9i12FwAmZwa2udU8,2787 -aiohttp/client.py,sha256=c6I3s4pJjewThnygoBc9S8J0OyKFi2iWUrpLuZUhn08,46228 -aiohttp/client_exceptions.py,sha256=_UcHK3XARTA97iKZVyV4pxcXIrZaNMXo2uP-i1_RbcI,9619 -aiohttp/client_proto.py,sha256=znDiFu6aO85uYH2RAQZYXoN2useLY9K_DssswchyYKQ,8447 -aiohttp/client_reqrep.py,sha256=TIHaRXXdl_8pqxizifwaM25pW2_JmkfTM92KS93MuPI,38019 -aiohttp/client_ws.py,sha256=R8hACPfspjbzGmBLMR4wd94-ZhHlMnrtxMT86SDYMWg,10840 -aiohttp/connector.py,sha256=5jfOr8HbliCAKsCeaDr_HBr1kMhvrmGX5Gtl70vl3MI,52303 -aiohttp/cookiejar.py,sha256=qougeR1yU3JYyjIdbdELuERxgyQaAuXtYWw7HnbXqiY,13983 -aiohttp/formdata.py,sha256=dAEgBnFO9xcbmyf8Dbl5pB38GF1JPOwS9sFoG7rBsDo,6294 -aiohttp/hdrs.py,sha256=ygDnAqYCot8NMQyjck2r9CzpTspAOXpHknNl-yxIybY,4838 -aiohttp/helpers.py,sha256=hWYfMH8hdLea0u67N12xOPE7seloFKyWm99UNMWhBvs,27118 -aiohttp/http.py,sha256=NKlSh1UEf-ZoYBYI0IoAUq0jy_-wKyJQ-aT0GjQCy7k,1896 -aiohttp/http_exceptions.py,sha256=rLwhCbFrOpQ_ntr3GnxaxD3oRnTTNM1utmDDBUbdVTU,2691 -aiohttp/http_parser.py,sha256=M36gf2QvuBhpflaADhYMIch-GfD6lqQxgsgQANnxgF8,33546 -aiohttp/http_websocket.py,sha256=xeG_CKBaRiCy_bntLl4My63styputcl1zpGY2wtOmHY,26060 -aiohttp/http_writer.py,sha256=SglEj4FTKratNnHijo9Zhy5ZdXSy_0nClm_WzA6UoZs,6176 -aiohttp/locks.py,sha256=fIuR6LrO3cyaSR7hwUzftTM-tnOhkVfm8NVyn8EwPis,1193 -aiohttp/log.py,sha256=zYUTvXsMQ9Sz1yNN8kXwd5Qxu49a1FzjZ_wQqriEc8M,333 -aiohttp/multipart.py,sha256=0m5kNFTUrOWs_fhKWEjhnZYirZhAakTLgrWy0SQbnH0,33400 -aiohttp/payload.py,sha256=vycRTUCM-57LyZ7hVrLffJfulBeT3rhO6A-YxYmUoDk,14165 -aiohttp/payload_streamer.py,sha256=6bbqsfgysHzfUTJIUlqad1wRklVuLmNHVtScv_mWhGY,2187 -aiohttp/py.typed,sha256=3VVwXUAWVEVX7sDwyYDnW5ZdBC9_Z9AJAFfLCleUW0k,8 -aiohttp/pytest_plugin.py,sha256=26CllzLUw-JGrwfXYIK-XGbDMCDwbIaomV7Sk4WZVG4,12163 -aiohttp/resolver.py,sha256=UWM-6HJkOLwkGveoesBnGv-pJePtpE7js6ujYi7XHoc,5252 -aiohttp/streams.py,sha256=jDR3ZtPlDjaL35Oe5HcLq0LvoYXIGEbSRUnqZKEfiNk,21500 -aiohttp/tcp_helpers.py,sha256=jPHZyIHbIAqyWS0QShT_ZgKLMiDW7s_124IPc4irTU8,1000 -aiohttp/test_utils.py,sha256=hLOEAJzOfM69LGMx74xrLutS_xZMI_6-AVkPDpWyNx4,21917 -aiohttp/tracing.py,sha256=RoYBPZQqvV2pIRbeaSUGe-cElR2FdQYBZOaMnPPRJXE,15777 -aiohttp/typedefs.py,sha256=E-iS7tNE3CrcMAjz5uiwr_Zlp4CKpCU99hzAKw08g14,1830 -aiohttp/web.py,sha256=hrZ6KRXbBLLQ1XThCoL-696TApjFiYDB6vXyOsv9lBc,18515 -aiohttp/web_app.py,sha256=pQwAAMSlu89p4Vt0DRG5_c4nvOzXHi3MBSlCCiQTH14,17825 -aiohttp/web_exceptions.py,sha256=ydzJJKwJWHOKzjzh0XtZNzZ5NCb0Me8DKmlKy2qvijw,10547 -aiohttp/web_fileresponse.py,sha256=tRRZyBNPL579Ac8Q2mSF7qjHIkV42z9VyVEkvQLOJlQ,11072 -aiohttp/web_log.py,sha256=3TaiQcu9N5teUfLn71__htAnhPgE90vneVM_YCk5Zlc,7773 -aiohttp/web_middlewares.py,sha256=qmHNhOdhTtJZjChDiBlF9M-SGxF3vz2koDnxMPrlNCA,4256 -aiohttp/web_protocol.py,sha256=YOCCQYDGXZ3XQ-931PDL_JEgIDyzyNMcHRlfXyzbMe0,23229 -aiohttp/web_request.py,sha256=T5N94hz58iBnFK8ugKI02t_mJ_KRosuII3ytrb07f6I,28762 -aiohttp/web_response.py,sha256=hCk7LNxI90k1XUKOLQDWF5hs0mlD15INxibeXbj_LXg,28392 -aiohttp/web_routedef.py,sha256=zz6VaH5Mm4lAnplxoCMEVDnh1BfTGJiAWLOHalMgtRA,6253 -aiohttp/web_runner.py,sha256=QEIbQwHXwQHoHVzKxJ1V5mcxcfLZv-h9kSzcqA6REk4,11570 -aiohttp/web_server.py,sha256=iKc9a4fQS14-3ivqzBiBp742m8vEexRZiSzeKTW7NCo,2120 -aiohttp/web_urldispatcher.py,sha256=ZlkWuhY_Nl6mO7x9Aqn3-5XRle1v1G58_ynmPtJXpI8,40767 -aiohttp/web_ws.py,sha256=YAEf_B2OXOCtZnvH2V2AM4E2FHVeIo7Gg_4t5wlx1R8,17746 -aiohttp/worker.py,sha256=isIbXTFiV-oNOeI6hxRGW2My6O3MW2ImqOqjNaP9auE,9048 diff --git a/.venv/Lib/site-packages/aiohttp-3.8.1.dist-info/WHEEL b/.venv/Lib/site-packages/aiohttp-3.8.1.dist-info/WHEEL deleted file mode 100644 index 2c375d8..0000000 --- a/.venv/Lib/site-packages/aiohttp-3.8.1.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: bdist_wheel (0.37.0) -Root-Is-Purelib: false -Tag: cp38-cp38-win_amd64 - diff --git a/.venv/Lib/site-packages/aiohttp-3.8.1.dist-info/top_level.txt b/.venv/Lib/site-packages/aiohttp-3.8.1.dist-info/top_level.txt deleted file mode 100644 index ee4ba4f..0000000 --- a/.venv/Lib/site-packages/aiohttp-3.8.1.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -aiohttp diff --git a/.venv/Lib/site-packages/aiohttp/.hash/_cparser.pxd.hash b/.venv/Lib/site-packages/aiohttp/.hash/_cparser.pxd.hash deleted file mode 100644 index cd588d0..0000000 --- a/.venv/Lib/site-packages/aiohttp/.hash/_cparser.pxd.hash +++ /dev/null @@ -1 +0,0 @@ -ac4b44b21b67e78c127ff6422741018d1c9506420ebffa21d7b05c68d39de95f *D:/a/aiohttp/aiohttp/aiohttp/_cparser.pxd diff --git a/.venv/Lib/site-packages/aiohttp/.hash/_find_header.pxd.hash b/.venv/Lib/site-packages/aiohttp/.hash/_find_header.pxd.hash deleted file mode 100644 index 8af9f81..0000000 --- a/.venv/Lib/site-packages/aiohttp/.hash/_find_header.pxd.hash +++ /dev/null @@ -1 +0,0 @@ -0455129b185e981b5b96ac738f31f7c74dc57f1696953cae0083b3f18679fe73 *D:/a/aiohttp/aiohttp/aiohttp/_find_header.pxd diff --git a/.venv/Lib/site-packages/aiohttp/.hash/_helpers.pyi.hash b/.venv/Lib/site-packages/aiohttp/.hash/_helpers.pyi.hash deleted file mode 100644 index 82a670d..0000000 --- a/.venv/Lib/site-packages/aiohttp/.hash/_helpers.pyi.hash +++ /dev/null @@ -1 +0,0 @@ -d87779202d197f8613109e35dacbb2ca1b21d64572543bf9838b2d832a362ac7 *D:/a/aiohttp/aiohttp/aiohttp/_helpers.pyi diff --git a/.venv/Lib/site-packages/aiohttp/.hash/_helpers.pyx.hash b/.venv/Lib/site-packages/aiohttp/.hash/_helpers.pyx.hash deleted file mode 100644 index 251b846..0000000 --- a/.venv/Lib/site-packages/aiohttp/.hash/_helpers.pyx.hash +++ /dev/null @@ -1 +0,0 @@ -b6097b7d987440c4fa7237f88d227c89a3ba0dd403dc638ddbe487e0de7f1138 *D:/a/aiohttp/aiohttp/aiohttp/_helpers.pyx diff --git a/.venv/Lib/site-packages/aiohttp/.hash/_http_parser.pyx.hash b/.venv/Lib/site-packages/aiohttp/.hash/_http_parser.pyx.hash deleted file mode 100644 index dec528a..0000000 --- a/.venv/Lib/site-packages/aiohttp/.hash/_http_parser.pyx.hash +++ /dev/null @@ -1 +0,0 @@ -0cf034484f178c9c1d6bcea6d6edc5cabf96ae35359e00344d0d1033c9cff512 *D:/a/aiohttp/aiohttp/aiohttp/_http_parser.pyx diff --git a/.venv/Lib/site-packages/aiohttp/.hash/_http_writer.pyx.hash b/.venv/Lib/site-packages/aiohttp/.hash/_http_writer.pyx.hash deleted file mode 100644 index 11278aa..0000000 --- a/.venv/Lib/site-packages/aiohttp/.hash/_http_writer.pyx.hash +++ /dev/null @@ -1 +0,0 @@ -f0204bcad3b6af1d6476959ef47612ce784b5dd7995b213edf123b8da19ab1a8 *D:/a/aiohttp/aiohttp/aiohttp/_http_writer.pyx diff --git a/.venv/Lib/site-packages/aiohttp/.hash/_websocket.pyx.hash b/.venv/Lib/site-packages/aiohttp/.hash/_websocket.pyx.hash deleted file mode 100644 index 1a3346e..0000000 --- a/.venv/Lib/site-packages/aiohttp/.hash/_websocket.pyx.hash +++ /dev/null @@ -1 +0,0 @@ -a3d27bca2f5cdbe8d3063137754917c610d62af456273e4665fc8bb202506b7f *D:/a/aiohttp/aiohttp/aiohttp/_websocket.pyx diff --git a/.venv/Lib/site-packages/aiohttp/.hash/hdrs.py.hash b/.venv/Lib/site-packages/aiohttp/.hash/hdrs.py.hash deleted file mode 100644 index 7b005e7..0000000 --- a/.venv/Lib/site-packages/aiohttp/.hash/hdrs.py.hash +++ /dev/null @@ -1 +0,0 @@ -ca00e702a602a2df0d310ca3724dabf42ce94eca40397a47927365fb2c48c9b6 *D:/a/aiohttp/aiohttp/aiohttp/hdrs.py diff --git a/.venv/Lib/site-packages/aiohttp/__init__.py b/.venv/Lib/site-packages/aiohttp/__init__.py deleted file mode 100644 index 4bbcef2..0000000 --- a/.venv/Lib/site-packages/aiohttp/__init__.py +++ /dev/null @@ -1,216 +0,0 @@ -__version__ = "3.8.1" - -from typing import Tuple - -from . import hdrs as hdrs -from .client import ( - BaseConnector as BaseConnector, - ClientConnectionError as ClientConnectionError, - ClientConnectorCertificateError as ClientConnectorCertificateError, - ClientConnectorError as ClientConnectorError, - ClientConnectorSSLError as ClientConnectorSSLError, - ClientError as ClientError, - ClientHttpProxyError as ClientHttpProxyError, - ClientOSError as ClientOSError, - ClientPayloadError as ClientPayloadError, - ClientProxyConnectionError as ClientProxyConnectionError, - ClientRequest as ClientRequest, - ClientResponse as ClientResponse, - ClientResponseError as ClientResponseError, - ClientSession as ClientSession, - ClientSSLError as ClientSSLError, - ClientTimeout as ClientTimeout, - ClientWebSocketResponse as ClientWebSocketResponse, - ContentTypeError as ContentTypeError, - Fingerprint as Fingerprint, - InvalidURL as InvalidURL, - NamedPipeConnector as NamedPipeConnector, - RequestInfo as RequestInfo, - ServerConnectionError as ServerConnectionError, - ServerDisconnectedError as ServerDisconnectedError, - ServerFingerprintMismatch as ServerFingerprintMismatch, - ServerTimeoutError as ServerTimeoutError, - TCPConnector as TCPConnector, - TooManyRedirects as TooManyRedirects, - UnixConnector as UnixConnector, - WSServerHandshakeError as WSServerHandshakeError, - request as request, -) -from .cookiejar import CookieJar as CookieJar, DummyCookieJar as DummyCookieJar -from .formdata import FormData as FormData -from .helpers import BasicAuth, ChainMapProxy, ETag -from .http import ( - HttpVersion as HttpVersion, - HttpVersion10 as HttpVersion10, - HttpVersion11 as HttpVersion11, - WebSocketError as WebSocketError, - WSCloseCode as WSCloseCode, - WSMessage as WSMessage, - WSMsgType as WSMsgType, -) -from .multipart import ( - BadContentDispositionHeader as BadContentDispositionHeader, - BadContentDispositionParam as BadContentDispositionParam, - BodyPartReader as BodyPartReader, - MultipartReader as MultipartReader, - MultipartWriter as MultipartWriter, - content_disposition_filename as content_disposition_filename, - parse_content_disposition as parse_content_disposition, -) -from .payload import ( - PAYLOAD_REGISTRY as PAYLOAD_REGISTRY, - AsyncIterablePayload as AsyncIterablePayload, - BufferedReaderPayload as BufferedReaderPayload, - BytesIOPayload as BytesIOPayload, - BytesPayload as BytesPayload, - IOBasePayload as IOBasePayload, - JsonPayload as JsonPayload, - Payload as Payload, - StringIOPayload as StringIOPayload, - StringPayload as StringPayload, - TextIOPayload as TextIOPayload, - get_payload as get_payload, - payload_type as payload_type, -) -from .payload_streamer import streamer as streamer -from .resolver import ( - AsyncResolver as AsyncResolver, - DefaultResolver as DefaultResolver, - ThreadedResolver as ThreadedResolver, -) -from .streams import ( - EMPTY_PAYLOAD as EMPTY_PAYLOAD, - DataQueue as DataQueue, - EofStream as EofStream, - FlowControlDataQueue as FlowControlDataQueue, - StreamReader as StreamReader, -) -from .tracing import ( - TraceConfig as TraceConfig, - TraceConnectionCreateEndParams as TraceConnectionCreateEndParams, - TraceConnectionCreateStartParams as TraceConnectionCreateStartParams, - TraceConnectionQueuedEndParams as TraceConnectionQueuedEndParams, - TraceConnectionQueuedStartParams as TraceConnectionQueuedStartParams, - TraceConnectionReuseconnParams as TraceConnectionReuseconnParams, - TraceDnsCacheHitParams as TraceDnsCacheHitParams, - TraceDnsCacheMissParams as TraceDnsCacheMissParams, - TraceDnsResolveHostEndParams as TraceDnsResolveHostEndParams, - TraceDnsResolveHostStartParams as TraceDnsResolveHostStartParams, - TraceRequestChunkSentParams as TraceRequestChunkSentParams, - TraceRequestEndParams as TraceRequestEndParams, - TraceRequestExceptionParams as TraceRequestExceptionParams, - TraceRequestRedirectParams as TraceRequestRedirectParams, - TraceRequestStartParams as TraceRequestStartParams, - TraceResponseChunkReceivedParams as TraceResponseChunkReceivedParams, -) - -__all__: Tuple[str, ...] = ( - "hdrs", - # client - "BaseConnector", - "ClientConnectionError", - "ClientConnectorCertificateError", - "ClientConnectorError", - "ClientConnectorSSLError", - "ClientError", - "ClientHttpProxyError", - "ClientOSError", - "ClientPayloadError", - "ClientProxyConnectionError", - "ClientResponse", - "ClientRequest", - "ClientResponseError", - "ClientSSLError", - "ClientSession", - "ClientTimeout", - "ClientWebSocketResponse", - "ContentTypeError", - "Fingerprint", - "InvalidURL", - "RequestInfo", - "ServerConnectionError", - "ServerDisconnectedError", - "ServerFingerprintMismatch", - "ServerTimeoutError", - "TCPConnector", - "TooManyRedirects", - "UnixConnector", - "NamedPipeConnector", - "WSServerHandshakeError", - "request", - # cookiejar - "CookieJar", - "DummyCookieJar", - # formdata - "FormData", - # helpers - "BasicAuth", - "ChainMapProxy", - "ETag", - # http - "HttpVersion", - "HttpVersion10", - "HttpVersion11", - "WSMsgType", - "WSCloseCode", - "WSMessage", - "WebSocketError", - # multipart - "BadContentDispositionHeader", - "BadContentDispositionParam", - "BodyPartReader", - "MultipartReader", - "MultipartWriter", - "content_disposition_filename", - "parse_content_disposition", - # payload - "AsyncIterablePayload", - "BufferedReaderPayload", - "BytesIOPayload", - "BytesPayload", - "IOBasePayload", - "JsonPayload", - "PAYLOAD_REGISTRY", - "Payload", - "StringIOPayload", - "StringPayload", - "TextIOPayload", - "get_payload", - "payload_type", - # payload_streamer - "streamer", - # resolver - "AsyncResolver", - "DefaultResolver", - "ThreadedResolver", - # streams - "DataQueue", - "EMPTY_PAYLOAD", - "EofStream", - "FlowControlDataQueue", - "StreamReader", - # tracing - "TraceConfig", - "TraceConnectionCreateEndParams", - "TraceConnectionCreateStartParams", - "TraceConnectionQueuedEndParams", - "TraceConnectionQueuedStartParams", - "TraceConnectionReuseconnParams", - "TraceDnsCacheHitParams", - "TraceDnsCacheMissParams", - "TraceDnsResolveHostEndParams", - "TraceDnsResolveHostStartParams", - "TraceRequestChunkSentParams", - "TraceRequestEndParams", - "TraceRequestExceptionParams", - "TraceRequestRedirectParams", - "TraceRequestStartParams", - "TraceResponseChunkReceivedParams", -) - -try: - from .worker import GunicornUVLoopWebWorker, GunicornWebWorker - - __all__ += ("GunicornWebWorker", "GunicornUVLoopWebWorker") -except ImportError: # pragma: no cover - pass diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/__init__.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index 170028e..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/abc.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/abc.cpython-38.pyc deleted file mode 100644 index 4a7adb9..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/abc.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/base_protocol.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/base_protocol.cpython-38.pyc deleted file mode 100644 index 7d322e5..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/base_protocol.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/client.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/client.cpython-38.pyc deleted file mode 100644 index e26f764..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/client.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/client_exceptions.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/client_exceptions.cpython-38.pyc deleted file mode 100644 index d0e505f..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/client_exceptions.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/client_proto.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/client_proto.cpython-38.pyc deleted file mode 100644 index 6ea335e..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/client_proto.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/client_reqrep.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/client_reqrep.cpython-38.pyc deleted file mode 100644 index c776757..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/client_reqrep.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/client_ws.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/client_ws.cpython-38.pyc deleted file mode 100644 index d5fcf79..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/client_ws.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/connector.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/connector.cpython-38.pyc deleted file mode 100644 index e6ac57c..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/connector.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/cookiejar.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/cookiejar.cpython-38.pyc deleted file mode 100644 index 6b39c0c..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/cookiejar.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/formdata.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/formdata.cpython-38.pyc deleted file mode 100644 index b7e126e..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/formdata.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/hdrs.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/hdrs.cpython-38.pyc deleted file mode 100644 index 668633d..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/hdrs.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/helpers.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/helpers.cpython-38.pyc deleted file mode 100644 index 00ce99e..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/helpers.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/http.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/http.cpython-38.pyc deleted file mode 100644 index 0084bcc..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/http.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/http_exceptions.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/http_exceptions.cpython-38.pyc deleted file mode 100644 index 2aae3e9..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/http_exceptions.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/http_parser.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/http_parser.cpython-38.pyc deleted file mode 100644 index bdfdcbb..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/http_parser.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/http_websocket.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/http_websocket.cpython-38.pyc deleted file mode 100644 index d63958a..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/http_websocket.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/http_writer.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/http_writer.cpython-38.pyc deleted file mode 100644 index 450487d..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/http_writer.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/locks.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/locks.cpython-38.pyc deleted file mode 100644 index d6e82f2..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/locks.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/log.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/log.cpython-38.pyc deleted file mode 100644 index 5494b21..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/log.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/multipart.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/multipart.cpython-38.pyc deleted file mode 100644 index 6020f28..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/multipart.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/payload.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/payload.cpython-38.pyc deleted file mode 100644 index 849e4ab..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/payload.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/payload_streamer.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/payload_streamer.cpython-38.pyc deleted file mode 100644 index 59652f1..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/payload_streamer.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/pytest_plugin.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/pytest_plugin.cpython-38.pyc deleted file mode 100644 index 520d42c..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/pytest_plugin.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/resolver.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/resolver.cpython-38.pyc deleted file mode 100644 index 9c4668c..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/resolver.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/streams.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/streams.cpython-38.pyc deleted file mode 100644 index c3494ad..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/streams.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/tcp_helpers.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/tcp_helpers.cpython-38.pyc deleted file mode 100644 index 2fc68c7..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/tcp_helpers.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/test_utils.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/test_utils.cpython-38.pyc deleted file mode 100644 index f4ea876..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/test_utils.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/tracing.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/tracing.cpython-38.pyc deleted file mode 100644 index f520251..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/tracing.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/typedefs.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/typedefs.cpython-38.pyc deleted file mode 100644 index 6a13d48..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/typedefs.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/web.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/web.cpython-38.pyc deleted file mode 100644 index 90032f5..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/web.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/web_app.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/web_app.cpython-38.pyc deleted file mode 100644 index 5666fcb..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/web_app.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/web_exceptions.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/web_exceptions.cpython-38.pyc deleted file mode 100644 index 4b565de..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/web_exceptions.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/web_fileresponse.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/web_fileresponse.cpython-38.pyc deleted file mode 100644 index 8575961..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/web_fileresponse.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/web_log.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/web_log.cpython-38.pyc deleted file mode 100644 index 6ee55d6..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/web_log.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/web_middlewares.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/web_middlewares.cpython-38.pyc deleted file mode 100644 index 96e3315..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/web_middlewares.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/web_protocol.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/web_protocol.cpython-38.pyc deleted file mode 100644 index f1c6d13..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/web_protocol.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/web_request.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/web_request.cpython-38.pyc deleted file mode 100644 index ba6a0de..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/web_request.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/web_response.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/web_response.cpython-38.pyc deleted file mode 100644 index bbd3249..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/web_response.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/web_routedef.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/web_routedef.cpython-38.pyc deleted file mode 100644 index 308c45a..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/web_routedef.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/web_runner.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/web_runner.cpython-38.pyc deleted file mode 100644 index 7b2dba0..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/web_runner.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/web_server.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/web_server.cpython-38.pyc deleted file mode 100644 index 3ab543c..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/web_server.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/web_urldispatcher.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/web_urldispatcher.cpython-38.pyc deleted file mode 100644 index 85379ed..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/web_urldispatcher.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/web_ws.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/web_ws.cpython-38.pyc deleted file mode 100644 index 908392d..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/web_ws.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/__pycache__/worker.cpython-38.pyc b/.venv/Lib/site-packages/aiohttp/__pycache__/worker.cpython-38.pyc deleted file mode 100644 index fbad1c5..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/__pycache__/worker.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/_cparser.pxd b/.venv/Lib/site-packages/aiohttp/_cparser.pxd deleted file mode 100644 index 165dd61..0000000 --- a/.venv/Lib/site-packages/aiohttp/_cparser.pxd +++ /dev/null @@ -1,190 +0,0 @@ -from libc.stdint cimport ( - int8_t, - int16_t, - int32_t, - int64_t, - uint8_t, - uint16_t, - uint32_t, - uint64_t, -) - - -cdef extern from "../vendor/llhttp/build/llhttp.h": - - struct llhttp__internal_s: - int32_t _index - void* _span_pos0 - void* _span_cb0 - int32_t error - const char* reason - const char* error_pos - void* data - void* _current - uint64_t content_length - uint8_t type - uint8_t method - uint8_t http_major - uint8_t http_minor - uint8_t header_state - uint8_t lenient_flags - uint8_t upgrade - uint8_t finish - uint16_t flags - uint16_t status_code - void* settings - - ctypedef llhttp__internal_s llhttp__internal_t - ctypedef llhttp__internal_t llhttp_t - - ctypedef int (*llhttp_data_cb)(llhttp_t*, const char *at, size_t length) except -1 - ctypedef int (*llhttp_cb)(llhttp_t*) except -1 - - struct llhttp_settings_s: - llhttp_cb on_message_begin - llhttp_data_cb on_url - llhttp_data_cb on_status - llhttp_data_cb on_header_field - llhttp_data_cb on_header_value - llhttp_cb on_headers_complete - llhttp_data_cb on_body - llhttp_cb on_message_complete - llhttp_cb on_chunk_header - llhttp_cb on_chunk_complete - - llhttp_cb on_url_complete - llhttp_cb on_status_complete - llhttp_cb on_header_field_complete - llhttp_cb on_header_value_complete - - ctypedef llhttp_settings_s llhttp_settings_t - - enum llhttp_errno: - HPE_OK, - HPE_INTERNAL, - HPE_STRICT, - HPE_LF_EXPECTED, - HPE_UNEXPECTED_CONTENT_LENGTH, - HPE_CLOSED_CONNECTION, - HPE_INVALID_METHOD, - HPE_INVALID_URL, - HPE_INVALID_CONSTANT, - HPE_INVALID_VERSION, - HPE_INVALID_HEADER_TOKEN, - HPE_INVALID_CONTENT_LENGTH, - HPE_INVALID_CHUNK_SIZE, - HPE_INVALID_STATUS, - HPE_INVALID_EOF_STATE, - HPE_INVALID_TRANSFER_ENCODING, - HPE_CB_MESSAGE_BEGIN, - HPE_CB_HEADERS_COMPLETE, - HPE_CB_MESSAGE_COMPLETE, - HPE_CB_CHUNK_HEADER, - HPE_CB_CHUNK_COMPLETE, - HPE_PAUSED, - HPE_PAUSED_UPGRADE, - HPE_USER - - ctypedef llhttp_errno llhttp_errno_t - - enum llhttp_flags: - F_CONNECTION_KEEP_ALIVE, - F_CONNECTION_CLOSE, - F_CONNECTION_UPGRADE, - F_CHUNKED, - F_UPGRADE, - F_CONTENT_LENGTH, - F_SKIPBODY, - F_TRAILING, - F_TRANSFER_ENCODING - - enum llhttp_lenient_flags: - LENIENT_HEADERS, - LENIENT_CHUNKED_LENGTH - - enum llhttp_type: - HTTP_REQUEST, - HTTP_RESPONSE, - HTTP_BOTH - - enum llhttp_finish_t: - HTTP_FINISH_SAFE, - HTTP_FINISH_SAFE_WITH_CB, - HTTP_FINISH_UNSAFE - - enum llhttp_method: - HTTP_DELETE, - HTTP_GET, - HTTP_HEAD, - HTTP_POST, - HTTP_PUT, - HTTP_CONNECT, - HTTP_OPTIONS, - HTTP_TRACE, - HTTP_COPY, - HTTP_LOCK, - HTTP_MKCOL, - HTTP_MOVE, - HTTP_PROPFIND, - HTTP_PROPPATCH, - HTTP_SEARCH, - HTTP_UNLOCK, - HTTP_BIND, - HTTP_REBIND, - HTTP_UNBIND, - HTTP_ACL, - HTTP_REPORT, - HTTP_MKACTIVITY, - HTTP_CHECKOUT, - HTTP_MERGE, - HTTP_MSEARCH, - HTTP_NOTIFY, - HTTP_SUBSCRIBE, - HTTP_UNSUBSCRIBE, - HTTP_PATCH, - HTTP_PURGE, - HTTP_MKCALENDAR, - HTTP_LINK, - HTTP_UNLINK, - HTTP_SOURCE, - HTTP_PRI, - HTTP_DESCRIBE, - HTTP_ANNOUNCE, - HTTP_SETUP, - HTTP_PLAY, - HTTP_PAUSE, - HTTP_TEARDOWN, - HTTP_GET_PARAMETER, - HTTP_SET_PARAMETER, - HTTP_REDIRECT, - HTTP_RECORD, - HTTP_FLUSH - - ctypedef llhttp_method llhttp_method_t; - - void llhttp_settings_init(llhttp_settings_t* settings) - void llhttp_init(llhttp_t* parser, llhttp_type type, - const llhttp_settings_t* settings) - - llhttp_errno_t llhttp_execute(llhttp_t* parser, const char* data, size_t len) - llhttp_errno_t llhttp_finish(llhttp_t* parser) - - int llhttp_message_needs_eof(const llhttp_t* parser) - - int llhttp_should_keep_alive(const llhttp_t* parser) - - void llhttp_pause(llhttp_t* parser) - void llhttp_resume(llhttp_t* parser) - - void llhttp_resume_after_upgrade(llhttp_t* parser) - - llhttp_errno_t llhttp_get_errno(const llhttp_t* parser) - const char* llhttp_get_error_reason(const llhttp_t* parser) - void llhttp_set_error_reason(llhttp_t* parser, const char* reason) - const char* llhttp_get_error_pos(const llhttp_t* parser) - const char* llhttp_errno_name(llhttp_errno_t err) - - const char* llhttp_method_name(llhttp_method_t method) - - void llhttp_set_lenient_headers(llhttp_t* parser, int enabled) - void llhttp_set_lenient_chunked_length(llhttp_t* parser, int enabled) diff --git a/.venv/Lib/site-packages/aiohttp/_find_header.c b/.venv/Lib/site-packages/aiohttp/_find_header.c deleted file mode 100644 index 012cba3..0000000 --- a/.venv/Lib/site-packages/aiohttp/_find_header.c +++ /dev/null @@ -1,9870 +0,0 @@ -/* The file is autogenerated from aiohttp/hdrs.py -Run ./tools/gen.py to update it after the origin changing. */ - -#include "_find_header.h" - -#define NEXT_CHAR() \ -{ \ - count++; \ - if (count == size) { \ - /* end of search */ \ - return -1; \ - } \ - pchar++; \ - ch = *pchar; \ - last = (count == size -1); \ -} while(0); - -int -find_header(const char *str, int size) -{ - char *pchar = str; - int last; - char ch; - int count = -1; - pchar--; - - - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto A; - case 'a': - if (last) { - return -1; - } - goto A; - case 'C': - if (last) { - return -1; - } - goto C; - case 'c': - if (last) { - return -1; - } - goto C; - case 'D': - if (last) { - return -1; - } - goto D; - case 'd': - if (last) { - return -1; - } - goto D; - case 'E': - if (last) { - return -1; - } - goto E; - case 'e': - if (last) { - return -1; - } - goto E; - case 'F': - if (last) { - return -1; - } - goto F; - case 'f': - if (last) { - return -1; - } - goto F; - case 'H': - if (last) { - return -1; - } - goto H; - case 'h': - if (last) { - return -1; - } - goto H; - case 'I': - if (last) { - return -1; - } - goto I; - case 'i': - if (last) { - return -1; - } - goto I; - case 'K': - if (last) { - return -1; - } - goto K; - case 'k': - if (last) { - return -1; - } - goto K; - case 'L': - if (last) { - return -1; - } - goto L; - case 'l': - if (last) { - return -1; - } - goto L; - case 'M': - if (last) { - return -1; - } - goto M; - case 'm': - if (last) { - return -1; - } - goto M; - case 'O': - if (last) { - return -1; - } - goto O; - case 'o': - if (last) { - return -1; - } - goto O; - case 'P': - if (last) { - return -1; - } - goto P; - case 'p': - if (last) { - return -1; - } - goto P; - case 'R': - if (last) { - return -1; - } - goto R; - case 'r': - if (last) { - return -1; - } - goto R; - case 'S': - if (last) { - return -1; - } - goto S; - case 's': - if (last) { - return -1; - } - goto S; - case 'T': - if (last) { - return -1; - } - goto T; - case 't': - if (last) { - return -1; - } - goto T; - case 'U': - if (last) { - return -1; - } - goto U; - case 'u': - if (last) { - return -1; - } - goto U; - case 'V': - if (last) { - return -1; - } - goto V; - case 'v': - if (last) { - return -1; - } - goto V; - case 'W': - if (last) { - return -1; - } - goto W; - case 'w': - if (last) { - return -1; - } - goto W; - case 'X': - if (last) { - return -1; - } - goto X; - case 'x': - if (last) { - return -1; - } - goto X; - default: - return -1; - } - -A: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto AC; - case 'c': - if (last) { - return -1; - } - goto AC; - case 'G': - if (last) { - return -1; - } - goto AG; - case 'g': - if (last) { - return -1; - } - goto AG; - case 'L': - if (last) { - return -1; - } - goto AL; - case 'l': - if (last) { - return -1; - } - goto AL; - case 'U': - if (last) { - return -1; - } - goto AU; - case 'u': - if (last) { - return -1; - } - goto AU; - default: - return -1; - } - -AC: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto ACC; - case 'c': - if (last) { - return -1; - } - goto ACC; - default: - return -1; - } - -ACC: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto ACCE; - case 'e': - if (last) { - return -1; - } - goto ACCE; - default: - return -1; - } - -ACCE: - NEXT_CHAR(); - switch (ch) { - case 'P': - if (last) { - return -1; - } - goto ACCEP; - case 'p': - if (last) { - return -1; - } - goto ACCEP; - case 'S': - if (last) { - return -1; - } - goto ACCES; - case 's': - if (last) { - return -1; - } - goto ACCES; - default: - return -1; - } - -ACCEP: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return 0; - } - goto ACCEPT; - case 't': - if (last) { - return 0; - } - goto ACCEPT; - default: - return -1; - } - -ACCEPT: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto ACCEPT_; - default: - return -1; - } - -ACCEPT_: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto ACCEPT_C; - case 'c': - if (last) { - return -1; - } - goto ACCEPT_C; - case 'E': - if (last) { - return -1; - } - goto ACCEPT_E; - case 'e': - if (last) { - return -1; - } - goto ACCEPT_E; - case 'L': - if (last) { - return -1; - } - goto ACCEPT_L; - case 'l': - if (last) { - return -1; - } - goto ACCEPT_L; - case 'R': - if (last) { - return -1; - } - goto ACCEPT_R; - case 'r': - if (last) { - return -1; - } - goto ACCEPT_R; - default: - return -1; - } - -ACCEPT_C: - NEXT_CHAR(); - switch (ch) { - case 'H': - if (last) { - return -1; - } - goto ACCEPT_CH; - case 'h': - if (last) { - return -1; - } - goto ACCEPT_CH; - default: - return -1; - } - -ACCEPT_CH: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto ACCEPT_CHA; - case 'a': - if (last) { - return -1; - } - goto ACCEPT_CHA; - default: - return -1; - } - -ACCEPT_CHA: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto ACCEPT_CHAR; - case 'r': - if (last) { - return -1; - } - goto ACCEPT_CHAR; - default: - return -1; - } - -ACCEPT_CHAR: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return -1; - } - goto ACCEPT_CHARS; - case 's': - if (last) { - return -1; - } - goto ACCEPT_CHARS; - default: - return -1; - } - -ACCEPT_CHARS: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto ACCEPT_CHARSE; - case 'e': - if (last) { - return -1; - } - goto ACCEPT_CHARSE; - default: - return -1; - } - -ACCEPT_CHARSE: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return 1; - } - goto ACCEPT_CHARSET; - case 't': - if (last) { - return 1; - } - goto ACCEPT_CHARSET; - default: - return -1; - } - -ACCEPT_E: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto ACCEPT_EN; - case 'n': - if (last) { - return -1; - } - goto ACCEPT_EN; - default: - return -1; - } - -ACCEPT_EN: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto ACCEPT_ENC; - case 'c': - if (last) { - return -1; - } - goto ACCEPT_ENC; - default: - return -1; - } - -ACCEPT_ENC: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto ACCEPT_ENCO; - case 'o': - if (last) { - return -1; - } - goto ACCEPT_ENCO; - default: - return -1; - } - -ACCEPT_ENCO: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return -1; - } - goto ACCEPT_ENCOD; - case 'd': - if (last) { - return -1; - } - goto ACCEPT_ENCOD; - default: - return -1; - } - -ACCEPT_ENCOD: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto ACCEPT_ENCODI; - case 'i': - if (last) { - return -1; - } - goto ACCEPT_ENCODI; - default: - return -1; - } - -ACCEPT_ENCODI: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto ACCEPT_ENCODIN; - case 'n': - if (last) { - return -1; - } - goto ACCEPT_ENCODIN; - default: - return -1; - } - -ACCEPT_ENCODIN: - NEXT_CHAR(); - switch (ch) { - case 'G': - if (last) { - return 2; - } - goto ACCEPT_ENCODING; - case 'g': - if (last) { - return 2; - } - goto ACCEPT_ENCODING; - default: - return -1; - } - -ACCEPT_L: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto ACCEPT_LA; - case 'a': - if (last) { - return -1; - } - goto ACCEPT_LA; - default: - return -1; - } - -ACCEPT_LA: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto ACCEPT_LAN; - case 'n': - if (last) { - return -1; - } - goto ACCEPT_LAN; - default: - return -1; - } - -ACCEPT_LAN: - NEXT_CHAR(); - switch (ch) { - case 'G': - if (last) { - return -1; - } - goto ACCEPT_LANG; - case 'g': - if (last) { - return -1; - } - goto ACCEPT_LANG; - default: - return -1; - } - -ACCEPT_LANG: - NEXT_CHAR(); - switch (ch) { - case 'U': - if (last) { - return -1; - } - goto ACCEPT_LANGU; - case 'u': - if (last) { - return -1; - } - goto ACCEPT_LANGU; - default: - return -1; - } - -ACCEPT_LANGU: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto ACCEPT_LANGUA; - case 'a': - if (last) { - return -1; - } - goto ACCEPT_LANGUA; - default: - return -1; - } - -ACCEPT_LANGUA: - NEXT_CHAR(); - switch (ch) { - case 'G': - if (last) { - return -1; - } - goto ACCEPT_LANGUAG; - case 'g': - if (last) { - return -1; - } - goto ACCEPT_LANGUAG; - default: - return -1; - } - -ACCEPT_LANGUAG: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return 3; - } - goto ACCEPT_LANGUAGE; - case 'e': - if (last) { - return 3; - } - goto ACCEPT_LANGUAGE; - default: - return -1; - } - -ACCEPT_R: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto ACCEPT_RA; - case 'a': - if (last) { - return -1; - } - goto ACCEPT_RA; - default: - return -1; - } - -ACCEPT_RA: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto ACCEPT_RAN; - case 'n': - if (last) { - return -1; - } - goto ACCEPT_RAN; - default: - return -1; - } - -ACCEPT_RAN: - NEXT_CHAR(); - switch (ch) { - case 'G': - if (last) { - return -1; - } - goto ACCEPT_RANG; - case 'g': - if (last) { - return -1; - } - goto ACCEPT_RANG; - default: - return -1; - } - -ACCEPT_RANG: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto ACCEPT_RANGE; - case 'e': - if (last) { - return -1; - } - goto ACCEPT_RANGE; - default: - return -1; - } - -ACCEPT_RANGE: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return 4; - } - goto ACCEPT_RANGES; - case 's': - if (last) { - return 4; - } - goto ACCEPT_RANGES; - default: - return -1; - } - -ACCES: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return -1; - } - goto ACCESS; - case 's': - if (last) { - return -1; - } - goto ACCESS; - default: - return -1; - } - -ACCESS: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto ACCESS_; - default: - return -1; - } - -ACCESS_: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto ACCESS_C; - case 'c': - if (last) { - return -1; - } - goto ACCESS_C; - default: - return -1; - } - -ACCESS_C: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto ACCESS_CO; - case 'o': - if (last) { - return -1; - } - goto ACCESS_CO; - default: - return -1; - } - -ACCESS_CO: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto ACCESS_CON; - case 'n': - if (last) { - return -1; - } - goto ACCESS_CON; - default: - return -1; - } - -ACCESS_CON: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto ACCESS_CONT; - case 't': - if (last) { - return -1; - } - goto ACCESS_CONT; - default: - return -1; - } - -ACCESS_CONT: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto ACCESS_CONTR; - case 'r': - if (last) { - return -1; - } - goto ACCESS_CONTR; - default: - return -1; - } - -ACCESS_CONTR: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto ACCESS_CONTRO; - case 'o': - if (last) { - return -1; - } - goto ACCESS_CONTRO; - default: - return -1; - } - -ACCESS_CONTRO: - NEXT_CHAR(); - switch (ch) { - case 'L': - if (last) { - return -1; - } - goto ACCESS_CONTROL; - case 'l': - if (last) { - return -1; - } - goto ACCESS_CONTROL; - default: - return -1; - } - -ACCESS_CONTROL: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto ACCESS_CONTROL_; - default: - return -1; - } - -ACCESS_CONTROL_: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto ACCESS_CONTROL_A; - case 'a': - if (last) { - return -1; - } - goto ACCESS_CONTROL_A; - case 'E': - if (last) { - return -1; - } - goto ACCESS_CONTROL_E; - case 'e': - if (last) { - return -1; - } - goto ACCESS_CONTROL_E; - case 'M': - if (last) { - return -1; - } - goto ACCESS_CONTROL_M; - case 'm': - if (last) { - return -1; - } - goto ACCESS_CONTROL_M; - case 'R': - if (last) { - return -1; - } - goto ACCESS_CONTROL_R; - case 'r': - if (last) { - return -1; - } - goto ACCESS_CONTROL_R; - default: - return -1; - } - -ACCESS_CONTROL_A: - NEXT_CHAR(); - switch (ch) { - case 'L': - if (last) { - return -1; - } - goto ACCESS_CONTROL_AL; - case 'l': - if (last) { - return -1; - } - goto ACCESS_CONTROL_AL; - default: - return -1; - } - -ACCESS_CONTROL_AL: - NEXT_CHAR(); - switch (ch) { - case 'L': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALL; - case 'l': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALL; - default: - return -1; - } - -ACCESS_CONTROL_ALL: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLO; - case 'o': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLO; - default: - return -1; - } - -ACCESS_CONTROL_ALLO: - NEXT_CHAR(); - switch (ch) { - case 'W': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW; - case 'w': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_C; - case 'c': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_C; - case 'H': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_H; - case 'h': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_H; - case 'M': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_M; - case 'm': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_M; - case 'O': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_O; - case 'o': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_O; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_C: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_CR; - case 'r': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_CR; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_CR: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_CRE; - case 'e': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_CRE; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_CRE: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_CRED; - case 'd': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_CRED; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_CRED: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_CREDE; - case 'e': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_CREDE; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_CREDE: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_CREDEN; - case 'n': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_CREDEN; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_CREDEN: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_CREDENT; - case 't': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_CREDENT; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_CREDENT: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_CREDENTI; - case 'i': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_CREDENTI; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_CREDENTI: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_CREDENTIA; - case 'a': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_CREDENTIA; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_CREDENTIA: - NEXT_CHAR(); - switch (ch) { - case 'L': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_CREDENTIAL; - case 'l': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_CREDENTIAL; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_CREDENTIAL: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return 5; - } - goto ACCESS_CONTROL_ALLOW_CREDENTIALS; - case 's': - if (last) { - return 5; - } - goto ACCESS_CONTROL_ALLOW_CREDENTIALS; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_H: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_HE; - case 'e': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_HE; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_HE: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_HEA; - case 'a': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_HEA; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_HEA: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_HEAD; - case 'd': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_HEAD; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_HEAD: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_HEADE; - case 'e': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_HEADE; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_HEADE: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_HEADER; - case 'r': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_HEADER; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_HEADER: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return 6; - } - goto ACCESS_CONTROL_ALLOW_HEADERS; - case 's': - if (last) { - return 6; - } - goto ACCESS_CONTROL_ALLOW_HEADERS; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_M: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_ME; - case 'e': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_ME; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_ME: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_MET; - case 't': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_MET; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_MET: - NEXT_CHAR(); - switch (ch) { - case 'H': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_METH; - case 'h': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_METH; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_METH: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_METHO; - case 'o': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_METHO; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_METHO: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_METHOD; - case 'd': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_METHOD; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_METHOD: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return 7; - } - goto ACCESS_CONTROL_ALLOW_METHODS; - case 's': - if (last) { - return 7; - } - goto ACCESS_CONTROL_ALLOW_METHODS; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_O: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_OR; - case 'r': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_OR; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_OR: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_ORI; - case 'i': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_ORI; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_ORI: - NEXT_CHAR(); - switch (ch) { - case 'G': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_ORIG; - case 'g': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_ORIG; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_ORIG: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_ORIGI; - case 'i': - if (last) { - return -1; - } - goto ACCESS_CONTROL_ALLOW_ORIGI; - default: - return -1; - } - -ACCESS_CONTROL_ALLOW_ORIGI: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return 8; - } - goto ACCESS_CONTROL_ALLOW_ORIGIN; - case 'n': - if (last) { - return 8; - } - goto ACCESS_CONTROL_ALLOW_ORIGIN; - default: - return -1; - } - -ACCESS_CONTROL_E: - NEXT_CHAR(); - switch (ch) { - case 'X': - if (last) { - return -1; - } - goto ACCESS_CONTROL_EX; - case 'x': - if (last) { - return -1; - } - goto ACCESS_CONTROL_EX; - default: - return -1; - } - -ACCESS_CONTROL_EX: - NEXT_CHAR(); - switch (ch) { - case 'P': - if (last) { - return -1; - } - goto ACCESS_CONTROL_EXP; - case 'p': - if (last) { - return -1; - } - goto ACCESS_CONTROL_EXP; - default: - return -1; - } - -ACCESS_CONTROL_EXP: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto ACCESS_CONTROL_EXPO; - case 'o': - if (last) { - return -1; - } - goto ACCESS_CONTROL_EXPO; - default: - return -1; - } - -ACCESS_CONTROL_EXPO: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return -1; - } - goto ACCESS_CONTROL_EXPOS; - case 's': - if (last) { - return -1; - } - goto ACCESS_CONTROL_EXPOS; - default: - return -1; - } - -ACCESS_CONTROL_EXPOS: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto ACCESS_CONTROL_EXPOSE; - case 'e': - if (last) { - return -1; - } - goto ACCESS_CONTROL_EXPOSE; - default: - return -1; - } - -ACCESS_CONTROL_EXPOSE: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto ACCESS_CONTROL_EXPOSE_; - default: - return -1; - } - -ACCESS_CONTROL_EXPOSE_: - NEXT_CHAR(); - switch (ch) { - case 'H': - if (last) { - return -1; - } - goto ACCESS_CONTROL_EXPOSE_H; - case 'h': - if (last) { - return -1; - } - goto ACCESS_CONTROL_EXPOSE_H; - default: - return -1; - } - -ACCESS_CONTROL_EXPOSE_H: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto ACCESS_CONTROL_EXPOSE_HE; - case 'e': - if (last) { - return -1; - } - goto ACCESS_CONTROL_EXPOSE_HE; - default: - return -1; - } - -ACCESS_CONTROL_EXPOSE_HE: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto ACCESS_CONTROL_EXPOSE_HEA; - case 'a': - if (last) { - return -1; - } - goto ACCESS_CONTROL_EXPOSE_HEA; - default: - return -1; - } - -ACCESS_CONTROL_EXPOSE_HEA: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return -1; - } - goto ACCESS_CONTROL_EXPOSE_HEAD; - case 'd': - if (last) { - return -1; - } - goto ACCESS_CONTROL_EXPOSE_HEAD; - default: - return -1; - } - -ACCESS_CONTROL_EXPOSE_HEAD: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto ACCESS_CONTROL_EXPOSE_HEADE; - case 'e': - if (last) { - return -1; - } - goto ACCESS_CONTROL_EXPOSE_HEADE; - default: - return -1; - } - -ACCESS_CONTROL_EXPOSE_HEADE: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto ACCESS_CONTROL_EXPOSE_HEADER; - case 'r': - if (last) { - return -1; - } - goto ACCESS_CONTROL_EXPOSE_HEADER; - default: - return -1; - } - -ACCESS_CONTROL_EXPOSE_HEADER: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return 9; - } - goto ACCESS_CONTROL_EXPOSE_HEADERS; - case 's': - if (last) { - return 9; - } - goto ACCESS_CONTROL_EXPOSE_HEADERS; - default: - return -1; - } - -ACCESS_CONTROL_M: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto ACCESS_CONTROL_MA; - case 'a': - if (last) { - return -1; - } - goto ACCESS_CONTROL_MA; - default: - return -1; - } - -ACCESS_CONTROL_MA: - NEXT_CHAR(); - switch (ch) { - case 'X': - if (last) { - return -1; - } - goto ACCESS_CONTROL_MAX; - case 'x': - if (last) { - return -1; - } - goto ACCESS_CONTROL_MAX; - default: - return -1; - } - -ACCESS_CONTROL_MAX: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto ACCESS_CONTROL_MAX_; - default: - return -1; - } - -ACCESS_CONTROL_MAX_: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto ACCESS_CONTROL_MAX_A; - case 'a': - if (last) { - return -1; - } - goto ACCESS_CONTROL_MAX_A; - default: - return -1; - } - -ACCESS_CONTROL_MAX_A: - NEXT_CHAR(); - switch (ch) { - case 'G': - if (last) { - return -1; - } - goto ACCESS_CONTROL_MAX_AG; - case 'g': - if (last) { - return -1; - } - goto ACCESS_CONTROL_MAX_AG; - default: - return -1; - } - -ACCESS_CONTROL_MAX_AG: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return 10; - } - goto ACCESS_CONTROL_MAX_AGE; - case 'e': - if (last) { - return 10; - } - goto ACCESS_CONTROL_MAX_AGE; - default: - return -1; - } - -ACCESS_CONTROL_R: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto ACCESS_CONTROL_RE; - case 'e': - if (last) { - return -1; - } - goto ACCESS_CONTROL_RE; - default: - return -1; - } - -ACCESS_CONTROL_RE: - NEXT_CHAR(); - switch (ch) { - case 'Q': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQ; - case 'q': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQ; - default: - return -1; - } - -ACCESS_CONTROL_REQ: - NEXT_CHAR(); - switch (ch) { - case 'U': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQU; - case 'u': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQU; - default: - return -1; - } - -ACCESS_CONTROL_REQU: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUE; - case 'e': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUE; - default: - return -1; - } - -ACCESS_CONTROL_REQUE: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUES; - case 's': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUES; - default: - return -1; - } - -ACCESS_CONTROL_REQUES: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUEST; - case 't': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUEST; - default: - return -1; - } - -ACCESS_CONTROL_REQUEST: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUEST_; - default: - return -1; - } - -ACCESS_CONTROL_REQUEST_: - NEXT_CHAR(); - switch (ch) { - case 'H': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUEST_H; - case 'h': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUEST_H; - case 'M': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUEST_M; - case 'm': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUEST_M; - default: - return -1; - } - -ACCESS_CONTROL_REQUEST_H: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUEST_HE; - case 'e': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUEST_HE; - default: - return -1; - } - -ACCESS_CONTROL_REQUEST_HE: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUEST_HEA; - case 'a': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUEST_HEA; - default: - return -1; - } - -ACCESS_CONTROL_REQUEST_HEA: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUEST_HEAD; - case 'd': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUEST_HEAD; - default: - return -1; - } - -ACCESS_CONTROL_REQUEST_HEAD: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUEST_HEADE; - case 'e': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUEST_HEADE; - default: - return -1; - } - -ACCESS_CONTROL_REQUEST_HEADE: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUEST_HEADER; - case 'r': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUEST_HEADER; - default: - return -1; - } - -ACCESS_CONTROL_REQUEST_HEADER: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return 11; - } - goto ACCESS_CONTROL_REQUEST_HEADERS; - case 's': - if (last) { - return 11; - } - goto ACCESS_CONTROL_REQUEST_HEADERS; - default: - return -1; - } - -ACCESS_CONTROL_REQUEST_M: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUEST_ME; - case 'e': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUEST_ME; - default: - return -1; - } - -ACCESS_CONTROL_REQUEST_ME: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUEST_MET; - case 't': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUEST_MET; - default: - return -1; - } - -ACCESS_CONTROL_REQUEST_MET: - NEXT_CHAR(); - switch (ch) { - case 'H': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUEST_METH; - case 'h': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUEST_METH; - default: - return -1; - } - -ACCESS_CONTROL_REQUEST_METH: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUEST_METHO; - case 'o': - if (last) { - return -1; - } - goto ACCESS_CONTROL_REQUEST_METHO; - default: - return -1; - } - -ACCESS_CONTROL_REQUEST_METHO: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return 12; - } - goto ACCESS_CONTROL_REQUEST_METHOD; - case 'd': - if (last) { - return 12; - } - goto ACCESS_CONTROL_REQUEST_METHOD; - default: - return -1; - } - -AG: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return 13; - } - goto AGE; - case 'e': - if (last) { - return 13; - } - goto AGE; - default: - return -1; - } - -AL: - NEXT_CHAR(); - switch (ch) { - case 'L': - if (last) { - return -1; - } - goto ALL; - case 'l': - if (last) { - return -1; - } - goto ALL; - default: - return -1; - } - -ALL: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto ALLO; - case 'o': - if (last) { - return -1; - } - goto ALLO; - default: - return -1; - } - -ALLO: - NEXT_CHAR(); - switch (ch) { - case 'W': - if (last) { - return 14; - } - goto ALLOW; - case 'w': - if (last) { - return 14; - } - goto ALLOW; - default: - return -1; - } - -AU: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto AUT; - case 't': - if (last) { - return -1; - } - goto AUT; - default: - return -1; - } - -AUT: - NEXT_CHAR(); - switch (ch) { - case 'H': - if (last) { - return -1; - } - goto AUTH; - case 'h': - if (last) { - return -1; - } - goto AUTH; - default: - return -1; - } - -AUTH: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto AUTHO; - case 'o': - if (last) { - return -1; - } - goto AUTHO; - default: - return -1; - } - -AUTHO: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto AUTHOR; - case 'r': - if (last) { - return -1; - } - goto AUTHOR; - default: - return -1; - } - -AUTHOR: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto AUTHORI; - case 'i': - if (last) { - return -1; - } - goto AUTHORI; - default: - return -1; - } - -AUTHORI: - NEXT_CHAR(); - switch (ch) { - case 'Z': - if (last) { - return -1; - } - goto AUTHORIZ; - case 'z': - if (last) { - return -1; - } - goto AUTHORIZ; - default: - return -1; - } - -AUTHORIZ: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto AUTHORIZA; - case 'a': - if (last) { - return -1; - } - goto AUTHORIZA; - default: - return -1; - } - -AUTHORIZA: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto AUTHORIZAT; - case 't': - if (last) { - return -1; - } - goto AUTHORIZAT; - default: - return -1; - } - -AUTHORIZAT: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto AUTHORIZATI; - case 'i': - if (last) { - return -1; - } - goto AUTHORIZATI; - default: - return -1; - } - -AUTHORIZATI: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto AUTHORIZATIO; - case 'o': - if (last) { - return -1; - } - goto AUTHORIZATIO; - default: - return -1; - } - -AUTHORIZATIO: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return 15; - } - goto AUTHORIZATION; - case 'n': - if (last) { - return 15; - } - goto AUTHORIZATION; - default: - return -1; - } - -C: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto CA; - case 'a': - if (last) { - return -1; - } - goto CA; - case 'O': - if (last) { - return -1; - } - goto CO; - case 'o': - if (last) { - return -1; - } - goto CO; - default: - return -1; - } - -CA: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto CAC; - case 'c': - if (last) { - return -1; - } - goto CAC; - default: - return -1; - } - -CAC: - NEXT_CHAR(); - switch (ch) { - case 'H': - if (last) { - return -1; - } - goto CACH; - case 'h': - if (last) { - return -1; - } - goto CACH; - default: - return -1; - } - -CACH: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto CACHE; - case 'e': - if (last) { - return -1; - } - goto CACHE; - default: - return -1; - } - -CACHE: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto CACHE_; - default: - return -1; - } - -CACHE_: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto CACHE_C; - case 'c': - if (last) { - return -1; - } - goto CACHE_C; - default: - return -1; - } - -CACHE_C: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto CACHE_CO; - case 'o': - if (last) { - return -1; - } - goto CACHE_CO; - default: - return -1; - } - -CACHE_CO: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto CACHE_CON; - case 'n': - if (last) { - return -1; - } - goto CACHE_CON; - default: - return -1; - } - -CACHE_CON: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto CACHE_CONT; - case 't': - if (last) { - return -1; - } - goto CACHE_CONT; - default: - return -1; - } - -CACHE_CONT: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto CACHE_CONTR; - case 'r': - if (last) { - return -1; - } - goto CACHE_CONTR; - default: - return -1; - } - -CACHE_CONTR: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto CACHE_CONTRO; - case 'o': - if (last) { - return -1; - } - goto CACHE_CONTRO; - default: - return -1; - } - -CACHE_CONTRO: - NEXT_CHAR(); - switch (ch) { - case 'L': - if (last) { - return 16; - } - goto CACHE_CONTROL; - case 'l': - if (last) { - return 16; - } - goto CACHE_CONTROL; - default: - return -1; - } - -CO: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto CON; - case 'n': - if (last) { - return -1; - } - goto CON; - case 'O': - if (last) { - return -1; - } - goto COO; - case 'o': - if (last) { - return -1; - } - goto COO; - default: - return -1; - } - -CON: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto CONN; - case 'n': - if (last) { - return -1; - } - goto CONN; - case 'T': - if (last) { - return -1; - } - goto CONT; - case 't': - if (last) { - return -1; - } - goto CONT; - default: - return -1; - } - -CONN: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto CONNE; - case 'e': - if (last) { - return -1; - } - goto CONNE; - default: - return -1; - } - -CONNE: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto CONNEC; - case 'c': - if (last) { - return -1; - } - goto CONNEC; - default: - return -1; - } - -CONNEC: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto CONNECT; - case 't': - if (last) { - return -1; - } - goto CONNECT; - default: - return -1; - } - -CONNECT: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto CONNECTI; - case 'i': - if (last) { - return -1; - } - goto CONNECTI; - default: - return -1; - } - -CONNECTI: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto CONNECTIO; - case 'o': - if (last) { - return -1; - } - goto CONNECTIO; - default: - return -1; - } - -CONNECTIO: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return 17; - } - goto CONNECTION; - case 'n': - if (last) { - return 17; - } - goto CONNECTION; - default: - return -1; - } - -CONT: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto CONTE; - case 'e': - if (last) { - return -1; - } - goto CONTE; - default: - return -1; - } - -CONTE: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto CONTEN; - case 'n': - if (last) { - return -1; - } - goto CONTEN; - default: - return -1; - } - -CONTEN: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto CONTENT; - case 't': - if (last) { - return -1; - } - goto CONTENT; - default: - return -1; - } - -CONTENT: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto CONTENT_; - default: - return -1; - } - -CONTENT_: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return -1; - } - goto CONTENT_D; - case 'd': - if (last) { - return -1; - } - goto CONTENT_D; - case 'E': - if (last) { - return -1; - } - goto CONTENT_E; - case 'e': - if (last) { - return -1; - } - goto CONTENT_E; - case 'L': - if (last) { - return -1; - } - goto CONTENT_L; - case 'l': - if (last) { - return -1; - } - goto CONTENT_L; - case 'M': - if (last) { - return -1; - } - goto CONTENT_M; - case 'm': - if (last) { - return -1; - } - goto CONTENT_M; - case 'R': - if (last) { - return -1; - } - goto CONTENT_R; - case 'r': - if (last) { - return -1; - } - goto CONTENT_R; - case 'T': - if (last) { - return -1; - } - goto CONTENT_T; - case 't': - if (last) { - return -1; - } - goto CONTENT_T; - default: - return -1; - } - -CONTENT_D: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto CONTENT_DI; - case 'i': - if (last) { - return -1; - } - goto CONTENT_DI; - default: - return -1; - } - -CONTENT_DI: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return -1; - } - goto CONTENT_DIS; - case 's': - if (last) { - return -1; - } - goto CONTENT_DIS; - default: - return -1; - } - -CONTENT_DIS: - NEXT_CHAR(); - switch (ch) { - case 'P': - if (last) { - return -1; - } - goto CONTENT_DISP; - case 'p': - if (last) { - return -1; - } - goto CONTENT_DISP; - default: - return -1; - } - -CONTENT_DISP: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto CONTENT_DISPO; - case 'o': - if (last) { - return -1; - } - goto CONTENT_DISPO; - default: - return -1; - } - -CONTENT_DISPO: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return -1; - } - goto CONTENT_DISPOS; - case 's': - if (last) { - return -1; - } - goto CONTENT_DISPOS; - default: - return -1; - } - -CONTENT_DISPOS: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto CONTENT_DISPOSI; - case 'i': - if (last) { - return -1; - } - goto CONTENT_DISPOSI; - default: - return -1; - } - -CONTENT_DISPOSI: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto CONTENT_DISPOSIT; - case 't': - if (last) { - return -1; - } - goto CONTENT_DISPOSIT; - default: - return -1; - } - -CONTENT_DISPOSIT: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto CONTENT_DISPOSITI; - case 'i': - if (last) { - return -1; - } - goto CONTENT_DISPOSITI; - default: - return -1; - } - -CONTENT_DISPOSITI: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto CONTENT_DISPOSITIO; - case 'o': - if (last) { - return -1; - } - goto CONTENT_DISPOSITIO; - default: - return -1; - } - -CONTENT_DISPOSITIO: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return 18; - } - goto CONTENT_DISPOSITION; - case 'n': - if (last) { - return 18; - } - goto CONTENT_DISPOSITION; - default: - return -1; - } - -CONTENT_E: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto CONTENT_EN; - case 'n': - if (last) { - return -1; - } - goto CONTENT_EN; - default: - return -1; - } - -CONTENT_EN: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto CONTENT_ENC; - case 'c': - if (last) { - return -1; - } - goto CONTENT_ENC; - default: - return -1; - } - -CONTENT_ENC: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto CONTENT_ENCO; - case 'o': - if (last) { - return -1; - } - goto CONTENT_ENCO; - default: - return -1; - } - -CONTENT_ENCO: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return -1; - } - goto CONTENT_ENCOD; - case 'd': - if (last) { - return -1; - } - goto CONTENT_ENCOD; - default: - return -1; - } - -CONTENT_ENCOD: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto CONTENT_ENCODI; - case 'i': - if (last) { - return -1; - } - goto CONTENT_ENCODI; - default: - return -1; - } - -CONTENT_ENCODI: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto CONTENT_ENCODIN; - case 'n': - if (last) { - return -1; - } - goto CONTENT_ENCODIN; - default: - return -1; - } - -CONTENT_ENCODIN: - NEXT_CHAR(); - switch (ch) { - case 'G': - if (last) { - return 19; - } - goto CONTENT_ENCODING; - case 'g': - if (last) { - return 19; - } - goto CONTENT_ENCODING; - default: - return -1; - } - -CONTENT_L: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto CONTENT_LA; - case 'a': - if (last) { - return -1; - } - goto CONTENT_LA; - case 'E': - if (last) { - return -1; - } - goto CONTENT_LE; - case 'e': - if (last) { - return -1; - } - goto CONTENT_LE; - case 'O': - if (last) { - return -1; - } - goto CONTENT_LO; - case 'o': - if (last) { - return -1; - } - goto CONTENT_LO; - default: - return -1; - } - -CONTENT_LA: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto CONTENT_LAN; - case 'n': - if (last) { - return -1; - } - goto CONTENT_LAN; - default: - return -1; - } - -CONTENT_LAN: - NEXT_CHAR(); - switch (ch) { - case 'G': - if (last) { - return -1; - } - goto CONTENT_LANG; - case 'g': - if (last) { - return -1; - } - goto CONTENT_LANG; - default: - return -1; - } - -CONTENT_LANG: - NEXT_CHAR(); - switch (ch) { - case 'U': - if (last) { - return -1; - } - goto CONTENT_LANGU; - case 'u': - if (last) { - return -1; - } - goto CONTENT_LANGU; - default: - return -1; - } - -CONTENT_LANGU: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto CONTENT_LANGUA; - case 'a': - if (last) { - return -1; - } - goto CONTENT_LANGUA; - default: - return -1; - } - -CONTENT_LANGUA: - NEXT_CHAR(); - switch (ch) { - case 'G': - if (last) { - return -1; - } - goto CONTENT_LANGUAG; - case 'g': - if (last) { - return -1; - } - goto CONTENT_LANGUAG; - default: - return -1; - } - -CONTENT_LANGUAG: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return 20; - } - goto CONTENT_LANGUAGE; - case 'e': - if (last) { - return 20; - } - goto CONTENT_LANGUAGE; - default: - return -1; - } - -CONTENT_LE: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto CONTENT_LEN; - case 'n': - if (last) { - return -1; - } - goto CONTENT_LEN; - default: - return -1; - } - -CONTENT_LEN: - NEXT_CHAR(); - switch (ch) { - case 'G': - if (last) { - return -1; - } - goto CONTENT_LENG; - case 'g': - if (last) { - return -1; - } - goto CONTENT_LENG; - default: - return -1; - } - -CONTENT_LENG: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto CONTENT_LENGT; - case 't': - if (last) { - return -1; - } - goto CONTENT_LENGT; - default: - return -1; - } - -CONTENT_LENGT: - NEXT_CHAR(); - switch (ch) { - case 'H': - if (last) { - return 21; - } - goto CONTENT_LENGTH; - case 'h': - if (last) { - return 21; - } - goto CONTENT_LENGTH; - default: - return -1; - } - -CONTENT_LO: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto CONTENT_LOC; - case 'c': - if (last) { - return -1; - } - goto CONTENT_LOC; - default: - return -1; - } - -CONTENT_LOC: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto CONTENT_LOCA; - case 'a': - if (last) { - return -1; - } - goto CONTENT_LOCA; - default: - return -1; - } - -CONTENT_LOCA: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto CONTENT_LOCAT; - case 't': - if (last) { - return -1; - } - goto CONTENT_LOCAT; - default: - return -1; - } - -CONTENT_LOCAT: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto CONTENT_LOCATI; - case 'i': - if (last) { - return -1; - } - goto CONTENT_LOCATI; - default: - return -1; - } - -CONTENT_LOCATI: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto CONTENT_LOCATIO; - case 'o': - if (last) { - return -1; - } - goto CONTENT_LOCATIO; - default: - return -1; - } - -CONTENT_LOCATIO: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return 22; - } - goto CONTENT_LOCATION; - case 'n': - if (last) { - return 22; - } - goto CONTENT_LOCATION; - default: - return -1; - } - -CONTENT_M: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return -1; - } - goto CONTENT_MD; - case 'd': - if (last) { - return -1; - } - goto CONTENT_MD; - default: - return -1; - } - -CONTENT_MD: - NEXT_CHAR(); - switch (ch) { - case '5': - if (last) { - return 23; - } - goto CONTENT_MD5; - default: - return -1; - } - -CONTENT_R: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto CONTENT_RA; - case 'a': - if (last) { - return -1; - } - goto CONTENT_RA; - default: - return -1; - } - -CONTENT_RA: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto CONTENT_RAN; - case 'n': - if (last) { - return -1; - } - goto CONTENT_RAN; - default: - return -1; - } - -CONTENT_RAN: - NEXT_CHAR(); - switch (ch) { - case 'G': - if (last) { - return -1; - } - goto CONTENT_RANG; - case 'g': - if (last) { - return -1; - } - goto CONTENT_RANG; - default: - return -1; - } - -CONTENT_RANG: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return 24; - } - goto CONTENT_RANGE; - case 'e': - if (last) { - return 24; - } - goto CONTENT_RANGE; - default: - return -1; - } - -CONTENT_T: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto CONTENT_TR; - case 'r': - if (last) { - return -1; - } - goto CONTENT_TR; - case 'Y': - if (last) { - return -1; - } - goto CONTENT_TY; - case 'y': - if (last) { - return -1; - } - goto CONTENT_TY; - default: - return -1; - } - -CONTENT_TR: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto CONTENT_TRA; - case 'a': - if (last) { - return -1; - } - goto CONTENT_TRA; - default: - return -1; - } - -CONTENT_TRA: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto CONTENT_TRAN; - case 'n': - if (last) { - return -1; - } - goto CONTENT_TRAN; - default: - return -1; - } - -CONTENT_TRAN: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return -1; - } - goto CONTENT_TRANS; - case 's': - if (last) { - return -1; - } - goto CONTENT_TRANS; - default: - return -1; - } - -CONTENT_TRANS: - NEXT_CHAR(); - switch (ch) { - case 'F': - if (last) { - return -1; - } - goto CONTENT_TRANSF; - case 'f': - if (last) { - return -1; - } - goto CONTENT_TRANSF; - default: - return -1; - } - -CONTENT_TRANSF: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto CONTENT_TRANSFE; - case 'e': - if (last) { - return -1; - } - goto CONTENT_TRANSFE; - default: - return -1; - } - -CONTENT_TRANSFE: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto CONTENT_TRANSFER; - case 'r': - if (last) { - return -1; - } - goto CONTENT_TRANSFER; - default: - return -1; - } - -CONTENT_TRANSFER: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto CONTENT_TRANSFER_; - default: - return -1; - } - -CONTENT_TRANSFER_: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto CONTENT_TRANSFER_E; - case 'e': - if (last) { - return -1; - } - goto CONTENT_TRANSFER_E; - default: - return -1; - } - -CONTENT_TRANSFER_E: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto CONTENT_TRANSFER_EN; - case 'n': - if (last) { - return -1; - } - goto CONTENT_TRANSFER_EN; - default: - return -1; - } - -CONTENT_TRANSFER_EN: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto CONTENT_TRANSFER_ENC; - case 'c': - if (last) { - return -1; - } - goto CONTENT_TRANSFER_ENC; - default: - return -1; - } - -CONTENT_TRANSFER_ENC: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto CONTENT_TRANSFER_ENCO; - case 'o': - if (last) { - return -1; - } - goto CONTENT_TRANSFER_ENCO; - default: - return -1; - } - -CONTENT_TRANSFER_ENCO: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return -1; - } - goto CONTENT_TRANSFER_ENCOD; - case 'd': - if (last) { - return -1; - } - goto CONTENT_TRANSFER_ENCOD; - default: - return -1; - } - -CONTENT_TRANSFER_ENCOD: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto CONTENT_TRANSFER_ENCODI; - case 'i': - if (last) { - return -1; - } - goto CONTENT_TRANSFER_ENCODI; - default: - return -1; - } - -CONTENT_TRANSFER_ENCODI: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto CONTENT_TRANSFER_ENCODIN; - case 'n': - if (last) { - return -1; - } - goto CONTENT_TRANSFER_ENCODIN; - default: - return -1; - } - -CONTENT_TRANSFER_ENCODIN: - NEXT_CHAR(); - switch (ch) { - case 'G': - if (last) { - return 25; - } - goto CONTENT_TRANSFER_ENCODING; - case 'g': - if (last) { - return 25; - } - goto CONTENT_TRANSFER_ENCODING; - default: - return -1; - } - -CONTENT_TY: - NEXT_CHAR(); - switch (ch) { - case 'P': - if (last) { - return -1; - } - goto CONTENT_TYP; - case 'p': - if (last) { - return -1; - } - goto CONTENT_TYP; - default: - return -1; - } - -CONTENT_TYP: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return 26; - } - goto CONTENT_TYPE; - case 'e': - if (last) { - return 26; - } - goto CONTENT_TYPE; - default: - return -1; - } - -COO: - NEXT_CHAR(); - switch (ch) { - case 'K': - if (last) { - return -1; - } - goto COOK; - case 'k': - if (last) { - return -1; - } - goto COOK; - default: - return -1; - } - -COOK: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto COOKI; - case 'i': - if (last) { - return -1; - } - goto COOKI; - default: - return -1; - } - -COOKI: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return 27; - } - goto COOKIE; - case 'e': - if (last) { - return 27; - } - goto COOKIE; - default: - return -1; - } - -D: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto DA; - case 'a': - if (last) { - return -1; - } - goto DA; - case 'E': - if (last) { - return -1; - } - goto DE; - case 'e': - if (last) { - return -1; - } - goto DE; - case 'I': - if (last) { - return -1; - } - goto DI; - case 'i': - if (last) { - return -1; - } - goto DI; - default: - return -1; - } - -DA: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto DAT; - case 't': - if (last) { - return -1; - } - goto DAT; - default: - return -1; - } - -DAT: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return 28; - } - goto DATE; - case 'e': - if (last) { - return 28; - } - goto DATE; - default: - return -1; - } - -DE: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return -1; - } - goto DES; - case 's': - if (last) { - return -1; - } - goto DES; - default: - return -1; - } - -DES: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto DEST; - case 't': - if (last) { - return -1; - } - goto DEST; - default: - return -1; - } - -DEST: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto DESTI; - case 'i': - if (last) { - return -1; - } - goto DESTI; - default: - return -1; - } - -DESTI: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto DESTIN; - case 'n': - if (last) { - return -1; - } - goto DESTIN; - default: - return -1; - } - -DESTIN: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto DESTINA; - case 'a': - if (last) { - return -1; - } - goto DESTINA; - default: - return -1; - } - -DESTINA: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto DESTINAT; - case 't': - if (last) { - return -1; - } - goto DESTINAT; - default: - return -1; - } - -DESTINAT: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto DESTINATI; - case 'i': - if (last) { - return -1; - } - goto DESTINATI; - default: - return -1; - } - -DESTINATI: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto DESTINATIO; - case 'o': - if (last) { - return -1; - } - goto DESTINATIO; - default: - return -1; - } - -DESTINATIO: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return 29; - } - goto DESTINATION; - case 'n': - if (last) { - return 29; - } - goto DESTINATION; - default: - return -1; - } - -DI: - NEXT_CHAR(); - switch (ch) { - case 'G': - if (last) { - return -1; - } - goto DIG; - case 'g': - if (last) { - return -1; - } - goto DIG; - default: - return -1; - } - -DIG: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto DIGE; - case 'e': - if (last) { - return -1; - } - goto DIGE; - default: - return -1; - } - -DIGE: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return -1; - } - goto DIGES; - case 's': - if (last) { - return -1; - } - goto DIGES; - default: - return -1; - } - -DIGES: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return 30; - } - goto DIGEST; - case 't': - if (last) { - return 30; - } - goto DIGEST; - default: - return -1; - } - -E: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto ET; - case 't': - if (last) { - return -1; - } - goto ET; - case 'X': - if (last) { - return -1; - } - goto EX; - case 'x': - if (last) { - return -1; - } - goto EX; - default: - return -1; - } - -ET: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto ETA; - case 'a': - if (last) { - return -1; - } - goto ETA; - default: - return -1; - } - -ETA: - NEXT_CHAR(); - switch (ch) { - case 'G': - if (last) { - return 31; - } - goto ETAG; - case 'g': - if (last) { - return 31; - } - goto ETAG; - default: - return -1; - } - -EX: - NEXT_CHAR(); - switch (ch) { - case 'P': - if (last) { - return -1; - } - goto EXP; - case 'p': - if (last) { - return -1; - } - goto EXP; - default: - return -1; - } - -EXP: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto EXPE; - case 'e': - if (last) { - return -1; - } - goto EXPE; - case 'I': - if (last) { - return -1; - } - goto EXPI; - case 'i': - if (last) { - return -1; - } - goto EXPI; - default: - return -1; - } - -EXPE: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto EXPEC; - case 'c': - if (last) { - return -1; - } - goto EXPEC; - default: - return -1; - } - -EXPEC: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return 32; - } - goto EXPECT; - case 't': - if (last) { - return 32; - } - goto EXPECT; - default: - return -1; - } - -EXPI: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto EXPIR; - case 'r': - if (last) { - return -1; - } - goto EXPIR; - default: - return -1; - } - -EXPIR: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto EXPIRE; - case 'e': - if (last) { - return -1; - } - goto EXPIRE; - default: - return -1; - } - -EXPIRE: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return 33; - } - goto EXPIRES; - case 's': - if (last) { - return 33; - } - goto EXPIRES; - default: - return -1; - } - -F: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto FO; - case 'o': - if (last) { - return -1; - } - goto FO; - case 'R': - if (last) { - return -1; - } - goto FR; - case 'r': - if (last) { - return -1; - } - goto FR; - default: - return -1; - } - -FO: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto FOR; - case 'r': - if (last) { - return -1; - } - goto FOR; - default: - return -1; - } - -FOR: - NEXT_CHAR(); - switch (ch) { - case 'W': - if (last) { - return -1; - } - goto FORW; - case 'w': - if (last) { - return -1; - } - goto FORW; - default: - return -1; - } - -FORW: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto FORWA; - case 'a': - if (last) { - return -1; - } - goto FORWA; - default: - return -1; - } - -FORWA: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto FORWAR; - case 'r': - if (last) { - return -1; - } - goto FORWAR; - default: - return -1; - } - -FORWAR: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return -1; - } - goto FORWARD; - case 'd': - if (last) { - return -1; - } - goto FORWARD; - default: - return -1; - } - -FORWARD: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto FORWARDE; - case 'e': - if (last) { - return -1; - } - goto FORWARDE; - default: - return -1; - } - -FORWARDE: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return 34; - } - goto FORWARDED; - case 'd': - if (last) { - return 34; - } - goto FORWARDED; - default: - return -1; - } - -FR: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto FRO; - case 'o': - if (last) { - return -1; - } - goto FRO; - default: - return -1; - } - -FRO: - NEXT_CHAR(); - switch (ch) { - case 'M': - if (last) { - return 35; - } - goto FROM; - case 'm': - if (last) { - return 35; - } - goto FROM; - default: - return -1; - } - -H: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto HO; - case 'o': - if (last) { - return -1; - } - goto HO; - default: - return -1; - } - -HO: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return -1; - } - goto HOS; - case 's': - if (last) { - return -1; - } - goto HOS; - default: - return -1; - } - -HOS: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return 36; - } - goto HOST; - case 't': - if (last) { - return 36; - } - goto HOST; - default: - return -1; - } - -I: - NEXT_CHAR(); - switch (ch) { - case 'F': - if (last) { - return -1; - } - goto IF; - case 'f': - if (last) { - return -1; - } - goto IF; - default: - return -1; - } - -IF: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto IF_; - default: - return -1; - } - -IF_: - NEXT_CHAR(); - switch (ch) { - case 'M': - if (last) { - return -1; - } - goto IF_M; - case 'm': - if (last) { - return -1; - } - goto IF_M; - case 'N': - if (last) { - return -1; - } - goto IF_N; - case 'n': - if (last) { - return -1; - } - goto IF_N; - case 'R': - if (last) { - return -1; - } - goto IF_R; - case 'r': - if (last) { - return -1; - } - goto IF_R; - case 'U': - if (last) { - return -1; - } - goto IF_U; - case 'u': - if (last) { - return -1; - } - goto IF_U; - default: - return -1; - } - -IF_M: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto IF_MA; - case 'a': - if (last) { - return -1; - } - goto IF_MA; - case 'O': - if (last) { - return -1; - } - goto IF_MO; - case 'o': - if (last) { - return -1; - } - goto IF_MO; - default: - return -1; - } - -IF_MA: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto IF_MAT; - case 't': - if (last) { - return -1; - } - goto IF_MAT; - default: - return -1; - } - -IF_MAT: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto IF_MATC; - case 'c': - if (last) { - return -1; - } - goto IF_MATC; - default: - return -1; - } - -IF_MATC: - NEXT_CHAR(); - switch (ch) { - case 'H': - if (last) { - return 37; - } - goto IF_MATCH; - case 'h': - if (last) { - return 37; - } - goto IF_MATCH; - default: - return -1; - } - -IF_MO: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return -1; - } - goto IF_MOD; - case 'd': - if (last) { - return -1; - } - goto IF_MOD; - default: - return -1; - } - -IF_MOD: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto IF_MODI; - case 'i': - if (last) { - return -1; - } - goto IF_MODI; - default: - return -1; - } - -IF_MODI: - NEXT_CHAR(); - switch (ch) { - case 'F': - if (last) { - return -1; - } - goto IF_MODIF; - case 'f': - if (last) { - return -1; - } - goto IF_MODIF; - default: - return -1; - } - -IF_MODIF: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto IF_MODIFI; - case 'i': - if (last) { - return -1; - } - goto IF_MODIFI; - default: - return -1; - } - -IF_MODIFI: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto IF_MODIFIE; - case 'e': - if (last) { - return -1; - } - goto IF_MODIFIE; - default: - return -1; - } - -IF_MODIFIE: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return -1; - } - goto IF_MODIFIED; - case 'd': - if (last) { - return -1; - } - goto IF_MODIFIED; - default: - return -1; - } - -IF_MODIFIED: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto IF_MODIFIED_; - default: - return -1; - } - -IF_MODIFIED_: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return -1; - } - goto IF_MODIFIED_S; - case 's': - if (last) { - return -1; - } - goto IF_MODIFIED_S; - default: - return -1; - } - -IF_MODIFIED_S: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto IF_MODIFIED_SI; - case 'i': - if (last) { - return -1; - } - goto IF_MODIFIED_SI; - default: - return -1; - } - -IF_MODIFIED_SI: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto IF_MODIFIED_SIN; - case 'n': - if (last) { - return -1; - } - goto IF_MODIFIED_SIN; - default: - return -1; - } - -IF_MODIFIED_SIN: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto IF_MODIFIED_SINC; - case 'c': - if (last) { - return -1; - } - goto IF_MODIFIED_SINC; - default: - return -1; - } - -IF_MODIFIED_SINC: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return 38; - } - goto IF_MODIFIED_SINCE; - case 'e': - if (last) { - return 38; - } - goto IF_MODIFIED_SINCE; - default: - return -1; - } - -IF_N: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto IF_NO; - case 'o': - if (last) { - return -1; - } - goto IF_NO; - default: - return -1; - } - -IF_NO: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto IF_NON; - case 'n': - if (last) { - return -1; - } - goto IF_NON; - default: - return -1; - } - -IF_NON: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto IF_NONE; - case 'e': - if (last) { - return -1; - } - goto IF_NONE; - default: - return -1; - } - -IF_NONE: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto IF_NONE_; - default: - return -1; - } - -IF_NONE_: - NEXT_CHAR(); - switch (ch) { - case 'M': - if (last) { - return -1; - } - goto IF_NONE_M; - case 'm': - if (last) { - return -1; - } - goto IF_NONE_M; - default: - return -1; - } - -IF_NONE_M: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto IF_NONE_MA; - case 'a': - if (last) { - return -1; - } - goto IF_NONE_MA; - default: - return -1; - } - -IF_NONE_MA: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto IF_NONE_MAT; - case 't': - if (last) { - return -1; - } - goto IF_NONE_MAT; - default: - return -1; - } - -IF_NONE_MAT: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto IF_NONE_MATC; - case 'c': - if (last) { - return -1; - } - goto IF_NONE_MATC; - default: - return -1; - } - -IF_NONE_MATC: - NEXT_CHAR(); - switch (ch) { - case 'H': - if (last) { - return 39; - } - goto IF_NONE_MATCH; - case 'h': - if (last) { - return 39; - } - goto IF_NONE_MATCH; - default: - return -1; - } - -IF_R: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto IF_RA; - case 'a': - if (last) { - return -1; - } - goto IF_RA; - default: - return -1; - } - -IF_RA: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto IF_RAN; - case 'n': - if (last) { - return -1; - } - goto IF_RAN; - default: - return -1; - } - -IF_RAN: - NEXT_CHAR(); - switch (ch) { - case 'G': - if (last) { - return -1; - } - goto IF_RANG; - case 'g': - if (last) { - return -1; - } - goto IF_RANG; - default: - return -1; - } - -IF_RANG: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return 40; - } - goto IF_RANGE; - case 'e': - if (last) { - return 40; - } - goto IF_RANGE; - default: - return -1; - } - -IF_U: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto IF_UN; - case 'n': - if (last) { - return -1; - } - goto IF_UN; - default: - return -1; - } - -IF_UN: - NEXT_CHAR(); - switch (ch) { - case 'M': - if (last) { - return -1; - } - goto IF_UNM; - case 'm': - if (last) { - return -1; - } - goto IF_UNM; - default: - return -1; - } - -IF_UNM: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto IF_UNMO; - case 'o': - if (last) { - return -1; - } - goto IF_UNMO; - default: - return -1; - } - -IF_UNMO: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return -1; - } - goto IF_UNMOD; - case 'd': - if (last) { - return -1; - } - goto IF_UNMOD; - default: - return -1; - } - -IF_UNMOD: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto IF_UNMODI; - case 'i': - if (last) { - return -1; - } - goto IF_UNMODI; - default: - return -1; - } - -IF_UNMODI: - NEXT_CHAR(); - switch (ch) { - case 'F': - if (last) { - return -1; - } - goto IF_UNMODIF; - case 'f': - if (last) { - return -1; - } - goto IF_UNMODIF; - default: - return -1; - } - -IF_UNMODIF: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto IF_UNMODIFI; - case 'i': - if (last) { - return -1; - } - goto IF_UNMODIFI; - default: - return -1; - } - -IF_UNMODIFI: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto IF_UNMODIFIE; - case 'e': - if (last) { - return -1; - } - goto IF_UNMODIFIE; - default: - return -1; - } - -IF_UNMODIFIE: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return -1; - } - goto IF_UNMODIFIED; - case 'd': - if (last) { - return -1; - } - goto IF_UNMODIFIED; - default: - return -1; - } - -IF_UNMODIFIED: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto IF_UNMODIFIED_; - default: - return -1; - } - -IF_UNMODIFIED_: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return -1; - } - goto IF_UNMODIFIED_S; - case 's': - if (last) { - return -1; - } - goto IF_UNMODIFIED_S; - default: - return -1; - } - -IF_UNMODIFIED_S: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto IF_UNMODIFIED_SI; - case 'i': - if (last) { - return -1; - } - goto IF_UNMODIFIED_SI; - default: - return -1; - } - -IF_UNMODIFIED_SI: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto IF_UNMODIFIED_SIN; - case 'n': - if (last) { - return -1; - } - goto IF_UNMODIFIED_SIN; - default: - return -1; - } - -IF_UNMODIFIED_SIN: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto IF_UNMODIFIED_SINC; - case 'c': - if (last) { - return -1; - } - goto IF_UNMODIFIED_SINC; - default: - return -1; - } - -IF_UNMODIFIED_SINC: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return 41; - } - goto IF_UNMODIFIED_SINCE; - case 'e': - if (last) { - return 41; - } - goto IF_UNMODIFIED_SINCE; - default: - return -1; - } - -K: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto KE; - case 'e': - if (last) { - return -1; - } - goto KE; - default: - return -1; - } - -KE: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto KEE; - case 'e': - if (last) { - return -1; - } - goto KEE; - default: - return -1; - } - -KEE: - NEXT_CHAR(); - switch (ch) { - case 'P': - if (last) { - return -1; - } - goto KEEP; - case 'p': - if (last) { - return -1; - } - goto KEEP; - default: - return -1; - } - -KEEP: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto KEEP_; - default: - return -1; - } - -KEEP_: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto KEEP_A; - case 'a': - if (last) { - return -1; - } - goto KEEP_A; - default: - return -1; - } - -KEEP_A: - NEXT_CHAR(); - switch (ch) { - case 'L': - if (last) { - return -1; - } - goto KEEP_AL; - case 'l': - if (last) { - return -1; - } - goto KEEP_AL; - default: - return -1; - } - -KEEP_AL: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto KEEP_ALI; - case 'i': - if (last) { - return -1; - } - goto KEEP_ALI; - default: - return -1; - } - -KEEP_ALI: - NEXT_CHAR(); - switch (ch) { - case 'V': - if (last) { - return -1; - } - goto KEEP_ALIV; - case 'v': - if (last) { - return -1; - } - goto KEEP_ALIV; - default: - return -1; - } - -KEEP_ALIV: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return 42; - } - goto KEEP_ALIVE; - case 'e': - if (last) { - return 42; - } - goto KEEP_ALIVE; - default: - return -1; - } - -L: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto LA; - case 'a': - if (last) { - return -1; - } - goto LA; - case 'I': - if (last) { - return -1; - } - goto LI; - case 'i': - if (last) { - return -1; - } - goto LI; - case 'O': - if (last) { - return -1; - } - goto LO; - case 'o': - if (last) { - return -1; - } - goto LO; - default: - return -1; - } - -LA: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return -1; - } - goto LAS; - case 's': - if (last) { - return -1; - } - goto LAS; - default: - return -1; - } - -LAS: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto LAST; - case 't': - if (last) { - return -1; - } - goto LAST; - default: - return -1; - } - -LAST: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto LAST_; - default: - return -1; - } - -LAST_: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto LAST_E; - case 'e': - if (last) { - return -1; - } - goto LAST_E; - case 'M': - if (last) { - return -1; - } - goto LAST_M; - case 'm': - if (last) { - return -1; - } - goto LAST_M; - default: - return -1; - } - -LAST_E: - NEXT_CHAR(); - switch (ch) { - case 'V': - if (last) { - return -1; - } - goto LAST_EV; - case 'v': - if (last) { - return -1; - } - goto LAST_EV; - default: - return -1; - } - -LAST_EV: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto LAST_EVE; - case 'e': - if (last) { - return -1; - } - goto LAST_EVE; - default: - return -1; - } - -LAST_EVE: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto LAST_EVEN; - case 'n': - if (last) { - return -1; - } - goto LAST_EVEN; - default: - return -1; - } - -LAST_EVEN: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto LAST_EVENT; - case 't': - if (last) { - return -1; - } - goto LAST_EVENT; - default: - return -1; - } - -LAST_EVENT: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto LAST_EVENT_; - default: - return -1; - } - -LAST_EVENT_: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto LAST_EVENT_I; - case 'i': - if (last) { - return -1; - } - goto LAST_EVENT_I; - default: - return -1; - } - -LAST_EVENT_I: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return 43; - } - goto LAST_EVENT_ID; - case 'd': - if (last) { - return 43; - } - goto LAST_EVENT_ID; - default: - return -1; - } - -LAST_M: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto LAST_MO; - case 'o': - if (last) { - return -1; - } - goto LAST_MO; - default: - return -1; - } - -LAST_MO: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return -1; - } - goto LAST_MOD; - case 'd': - if (last) { - return -1; - } - goto LAST_MOD; - default: - return -1; - } - -LAST_MOD: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto LAST_MODI; - case 'i': - if (last) { - return -1; - } - goto LAST_MODI; - default: - return -1; - } - -LAST_MODI: - NEXT_CHAR(); - switch (ch) { - case 'F': - if (last) { - return -1; - } - goto LAST_MODIF; - case 'f': - if (last) { - return -1; - } - goto LAST_MODIF; - default: - return -1; - } - -LAST_MODIF: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto LAST_MODIFI; - case 'i': - if (last) { - return -1; - } - goto LAST_MODIFI; - default: - return -1; - } - -LAST_MODIFI: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto LAST_MODIFIE; - case 'e': - if (last) { - return -1; - } - goto LAST_MODIFIE; - default: - return -1; - } - -LAST_MODIFIE: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return 44; - } - goto LAST_MODIFIED; - case 'd': - if (last) { - return 44; - } - goto LAST_MODIFIED; - default: - return -1; - } - -LI: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto LIN; - case 'n': - if (last) { - return -1; - } - goto LIN; - default: - return -1; - } - -LIN: - NEXT_CHAR(); - switch (ch) { - case 'K': - if (last) { - return 45; - } - goto LINK; - case 'k': - if (last) { - return 45; - } - goto LINK; - default: - return -1; - } - -LO: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto LOC; - case 'c': - if (last) { - return -1; - } - goto LOC; - default: - return -1; - } - -LOC: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto LOCA; - case 'a': - if (last) { - return -1; - } - goto LOCA; - default: - return -1; - } - -LOCA: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto LOCAT; - case 't': - if (last) { - return -1; - } - goto LOCAT; - default: - return -1; - } - -LOCAT: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto LOCATI; - case 'i': - if (last) { - return -1; - } - goto LOCATI; - default: - return -1; - } - -LOCATI: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto LOCATIO; - case 'o': - if (last) { - return -1; - } - goto LOCATIO; - default: - return -1; - } - -LOCATIO: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return 46; - } - goto LOCATION; - case 'n': - if (last) { - return 46; - } - goto LOCATION; - default: - return -1; - } - -M: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto MA; - case 'a': - if (last) { - return -1; - } - goto MA; - default: - return -1; - } - -MA: - NEXT_CHAR(); - switch (ch) { - case 'X': - if (last) { - return -1; - } - goto MAX; - case 'x': - if (last) { - return -1; - } - goto MAX; - default: - return -1; - } - -MAX: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto MAX_; - default: - return -1; - } - -MAX_: - NEXT_CHAR(); - switch (ch) { - case 'F': - if (last) { - return -1; - } - goto MAX_F; - case 'f': - if (last) { - return -1; - } - goto MAX_F; - default: - return -1; - } - -MAX_F: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto MAX_FO; - case 'o': - if (last) { - return -1; - } - goto MAX_FO; - default: - return -1; - } - -MAX_FO: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto MAX_FOR; - case 'r': - if (last) { - return -1; - } - goto MAX_FOR; - default: - return -1; - } - -MAX_FOR: - NEXT_CHAR(); - switch (ch) { - case 'W': - if (last) { - return -1; - } - goto MAX_FORW; - case 'w': - if (last) { - return -1; - } - goto MAX_FORW; - default: - return -1; - } - -MAX_FORW: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto MAX_FORWA; - case 'a': - if (last) { - return -1; - } - goto MAX_FORWA; - default: - return -1; - } - -MAX_FORWA: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto MAX_FORWAR; - case 'r': - if (last) { - return -1; - } - goto MAX_FORWAR; - default: - return -1; - } - -MAX_FORWAR: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return -1; - } - goto MAX_FORWARD; - case 'd': - if (last) { - return -1; - } - goto MAX_FORWARD; - default: - return -1; - } - -MAX_FORWARD: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return 47; - } - goto MAX_FORWARDS; - case 's': - if (last) { - return 47; - } - goto MAX_FORWARDS; - default: - return -1; - } - -O: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto OR; - case 'r': - if (last) { - return -1; - } - goto OR; - default: - return -1; - } - -OR: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto ORI; - case 'i': - if (last) { - return -1; - } - goto ORI; - default: - return -1; - } - -ORI: - NEXT_CHAR(); - switch (ch) { - case 'G': - if (last) { - return -1; - } - goto ORIG; - case 'g': - if (last) { - return -1; - } - goto ORIG; - default: - return -1; - } - -ORIG: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto ORIGI; - case 'i': - if (last) { - return -1; - } - goto ORIGI; - default: - return -1; - } - -ORIGI: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return 48; - } - goto ORIGIN; - case 'n': - if (last) { - return 48; - } - goto ORIGIN; - default: - return -1; - } - -P: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto PR; - case 'r': - if (last) { - return -1; - } - goto PR; - default: - return -1; - } - -PR: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto PRA; - case 'a': - if (last) { - return -1; - } - goto PRA; - case 'O': - if (last) { - return -1; - } - goto PRO; - case 'o': - if (last) { - return -1; - } - goto PRO; - default: - return -1; - } - -PRA: - NEXT_CHAR(); - switch (ch) { - case 'G': - if (last) { - return -1; - } - goto PRAG; - case 'g': - if (last) { - return -1; - } - goto PRAG; - default: - return -1; - } - -PRAG: - NEXT_CHAR(); - switch (ch) { - case 'M': - if (last) { - return -1; - } - goto PRAGM; - case 'm': - if (last) { - return -1; - } - goto PRAGM; - default: - return -1; - } - -PRAGM: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return 49; - } - goto PRAGMA; - case 'a': - if (last) { - return 49; - } - goto PRAGMA; - default: - return -1; - } - -PRO: - NEXT_CHAR(); - switch (ch) { - case 'X': - if (last) { - return -1; - } - goto PROX; - case 'x': - if (last) { - return -1; - } - goto PROX; - default: - return -1; - } - -PROX: - NEXT_CHAR(); - switch (ch) { - case 'Y': - if (last) { - return -1; - } - goto PROXY; - case 'y': - if (last) { - return -1; - } - goto PROXY; - default: - return -1; - } - -PROXY: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto PROXY_; - default: - return -1; - } - -PROXY_: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto PROXY_A; - case 'a': - if (last) { - return -1; - } - goto PROXY_A; - default: - return -1; - } - -PROXY_A: - NEXT_CHAR(); - switch (ch) { - case 'U': - if (last) { - return -1; - } - goto PROXY_AU; - case 'u': - if (last) { - return -1; - } - goto PROXY_AU; - default: - return -1; - } - -PROXY_AU: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto PROXY_AUT; - case 't': - if (last) { - return -1; - } - goto PROXY_AUT; - default: - return -1; - } - -PROXY_AUT: - NEXT_CHAR(); - switch (ch) { - case 'H': - if (last) { - return -1; - } - goto PROXY_AUTH; - case 'h': - if (last) { - return -1; - } - goto PROXY_AUTH; - default: - return -1; - } - -PROXY_AUTH: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto PROXY_AUTHE; - case 'e': - if (last) { - return -1; - } - goto PROXY_AUTHE; - case 'O': - if (last) { - return -1; - } - goto PROXY_AUTHO; - case 'o': - if (last) { - return -1; - } - goto PROXY_AUTHO; - default: - return -1; - } - -PROXY_AUTHE: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto PROXY_AUTHEN; - case 'n': - if (last) { - return -1; - } - goto PROXY_AUTHEN; - default: - return -1; - } - -PROXY_AUTHEN: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto PROXY_AUTHENT; - case 't': - if (last) { - return -1; - } - goto PROXY_AUTHENT; - default: - return -1; - } - -PROXY_AUTHENT: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto PROXY_AUTHENTI; - case 'i': - if (last) { - return -1; - } - goto PROXY_AUTHENTI; - default: - return -1; - } - -PROXY_AUTHENTI: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto PROXY_AUTHENTIC; - case 'c': - if (last) { - return -1; - } - goto PROXY_AUTHENTIC; - default: - return -1; - } - -PROXY_AUTHENTIC: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto PROXY_AUTHENTICA; - case 'a': - if (last) { - return -1; - } - goto PROXY_AUTHENTICA; - default: - return -1; - } - -PROXY_AUTHENTICA: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto PROXY_AUTHENTICAT; - case 't': - if (last) { - return -1; - } - goto PROXY_AUTHENTICAT; - default: - return -1; - } - -PROXY_AUTHENTICAT: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return 50; - } - goto PROXY_AUTHENTICATE; - case 'e': - if (last) { - return 50; - } - goto PROXY_AUTHENTICATE; - default: - return -1; - } - -PROXY_AUTHO: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto PROXY_AUTHOR; - case 'r': - if (last) { - return -1; - } - goto PROXY_AUTHOR; - default: - return -1; - } - -PROXY_AUTHOR: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto PROXY_AUTHORI; - case 'i': - if (last) { - return -1; - } - goto PROXY_AUTHORI; - default: - return -1; - } - -PROXY_AUTHORI: - NEXT_CHAR(); - switch (ch) { - case 'Z': - if (last) { - return -1; - } - goto PROXY_AUTHORIZ; - case 'z': - if (last) { - return -1; - } - goto PROXY_AUTHORIZ; - default: - return -1; - } - -PROXY_AUTHORIZ: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto PROXY_AUTHORIZA; - case 'a': - if (last) { - return -1; - } - goto PROXY_AUTHORIZA; - default: - return -1; - } - -PROXY_AUTHORIZA: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto PROXY_AUTHORIZAT; - case 't': - if (last) { - return -1; - } - goto PROXY_AUTHORIZAT; - default: - return -1; - } - -PROXY_AUTHORIZAT: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto PROXY_AUTHORIZATI; - case 'i': - if (last) { - return -1; - } - goto PROXY_AUTHORIZATI; - default: - return -1; - } - -PROXY_AUTHORIZATI: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto PROXY_AUTHORIZATIO; - case 'o': - if (last) { - return -1; - } - goto PROXY_AUTHORIZATIO; - default: - return -1; - } - -PROXY_AUTHORIZATIO: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return 51; - } - goto PROXY_AUTHORIZATION; - case 'n': - if (last) { - return 51; - } - goto PROXY_AUTHORIZATION; - default: - return -1; - } - -R: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto RA; - case 'a': - if (last) { - return -1; - } - goto RA; - case 'E': - if (last) { - return -1; - } - goto RE; - case 'e': - if (last) { - return -1; - } - goto RE; - default: - return -1; - } - -RA: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto RAN; - case 'n': - if (last) { - return -1; - } - goto RAN; - default: - return -1; - } - -RAN: - NEXT_CHAR(); - switch (ch) { - case 'G': - if (last) { - return -1; - } - goto RANG; - case 'g': - if (last) { - return -1; - } - goto RANG; - default: - return -1; - } - -RANG: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return 52; - } - goto RANGE; - case 'e': - if (last) { - return 52; - } - goto RANGE; - default: - return -1; - } - -RE: - NEXT_CHAR(); - switch (ch) { - case 'F': - if (last) { - return -1; - } - goto REF; - case 'f': - if (last) { - return -1; - } - goto REF; - case 'T': - if (last) { - return -1; - } - goto RET; - case 't': - if (last) { - return -1; - } - goto RET; - default: - return -1; - } - -REF: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto REFE; - case 'e': - if (last) { - return -1; - } - goto REFE; - default: - return -1; - } - -REFE: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto REFER; - case 'r': - if (last) { - return -1; - } - goto REFER; - default: - return -1; - } - -REFER: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto REFERE; - case 'e': - if (last) { - return -1; - } - goto REFERE; - default: - return -1; - } - -REFERE: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return 53; - } - goto REFERER; - case 'r': - if (last) { - return 53; - } - goto REFERER; - default: - return -1; - } - -RET: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto RETR; - case 'r': - if (last) { - return -1; - } - goto RETR; - default: - return -1; - } - -RETR: - NEXT_CHAR(); - switch (ch) { - case 'Y': - if (last) { - return -1; - } - goto RETRY; - case 'y': - if (last) { - return -1; - } - goto RETRY; - default: - return -1; - } - -RETRY: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto RETRY_; - default: - return -1; - } - -RETRY_: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto RETRY_A; - case 'a': - if (last) { - return -1; - } - goto RETRY_A; - default: - return -1; - } - -RETRY_A: - NEXT_CHAR(); - switch (ch) { - case 'F': - if (last) { - return -1; - } - goto RETRY_AF; - case 'f': - if (last) { - return -1; - } - goto RETRY_AF; - default: - return -1; - } - -RETRY_AF: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto RETRY_AFT; - case 't': - if (last) { - return -1; - } - goto RETRY_AFT; - default: - return -1; - } - -RETRY_AFT: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto RETRY_AFTE; - case 'e': - if (last) { - return -1; - } - goto RETRY_AFTE; - default: - return -1; - } - -RETRY_AFTE: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return 54; - } - goto RETRY_AFTER; - case 'r': - if (last) { - return 54; - } - goto RETRY_AFTER; - default: - return -1; - } - -S: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto SE; - case 'e': - if (last) { - return -1; - } - goto SE; - default: - return -1; - } - -SE: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto SEC; - case 'c': - if (last) { - return -1; - } - goto SEC; - case 'R': - if (last) { - return -1; - } - goto SER; - case 'r': - if (last) { - return -1; - } - goto SER; - case 'T': - if (last) { - return -1; - } - goto SET; - case 't': - if (last) { - return -1; - } - goto SET; - default: - return -1; - } - -SEC: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto SEC_; - default: - return -1; - } - -SEC_: - NEXT_CHAR(); - switch (ch) { - case 'W': - if (last) { - return -1; - } - goto SEC_W; - case 'w': - if (last) { - return -1; - } - goto SEC_W; - default: - return -1; - } - -SEC_W: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto SEC_WE; - case 'e': - if (last) { - return -1; - } - goto SEC_WE; - default: - return -1; - } - -SEC_WE: - NEXT_CHAR(); - switch (ch) { - case 'B': - if (last) { - return -1; - } - goto SEC_WEB; - case 'b': - if (last) { - return -1; - } - goto SEC_WEB; - default: - return -1; - } - -SEC_WEB: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return -1; - } - goto SEC_WEBS; - case 's': - if (last) { - return -1; - } - goto SEC_WEBS; - default: - return -1; - } - -SEC_WEBS: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto SEC_WEBSO; - case 'o': - if (last) { - return -1; - } - goto SEC_WEBSO; - default: - return -1; - } - -SEC_WEBSO: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto SEC_WEBSOC; - case 'c': - if (last) { - return -1; - } - goto SEC_WEBSOC; - default: - return -1; - } - -SEC_WEBSOC: - NEXT_CHAR(); - switch (ch) { - case 'K': - if (last) { - return -1; - } - goto SEC_WEBSOCK; - case 'k': - if (last) { - return -1; - } - goto SEC_WEBSOCK; - default: - return -1; - } - -SEC_WEBSOCK: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto SEC_WEBSOCKE; - case 'e': - if (last) { - return -1; - } - goto SEC_WEBSOCKE; - default: - return -1; - } - -SEC_WEBSOCKE: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto SEC_WEBSOCKET; - case 't': - if (last) { - return -1; - } - goto SEC_WEBSOCKET; - default: - return -1; - } - -SEC_WEBSOCKET: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_; - default: - return -1; - } - -SEC_WEBSOCKET_: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_A; - case 'a': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_A; - case 'E': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_E; - case 'e': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_E; - case 'K': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_K; - case 'k': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_K; - case 'P': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_P; - case 'p': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_P; - case 'V': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_V; - case 'v': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_V; - default: - return -1; - } - -SEC_WEBSOCKET_A: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_AC; - case 'c': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_AC; - default: - return -1; - } - -SEC_WEBSOCKET_AC: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_ACC; - case 'c': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_ACC; - default: - return -1; - } - -SEC_WEBSOCKET_ACC: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_ACCE; - case 'e': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_ACCE; - default: - return -1; - } - -SEC_WEBSOCKET_ACCE: - NEXT_CHAR(); - switch (ch) { - case 'P': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_ACCEP; - case 'p': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_ACCEP; - default: - return -1; - } - -SEC_WEBSOCKET_ACCEP: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return 55; - } - goto SEC_WEBSOCKET_ACCEPT; - case 't': - if (last) { - return 55; - } - goto SEC_WEBSOCKET_ACCEPT; - default: - return -1; - } - -SEC_WEBSOCKET_E: - NEXT_CHAR(); - switch (ch) { - case 'X': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_EX; - case 'x': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_EX; - default: - return -1; - } - -SEC_WEBSOCKET_EX: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_EXT; - case 't': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_EXT; - default: - return -1; - } - -SEC_WEBSOCKET_EXT: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_EXTE; - case 'e': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_EXTE; - default: - return -1; - } - -SEC_WEBSOCKET_EXTE: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_EXTEN; - case 'n': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_EXTEN; - default: - return -1; - } - -SEC_WEBSOCKET_EXTEN: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_EXTENS; - case 's': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_EXTENS; - default: - return -1; - } - -SEC_WEBSOCKET_EXTENS: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_EXTENSI; - case 'i': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_EXTENSI; - default: - return -1; - } - -SEC_WEBSOCKET_EXTENSI: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_EXTENSIO; - case 'o': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_EXTENSIO; - default: - return -1; - } - -SEC_WEBSOCKET_EXTENSIO: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_EXTENSION; - case 'n': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_EXTENSION; - default: - return -1; - } - -SEC_WEBSOCKET_EXTENSION: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return 56; - } - goto SEC_WEBSOCKET_EXTENSIONS; - case 's': - if (last) { - return 56; - } - goto SEC_WEBSOCKET_EXTENSIONS; - default: - return -1; - } - -SEC_WEBSOCKET_K: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_KE; - case 'e': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_KE; - default: - return -1; - } - -SEC_WEBSOCKET_KE: - NEXT_CHAR(); - switch (ch) { - case 'Y': - if (last) { - return 57; - } - goto SEC_WEBSOCKET_KEY; - case 'y': - if (last) { - return 57; - } - goto SEC_WEBSOCKET_KEY; - default: - return -1; - } - -SEC_WEBSOCKET_KEY: - NEXT_CHAR(); - switch (ch) { - case '1': - if (last) { - return 58; - } - goto SEC_WEBSOCKET_KEY1; - default: - return -1; - } - -SEC_WEBSOCKET_P: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_PR; - case 'r': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_PR; - default: - return -1; - } - -SEC_WEBSOCKET_PR: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_PRO; - case 'o': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_PRO; - default: - return -1; - } - -SEC_WEBSOCKET_PRO: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_PROT; - case 't': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_PROT; - default: - return -1; - } - -SEC_WEBSOCKET_PROT: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_PROTO; - case 'o': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_PROTO; - default: - return -1; - } - -SEC_WEBSOCKET_PROTO: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_PROTOC; - case 'c': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_PROTOC; - default: - return -1; - } - -SEC_WEBSOCKET_PROTOC: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_PROTOCO; - case 'o': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_PROTOCO; - default: - return -1; - } - -SEC_WEBSOCKET_PROTOCO: - NEXT_CHAR(); - switch (ch) { - case 'L': - if (last) { - return 59; - } - goto SEC_WEBSOCKET_PROTOCOL; - case 'l': - if (last) { - return 59; - } - goto SEC_WEBSOCKET_PROTOCOL; - default: - return -1; - } - -SEC_WEBSOCKET_V: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_VE; - case 'e': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_VE; - default: - return -1; - } - -SEC_WEBSOCKET_VE: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_VER; - case 'r': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_VER; - default: - return -1; - } - -SEC_WEBSOCKET_VER: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_VERS; - case 's': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_VERS; - default: - return -1; - } - -SEC_WEBSOCKET_VERS: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_VERSI; - case 'i': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_VERSI; - default: - return -1; - } - -SEC_WEBSOCKET_VERSI: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_VERSIO; - case 'o': - if (last) { - return -1; - } - goto SEC_WEBSOCKET_VERSIO; - default: - return -1; - } - -SEC_WEBSOCKET_VERSIO: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return 60; - } - goto SEC_WEBSOCKET_VERSION; - case 'n': - if (last) { - return 60; - } - goto SEC_WEBSOCKET_VERSION; - default: - return -1; - } - -SER: - NEXT_CHAR(); - switch (ch) { - case 'V': - if (last) { - return -1; - } - goto SERV; - case 'v': - if (last) { - return -1; - } - goto SERV; - default: - return -1; - } - -SERV: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto SERVE; - case 'e': - if (last) { - return -1; - } - goto SERVE; - default: - return -1; - } - -SERVE: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return 61; - } - goto SERVER; - case 'r': - if (last) { - return 61; - } - goto SERVER; - default: - return -1; - } - -SET: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto SET_; - default: - return -1; - } - -SET_: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto SET_C; - case 'c': - if (last) { - return -1; - } - goto SET_C; - default: - return -1; - } - -SET_C: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto SET_CO; - case 'o': - if (last) { - return -1; - } - goto SET_CO; - default: - return -1; - } - -SET_CO: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto SET_COO; - case 'o': - if (last) { - return -1; - } - goto SET_COO; - default: - return -1; - } - -SET_COO: - NEXT_CHAR(); - switch (ch) { - case 'K': - if (last) { - return -1; - } - goto SET_COOK; - case 'k': - if (last) { - return -1; - } - goto SET_COOK; - default: - return -1; - } - -SET_COOK: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto SET_COOKI; - case 'i': - if (last) { - return -1; - } - goto SET_COOKI; - default: - return -1; - } - -SET_COOKI: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return 62; - } - goto SET_COOKIE; - case 'e': - if (last) { - return 62; - } - goto SET_COOKIE; - default: - return -1; - } - -T: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return 63; - } - goto TE; - case 'e': - if (last) { - return 63; - } - goto TE; - case 'R': - if (last) { - return -1; - } - goto TR; - case 'r': - if (last) { - return -1; - } - goto TR; - default: - return -1; - } - -TR: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto TRA; - case 'a': - if (last) { - return -1; - } - goto TRA; - default: - return -1; - } - -TRA: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto TRAI; - case 'i': - if (last) { - return -1; - } - goto TRAI; - case 'N': - if (last) { - return -1; - } - goto TRAN; - case 'n': - if (last) { - return -1; - } - goto TRAN; - default: - return -1; - } - -TRAI: - NEXT_CHAR(); - switch (ch) { - case 'L': - if (last) { - return -1; - } - goto TRAIL; - case 'l': - if (last) { - return -1; - } - goto TRAIL; - default: - return -1; - } - -TRAIL: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto TRAILE; - case 'e': - if (last) { - return -1; - } - goto TRAILE; - default: - return -1; - } - -TRAILE: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return 64; - } - goto TRAILER; - case 'r': - if (last) { - return 64; - } - goto TRAILER; - default: - return -1; - } - -TRAN: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return -1; - } - goto TRANS; - case 's': - if (last) { - return -1; - } - goto TRANS; - default: - return -1; - } - -TRANS: - NEXT_CHAR(); - switch (ch) { - case 'F': - if (last) { - return -1; - } - goto TRANSF; - case 'f': - if (last) { - return -1; - } - goto TRANSF; - default: - return -1; - } - -TRANSF: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto TRANSFE; - case 'e': - if (last) { - return -1; - } - goto TRANSFE; - default: - return -1; - } - -TRANSFE: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto TRANSFER; - case 'r': - if (last) { - return -1; - } - goto TRANSFER; - default: - return -1; - } - -TRANSFER: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto TRANSFER_; - default: - return -1; - } - -TRANSFER_: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto TRANSFER_E; - case 'e': - if (last) { - return -1; - } - goto TRANSFER_E; - default: - return -1; - } - -TRANSFER_E: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto TRANSFER_EN; - case 'n': - if (last) { - return -1; - } - goto TRANSFER_EN; - default: - return -1; - } - -TRANSFER_EN: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto TRANSFER_ENC; - case 'c': - if (last) { - return -1; - } - goto TRANSFER_ENC; - default: - return -1; - } - -TRANSFER_ENC: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto TRANSFER_ENCO; - case 'o': - if (last) { - return -1; - } - goto TRANSFER_ENCO; - default: - return -1; - } - -TRANSFER_ENCO: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return -1; - } - goto TRANSFER_ENCOD; - case 'd': - if (last) { - return -1; - } - goto TRANSFER_ENCOD; - default: - return -1; - } - -TRANSFER_ENCOD: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto TRANSFER_ENCODI; - case 'i': - if (last) { - return -1; - } - goto TRANSFER_ENCODI; - default: - return -1; - } - -TRANSFER_ENCODI: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto TRANSFER_ENCODIN; - case 'n': - if (last) { - return -1; - } - goto TRANSFER_ENCODIN; - default: - return -1; - } - -TRANSFER_ENCODIN: - NEXT_CHAR(); - switch (ch) { - case 'G': - if (last) { - return 65; - } - goto TRANSFER_ENCODING; - case 'g': - if (last) { - return 65; - } - goto TRANSFER_ENCODING; - default: - return -1; - } - -U: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto UR; - case 'r': - if (last) { - return -1; - } - goto UR; - case 'P': - if (last) { - return -1; - } - goto UP; - case 'p': - if (last) { - return -1; - } - goto UP; - case 'S': - if (last) { - return -1; - } - goto US; - case 's': - if (last) { - return -1; - } - goto US; - default: - return -1; - } - -UR: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return 66; - } - goto URI; - case 'i': - if (last) { - return 66; - } - goto URI; - default: - return -1; - } - -UP: - NEXT_CHAR(); - switch (ch) { - case 'G': - if (last) { - return -1; - } - goto UPG; - case 'g': - if (last) { - return -1; - } - goto UPG; - default: - return -1; - } - -UPG: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto UPGR; - case 'r': - if (last) { - return -1; - } - goto UPGR; - default: - return -1; - } - -UPGR: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto UPGRA; - case 'a': - if (last) { - return -1; - } - goto UPGRA; - default: - return -1; - } - -UPGRA: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return -1; - } - goto UPGRAD; - case 'd': - if (last) { - return -1; - } - goto UPGRAD; - default: - return -1; - } - -UPGRAD: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return 67; - } - goto UPGRADE; - case 'e': - if (last) { - return 67; - } - goto UPGRADE; - default: - return -1; - } - -US: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto USE; - case 'e': - if (last) { - return -1; - } - goto USE; - default: - return -1; - } - -USE: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto USER; - case 'r': - if (last) { - return -1; - } - goto USER; - default: - return -1; - } - -USER: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto USER_; - default: - return -1; - } - -USER_: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto USER_A; - case 'a': - if (last) { - return -1; - } - goto USER_A; - default: - return -1; - } - -USER_A: - NEXT_CHAR(); - switch (ch) { - case 'G': - if (last) { - return -1; - } - goto USER_AG; - case 'g': - if (last) { - return -1; - } - goto USER_AG; - default: - return -1; - } - -USER_AG: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto USER_AGE; - case 'e': - if (last) { - return -1; - } - goto USER_AGE; - default: - return -1; - } - -USER_AGE: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto USER_AGEN; - case 'n': - if (last) { - return -1; - } - goto USER_AGEN; - default: - return -1; - } - -USER_AGEN: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return 68; - } - goto USER_AGENT; - case 't': - if (last) { - return 68; - } - goto USER_AGENT; - default: - return -1; - } - -V: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto VA; - case 'a': - if (last) { - return -1; - } - goto VA; - case 'I': - if (last) { - return -1; - } - goto VI; - case 'i': - if (last) { - return -1; - } - goto VI; - default: - return -1; - } - -VA: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto VAR; - case 'r': - if (last) { - return -1; - } - goto VAR; - default: - return -1; - } - -VAR: - NEXT_CHAR(); - switch (ch) { - case 'Y': - if (last) { - return 69; - } - goto VARY; - case 'y': - if (last) { - return 69; - } - goto VARY; - default: - return -1; - } - -VI: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return 70; - } - goto VIA; - case 'a': - if (last) { - return 70; - } - goto VIA; - default: - return -1; - } - -W: - NEXT_CHAR(); - switch (ch) { - case 'W': - if (last) { - return -1; - } - goto WW; - case 'w': - if (last) { - return -1; - } - goto WW; - case 'A': - if (last) { - return -1; - } - goto WA; - case 'a': - if (last) { - return -1; - } - goto WA; - default: - return -1; - } - -WW: - NEXT_CHAR(); - switch (ch) { - case 'W': - if (last) { - return -1; - } - goto WWW; - case 'w': - if (last) { - return -1; - } - goto WWW; - default: - return -1; - } - -WWW: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto WWW_; - default: - return -1; - } - -WWW_: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto WWW_A; - case 'a': - if (last) { - return -1; - } - goto WWW_A; - default: - return -1; - } - -WWW_A: - NEXT_CHAR(); - switch (ch) { - case 'U': - if (last) { - return -1; - } - goto WWW_AU; - case 'u': - if (last) { - return -1; - } - goto WWW_AU; - default: - return -1; - } - -WWW_AU: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto WWW_AUT; - case 't': - if (last) { - return -1; - } - goto WWW_AUT; - default: - return -1; - } - -WWW_AUT: - NEXT_CHAR(); - switch (ch) { - case 'H': - if (last) { - return -1; - } - goto WWW_AUTH; - case 'h': - if (last) { - return -1; - } - goto WWW_AUTH; - default: - return -1; - } - -WWW_AUTH: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto WWW_AUTHE; - case 'e': - if (last) { - return -1; - } - goto WWW_AUTHE; - default: - return -1; - } - -WWW_AUTHE: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto WWW_AUTHEN; - case 'n': - if (last) { - return -1; - } - goto WWW_AUTHEN; - default: - return -1; - } - -WWW_AUTHEN: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto WWW_AUTHENT; - case 't': - if (last) { - return -1; - } - goto WWW_AUTHENT; - default: - return -1; - } - -WWW_AUTHENT: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto WWW_AUTHENTI; - case 'i': - if (last) { - return -1; - } - goto WWW_AUTHENTI; - default: - return -1; - } - -WWW_AUTHENTI: - NEXT_CHAR(); - switch (ch) { - case 'C': - if (last) { - return -1; - } - goto WWW_AUTHENTIC; - case 'c': - if (last) { - return -1; - } - goto WWW_AUTHENTIC; - default: - return -1; - } - -WWW_AUTHENTIC: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto WWW_AUTHENTICA; - case 'a': - if (last) { - return -1; - } - goto WWW_AUTHENTICA; - default: - return -1; - } - -WWW_AUTHENTICA: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto WWW_AUTHENTICAT; - case 't': - if (last) { - return -1; - } - goto WWW_AUTHENTICAT; - default: - return -1; - } - -WWW_AUTHENTICAT: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return 71; - } - goto WWW_AUTHENTICATE; - case 'e': - if (last) { - return 71; - } - goto WWW_AUTHENTICATE; - default: - return -1; - } - -WA: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto WAN; - case 'n': - if (last) { - return -1; - } - goto WAN; - case 'R': - if (last) { - return -1; - } - goto WAR; - case 'r': - if (last) { - return -1; - } - goto WAR; - default: - return -1; - } - -WAN: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto WANT; - case 't': - if (last) { - return -1; - } - goto WANT; - default: - return -1; - } - -WANT: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto WANT_; - default: - return -1; - } - -WANT_: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return -1; - } - goto WANT_D; - case 'd': - if (last) { - return -1; - } - goto WANT_D; - default: - return -1; - } - -WANT_D: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto WANT_DI; - case 'i': - if (last) { - return -1; - } - goto WANT_DI; - default: - return -1; - } - -WANT_DI: - NEXT_CHAR(); - switch (ch) { - case 'G': - if (last) { - return -1; - } - goto WANT_DIG; - case 'g': - if (last) { - return -1; - } - goto WANT_DIG; - default: - return -1; - } - -WANT_DIG: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto WANT_DIGE; - case 'e': - if (last) { - return -1; - } - goto WANT_DIGE; - default: - return -1; - } - -WANT_DIGE: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return -1; - } - goto WANT_DIGES; - case 's': - if (last) { - return -1; - } - goto WANT_DIGES; - default: - return -1; - } - -WANT_DIGES: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return 72; - } - goto WANT_DIGEST; - case 't': - if (last) { - return 72; - } - goto WANT_DIGEST; - default: - return -1; - } - -WAR: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto WARN; - case 'n': - if (last) { - return -1; - } - goto WARN; - default: - return -1; - } - -WARN: - NEXT_CHAR(); - switch (ch) { - case 'I': - if (last) { - return -1; - } - goto WARNI; - case 'i': - if (last) { - return -1; - } - goto WARNI; - default: - return -1; - } - -WARNI: - NEXT_CHAR(); - switch (ch) { - case 'N': - if (last) { - return -1; - } - goto WARNIN; - case 'n': - if (last) { - return -1; - } - goto WARNIN; - default: - return -1; - } - -WARNIN: - NEXT_CHAR(); - switch (ch) { - case 'G': - if (last) { - return 73; - } - goto WARNING; - case 'g': - if (last) { - return 73; - } - goto WARNING; - default: - return -1; - } - -X: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto X_; - default: - return -1; - } - -X_: - NEXT_CHAR(); - switch (ch) { - case 'F': - if (last) { - return -1; - } - goto X_F; - case 'f': - if (last) { - return -1; - } - goto X_F; - default: - return -1; - } - -X_F: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto X_FO; - case 'o': - if (last) { - return -1; - } - goto X_FO; - default: - return -1; - } - -X_FO: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto X_FOR; - case 'r': - if (last) { - return -1; - } - goto X_FOR; - default: - return -1; - } - -X_FOR: - NEXT_CHAR(); - switch (ch) { - case 'W': - if (last) { - return -1; - } - goto X_FORW; - case 'w': - if (last) { - return -1; - } - goto X_FORW; - default: - return -1; - } - -X_FORW: - NEXT_CHAR(); - switch (ch) { - case 'A': - if (last) { - return -1; - } - goto X_FORWA; - case 'a': - if (last) { - return -1; - } - goto X_FORWA; - default: - return -1; - } - -X_FORWA: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto X_FORWAR; - case 'r': - if (last) { - return -1; - } - goto X_FORWAR; - default: - return -1; - } - -X_FORWAR: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return -1; - } - goto X_FORWARD; - case 'd': - if (last) { - return -1; - } - goto X_FORWARD; - default: - return -1; - } - -X_FORWARD: - NEXT_CHAR(); - switch (ch) { - case 'E': - if (last) { - return -1; - } - goto X_FORWARDE; - case 'e': - if (last) { - return -1; - } - goto X_FORWARDE; - default: - return -1; - } - -X_FORWARDE: - NEXT_CHAR(); - switch (ch) { - case 'D': - if (last) { - return -1; - } - goto X_FORWARDED; - case 'd': - if (last) { - return -1; - } - goto X_FORWARDED; - default: - return -1; - } - -X_FORWARDED: - NEXT_CHAR(); - switch (ch) { - case '-': - if (last) { - return -1; - } - goto X_FORWARDED_; - default: - return -1; - } - -X_FORWARDED_: - NEXT_CHAR(); - switch (ch) { - case 'F': - if (last) { - return -1; - } - goto X_FORWARDED_F; - case 'f': - if (last) { - return -1; - } - goto X_FORWARDED_F; - case 'H': - if (last) { - return -1; - } - goto X_FORWARDED_H; - case 'h': - if (last) { - return -1; - } - goto X_FORWARDED_H; - case 'P': - if (last) { - return -1; - } - goto X_FORWARDED_P; - case 'p': - if (last) { - return -1; - } - goto X_FORWARDED_P; - default: - return -1; - } - -X_FORWARDED_F: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto X_FORWARDED_FO; - case 'o': - if (last) { - return -1; - } - goto X_FORWARDED_FO; - default: - return -1; - } - -X_FORWARDED_FO: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return 74; - } - goto X_FORWARDED_FOR; - case 'r': - if (last) { - return 74; - } - goto X_FORWARDED_FOR; - default: - return -1; - } - -X_FORWARDED_H: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto X_FORWARDED_HO; - case 'o': - if (last) { - return -1; - } - goto X_FORWARDED_HO; - default: - return -1; - } - -X_FORWARDED_HO: - NEXT_CHAR(); - switch (ch) { - case 'S': - if (last) { - return -1; - } - goto X_FORWARDED_HOS; - case 's': - if (last) { - return -1; - } - goto X_FORWARDED_HOS; - default: - return -1; - } - -X_FORWARDED_HOS: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return 75; - } - goto X_FORWARDED_HOST; - case 't': - if (last) { - return 75; - } - goto X_FORWARDED_HOST; - default: - return -1; - } - -X_FORWARDED_P: - NEXT_CHAR(); - switch (ch) { - case 'R': - if (last) { - return -1; - } - goto X_FORWARDED_PR; - case 'r': - if (last) { - return -1; - } - goto X_FORWARDED_PR; - default: - return -1; - } - -X_FORWARDED_PR: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return -1; - } - goto X_FORWARDED_PRO; - case 'o': - if (last) { - return -1; - } - goto X_FORWARDED_PRO; - default: - return -1; - } - -X_FORWARDED_PRO: - NEXT_CHAR(); - switch (ch) { - case 'T': - if (last) { - return -1; - } - goto X_FORWARDED_PROT; - case 't': - if (last) { - return -1; - } - goto X_FORWARDED_PROT; - default: - return -1; - } - -X_FORWARDED_PROT: - NEXT_CHAR(); - switch (ch) { - case 'O': - if (last) { - return 76; - } - goto X_FORWARDED_PROTO; - case 'o': - if (last) { - return 76; - } - goto X_FORWARDED_PROTO; - default: - return -1; - } - -ACCEPT_CHARSET: -ACCEPT_ENCODING: -ACCEPT_LANGUAGE: -ACCEPT_RANGES: -ACCESS_CONTROL_ALLOW_CREDENTIALS: -ACCESS_CONTROL_ALLOW_HEADERS: -ACCESS_CONTROL_ALLOW_METHODS: -ACCESS_CONTROL_ALLOW_ORIGIN: -ACCESS_CONTROL_EXPOSE_HEADERS: -ACCESS_CONTROL_MAX_AGE: -ACCESS_CONTROL_REQUEST_HEADERS: -ACCESS_CONTROL_REQUEST_METHOD: -AGE: -ALLOW: -AUTHORIZATION: -CACHE_CONTROL: -CONNECTION: -CONTENT_DISPOSITION: -CONTENT_ENCODING: -CONTENT_LANGUAGE: -CONTENT_LENGTH: -CONTENT_LOCATION: -CONTENT_MD5: -CONTENT_RANGE: -CONTENT_TRANSFER_ENCODING: -CONTENT_TYPE: -COOKIE: -DATE: -DESTINATION: -DIGEST: -ETAG: -EXPECT: -EXPIRES: -FORWARDED: -FROM: -HOST: -IF_MATCH: -IF_MODIFIED_SINCE: -IF_NONE_MATCH: -IF_RANGE: -IF_UNMODIFIED_SINCE: -KEEP_ALIVE: -LAST_EVENT_ID: -LAST_MODIFIED: -LINK: -LOCATION: -MAX_FORWARDS: -ORIGIN: -PRAGMA: -PROXY_AUTHENTICATE: -PROXY_AUTHORIZATION: -RANGE: -REFERER: -RETRY_AFTER: -SEC_WEBSOCKET_ACCEPT: -SEC_WEBSOCKET_EXTENSIONS: -SEC_WEBSOCKET_KEY1: -SEC_WEBSOCKET_PROTOCOL: -SEC_WEBSOCKET_VERSION: -SERVER: -SET_COOKIE: -TE: -TRAILER: -TRANSFER_ENCODING: -UPGRADE: -URI: -USER_AGENT: -VARY: -VIA: -WANT_DIGEST: -WARNING: -WWW_AUTHENTICATE: -X_FORWARDED_FOR: -X_FORWARDED_HOST: -X_FORWARDED_PROTO: -missing: - /* nothing found */ - return -1; -} diff --git a/.venv/Lib/site-packages/aiohttp/_find_header.h b/.venv/Lib/site-packages/aiohttp/_find_header.h deleted file mode 100644 index 99b7b4f..0000000 --- a/.venv/Lib/site-packages/aiohttp/_find_header.h +++ /dev/null @@ -1,14 +0,0 @@ -#ifndef _FIND_HEADERS_H -#define _FIND_HEADERS_H - -#ifdef __cplusplus -extern "C" { -#endif - -int find_header(const char *str, int size); - - -#ifdef __cplusplus -} -#endif -#endif diff --git a/.venv/Lib/site-packages/aiohttp/_find_header.pxd b/.venv/Lib/site-packages/aiohttp/_find_header.pxd deleted file mode 100644 index 37a6c37..0000000 --- a/.venv/Lib/site-packages/aiohttp/_find_header.pxd +++ /dev/null @@ -1,2 +0,0 @@ -cdef extern from "_find_header.h": - int find_header(char *, int) diff --git a/.venv/Lib/site-packages/aiohttp/_headers.pxi b/.venv/Lib/site-packages/aiohttp/_headers.pxi deleted file mode 100644 index 3744721..0000000 --- a/.venv/Lib/site-packages/aiohttp/_headers.pxi +++ /dev/null @@ -1,83 +0,0 @@ -# The file is autogenerated from aiohttp/hdrs.py -# Run ./tools/gen.py to update it after the origin changing. - -from . import hdrs -cdef tuple headers = ( - hdrs.ACCEPT, - hdrs.ACCEPT_CHARSET, - hdrs.ACCEPT_ENCODING, - hdrs.ACCEPT_LANGUAGE, - hdrs.ACCEPT_RANGES, - hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, - hdrs.ACCESS_CONTROL_ALLOW_HEADERS, - hdrs.ACCESS_CONTROL_ALLOW_METHODS, - hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, - hdrs.ACCESS_CONTROL_EXPOSE_HEADERS, - hdrs.ACCESS_CONTROL_MAX_AGE, - hdrs.ACCESS_CONTROL_REQUEST_HEADERS, - hdrs.ACCESS_CONTROL_REQUEST_METHOD, - hdrs.AGE, - hdrs.ALLOW, - hdrs.AUTHORIZATION, - hdrs.CACHE_CONTROL, - hdrs.CONNECTION, - hdrs.CONTENT_DISPOSITION, - hdrs.CONTENT_ENCODING, - hdrs.CONTENT_LANGUAGE, - hdrs.CONTENT_LENGTH, - hdrs.CONTENT_LOCATION, - hdrs.CONTENT_MD5, - hdrs.CONTENT_RANGE, - hdrs.CONTENT_TRANSFER_ENCODING, - hdrs.CONTENT_TYPE, - hdrs.COOKIE, - hdrs.DATE, - hdrs.DESTINATION, - hdrs.DIGEST, - hdrs.ETAG, - hdrs.EXPECT, - hdrs.EXPIRES, - hdrs.FORWARDED, - hdrs.FROM, - hdrs.HOST, - hdrs.IF_MATCH, - hdrs.IF_MODIFIED_SINCE, - hdrs.IF_NONE_MATCH, - hdrs.IF_RANGE, - hdrs.IF_UNMODIFIED_SINCE, - hdrs.KEEP_ALIVE, - hdrs.LAST_EVENT_ID, - hdrs.LAST_MODIFIED, - hdrs.LINK, - hdrs.LOCATION, - hdrs.MAX_FORWARDS, - hdrs.ORIGIN, - hdrs.PRAGMA, - hdrs.PROXY_AUTHENTICATE, - hdrs.PROXY_AUTHORIZATION, - hdrs.RANGE, - hdrs.REFERER, - hdrs.RETRY_AFTER, - hdrs.SEC_WEBSOCKET_ACCEPT, - hdrs.SEC_WEBSOCKET_EXTENSIONS, - hdrs.SEC_WEBSOCKET_KEY, - hdrs.SEC_WEBSOCKET_KEY1, - hdrs.SEC_WEBSOCKET_PROTOCOL, - hdrs.SEC_WEBSOCKET_VERSION, - hdrs.SERVER, - hdrs.SET_COOKIE, - hdrs.TE, - hdrs.TRAILER, - hdrs.TRANSFER_ENCODING, - hdrs.URI, - hdrs.UPGRADE, - hdrs.USER_AGENT, - hdrs.VARY, - hdrs.VIA, - hdrs.WWW_AUTHENTICATE, - hdrs.WANT_DIGEST, - hdrs.WARNING, - hdrs.X_FORWARDED_FOR, - hdrs.X_FORWARDED_HOST, - hdrs.X_FORWARDED_PROTO, -) diff --git a/.venv/Lib/site-packages/aiohttp/_helpers.c b/.venv/Lib/site-packages/aiohttp/_helpers.c deleted file mode 100644 index 713b9d7..0000000 --- a/.venv/Lib/site-packages/aiohttp/_helpers.c +++ /dev/null @@ -1,5467 +0,0 @@ -/* Generated by Cython 0.29.24 */ - -#ifndef PY_SSIZE_T_CLEAN -#define PY_SSIZE_T_CLEAN -#endif /* PY_SSIZE_T_CLEAN */ -#include "Python.h" -#ifndef Py_PYTHON_H - #error Python headers needed to compile C extensions, please install development version of Python. -#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03030000) - #error Cython requires Python 2.6+ or Python 3.3+. -#else -#define CYTHON_ABI "0_29_24" -#define CYTHON_HEX_VERSION 0x001D18F0 -#define CYTHON_FUTURE_DIVISION 1 -#include -#ifndef offsetof - #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) -#endif -#if !defined(WIN32) && !defined(MS_WINDOWS) - #ifndef __stdcall - #define __stdcall - #endif - #ifndef __cdecl - #define __cdecl - #endif - #ifndef __fastcall - #define __fastcall - #endif -#endif -#ifndef DL_IMPORT - #define DL_IMPORT(t) t -#endif -#ifndef DL_EXPORT - #define DL_EXPORT(t) t -#endif -#define __PYX_COMMA , -#ifndef HAVE_LONG_LONG - #if PY_VERSION_HEX >= 0x02070000 - #define HAVE_LONG_LONG - #endif -#endif -#ifndef PY_LONG_LONG - #define PY_LONG_LONG LONG_LONG -#endif -#ifndef Py_HUGE_VAL - #define Py_HUGE_VAL HUGE_VAL -#endif -#ifdef PYPY_VERSION - #define CYTHON_COMPILING_IN_PYPY 1 - #define CYTHON_COMPILING_IN_PYSTON 0 - #define CYTHON_COMPILING_IN_CPYTHON 0 - #undef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 0 - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #if PY_VERSION_HEX < 0x03050000 - #undef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 0 - #elif !defined(CYTHON_USE_ASYNC_SLOTS) - #define CYTHON_USE_ASYNC_SLOTS 1 - #endif - #undef CYTHON_USE_PYLIST_INTERNALS - #define CYTHON_USE_PYLIST_INTERNALS 0 - #undef CYTHON_USE_UNICODE_INTERNALS - #define CYTHON_USE_UNICODE_INTERNALS 0 - #undef CYTHON_USE_UNICODE_WRITER - #define CYTHON_USE_UNICODE_WRITER 0 - #undef CYTHON_USE_PYLONG_INTERNALS - #define CYTHON_USE_PYLONG_INTERNALS 0 - #undef CYTHON_AVOID_BORROWED_REFS - #define CYTHON_AVOID_BORROWED_REFS 1 - #undef CYTHON_ASSUME_SAFE_MACROS - #define CYTHON_ASSUME_SAFE_MACROS 0 - #undef CYTHON_UNPACK_METHODS - #define CYTHON_UNPACK_METHODS 0 - #undef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 0 - #undef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL 0 - #undef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT 0 - #undef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE 0 - #undef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS 0 - #undef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK 0 -#elif defined(PYSTON_VERSION) - #define CYTHON_COMPILING_IN_PYPY 0 - #define CYTHON_COMPILING_IN_PYSTON 1 - #define CYTHON_COMPILING_IN_CPYTHON 0 - #ifndef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 1 - #endif - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #undef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 0 - #undef CYTHON_USE_PYLIST_INTERNALS - #define CYTHON_USE_PYLIST_INTERNALS 0 - #ifndef CYTHON_USE_UNICODE_INTERNALS - #define CYTHON_USE_UNICODE_INTERNALS 1 - #endif - #undef CYTHON_USE_UNICODE_WRITER - #define CYTHON_USE_UNICODE_WRITER 0 - #undef CYTHON_USE_PYLONG_INTERNALS - #define CYTHON_USE_PYLONG_INTERNALS 0 - #ifndef CYTHON_AVOID_BORROWED_REFS - #define CYTHON_AVOID_BORROWED_REFS 0 - #endif - #ifndef CYTHON_ASSUME_SAFE_MACROS - #define CYTHON_ASSUME_SAFE_MACROS 1 - #endif - #ifndef CYTHON_UNPACK_METHODS - #define CYTHON_UNPACK_METHODS 1 - #endif - #undef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 0 - #undef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL 0 - #undef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT 0 - #undef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE 0 - #undef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS 0 - #undef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK 0 -#else - #define CYTHON_COMPILING_IN_PYPY 0 - #define CYTHON_COMPILING_IN_PYSTON 0 - #define CYTHON_COMPILING_IN_CPYTHON 1 - #ifndef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 1 - #endif - #if PY_VERSION_HEX < 0x02070000 - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #elif !defined(CYTHON_USE_PYTYPE_LOOKUP) - #define CYTHON_USE_PYTYPE_LOOKUP 1 - #endif - #if PY_MAJOR_VERSION < 3 - #undef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 0 - #elif !defined(CYTHON_USE_ASYNC_SLOTS) - #define CYTHON_USE_ASYNC_SLOTS 1 - #endif - #if PY_VERSION_HEX < 0x02070000 - #undef CYTHON_USE_PYLONG_INTERNALS - #define CYTHON_USE_PYLONG_INTERNALS 0 - #elif !defined(CYTHON_USE_PYLONG_INTERNALS) - #define CYTHON_USE_PYLONG_INTERNALS 1 - #endif - #ifndef CYTHON_USE_PYLIST_INTERNALS - #define CYTHON_USE_PYLIST_INTERNALS 1 - #endif - #ifndef CYTHON_USE_UNICODE_INTERNALS - #define CYTHON_USE_UNICODE_INTERNALS 1 - #endif - #if PY_VERSION_HEX < 0x030300F0 - #undef CYTHON_USE_UNICODE_WRITER - #define CYTHON_USE_UNICODE_WRITER 0 - #elif !defined(CYTHON_USE_UNICODE_WRITER) - #define CYTHON_USE_UNICODE_WRITER 1 - #endif - #ifndef CYTHON_AVOID_BORROWED_REFS - #define CYTHON_AVOID_BORROWED_REFS 0 - #endif - #ifndef CYTHON_ASSUME_SAFE_MACROS - #define CYTHON_ASSUME_SAFE_MACROS 1 - #endif - #ifndef CYTHON_UNPACK_METHODS - #define CYTHON_UNPACK_METHODS 1 - #endif - #ifndef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 1 - #endif - #ifndef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL 1 - #endif - #ifndef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT (PY_VERSION_HEX >= 0x03050000) - #endif - #ifndef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE (PY_VERSION_HEX >= 0x030400a1) - #endif - #ifndef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX >= 0x030600B1) - #endif - #ifndef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK (PY_VERSION_HEX >= 0x030700A3) - #endif -#endif -#if !defined(CYTHON_FAST_PYCCALL) -#define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) -#endif -#if CYTHON_USE_PYLONG_INTERNALS - #include "longintrepr.h" - #undef SHIFT - #undef BASE - #undef MASK - #ifdef SIZEOF_VOID_P - enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; - #endif -#endif -#ifndef __has_attribute - #define __has_attribute(x) 0 -#endif -#ifndef __has_cpp_attribute - #define __has_cpp_attribute(x) 0 -#endif -#ifndef CYTHON_RESTRICT - #if defined(__GNUC__) - #define CYTHON_RESTRICT __restrict__ - #elif defined(_MSC_VER) && _MSC_VER >= 1400 - #define CYTHON_RESTRICT __restrict - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_RESTRICT restrict - #else - #define CYTHON_RESTRICT - #endif -#endif -#ifndef CYTHON_UNUSED -# if defined(__GNUC__) -# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) -# define CYTHON_UNUSED __attribute__ ((__unused__)) -# else -# define CYTHON_UNUSED -# endif -# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) -# define CYTHON_UNUSED __attribute__ ((__unused__)) -# else -# define CYTHON_UNUSED -# endif -#endif -#ifndef CYTHON_MAYBE_UNUSED_VAR -# if defined(__cplusplus) - template void CYTHON_MAYBE_UNUSED_VAR( const T& ) { } -# else -# define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x) -# endif -#endif -#ifndef CYTHON_NCP_UNUSED -# if CYTHON_COMPILING_IN_CPYTHON -# define CYTHON_NCP_UNUSED -# else -# define CYTHON_NCP_UNUSED CYTHON_UNUSED -# endif -#endif -#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) -#ifdef _MSC_VER - #ifndef _MSC_STDINT_H_ - #if _MSC_VER < 1300 - typedef unsigned char uint8_t; - typedef unsigned int uint32_t; - #else - typedef unsigned __int8 uint8_t; - typedef unsigned __int32 uint32_t; - #endif - #endif -#else - #include -#endif -#ifndef CYTHON_FALLTHROUGH - #if defined(__cplusplus) && __cplusplus >= 201103L - #if __has_cpp_attribute(fallthrough) - #define CYTHON_FALLTHROUGH [[fallthrough]] - #elif __has_cpp_attribute(clang::fallthrough) - #define CYTHON_FALLTHROUGH [[clang::fallthrough]] - #elif __has_cpp_attribute(gnu::fallthrough) - #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] - #endif - #endif - #ifndef CYTHON_FALLTHROUGH - #if __has_attribute(fallthrough) - #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) - #else - #define CYTHON_FALLTHROUGH - #endif - #endif - #if defined(__clang__ ) && defined(__apple_build_version__) - #if __apple_build_version__ < 7000000 - #undef CYTHON_FALLTHROUGH - #define CYTHON_FALLTHROUGH - #endif - #endif -#endif - -#ifndef CYTHON_INLINE - #if defined(__clang__) - #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) - #elif defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline - #else - #define CYTHON_INLINE - #endif -#endif - -#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) - #define Py_OptimizeFlag 0 -#endif -#define __PYX_BUILD_PY_SSIZE_T "n" -#define CYTHON_FORMAT_SSIZE_T "z" -#if PY_MAJOR_VERSION < 3 - #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) - #define __Pyx_DefaultClassType PyClass_Type -#else - #define __Pyx_BUILTIN_MODULE_NAME "builtins" -#if PY_VERSION_HEX >= 0x030800A4 && PY_VERSION_HEX < 0x030800B2 - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a, 0, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) -#else - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) -#endif - #define __Pyx_DefaultClassType PyType_Type -#endif -#ifndef Py_TPFLAGS_CHECKTYPES - #define Py_TPFLAGS_CHECKTYPES 0 -#endif -#ifndef Py_TPFLAGS_HAVE_INDEX - #define Py_TPFLAGS_HAVE_INDEX 0 -#endif -#ifndef Py_TPFLAGS_HAVE_NEWBUFFER - #define Py_TPFLAGS_HAVE_NEWBUFFER 0 -#endif -#ifndef Py_TPFLAGS_HAVE_FINALIZE - #define Py_TPFLAGS_HAVE_FINALIZE 0 -#endif -#ifndef METH_STACKLESS - #define METH_STACKLESS 0 -#endif -#if PY_VERSION_HEX <= 0x030700A3 || !defined(METH_FASTCALL) - #ifndef METH_FASTCALL - #define METH_FASTCALL 0x80 - #endif - typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); - typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, - Py_ssize_t nargs, PyObject *kwnames); -#else - #define __Pyx_PyCFunctionFast _PyCFunctionFast - #define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords -#endif -#if CYTHON_FAST_PYCCALL -#define __Pyx_PyFastCFunction_Check(func)\ - ((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))))) -#else -#define __Pyx_PyFastCFunction_Check(func) 0 -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) - #define PyObject_Malloc(s) PyMem_Malloc(s) - #define PyObject_Free(p) PyMem_Free(p) - #define PyObject_Realloc(p) PyMem_Realloc(p) -#endif -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030400A1 - #define PyMem_RawMalloc(n) PyMem_Malloc(n) - #define PyMem_RawRealloc(p, n) PyMem_Realloc(p, n) - #define PyMem_RawFree(p) PyMem_Free(p) -#endif -#if CYTHON_COMPILING_IN_PYSTON - #define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co) - #define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno) -#else - #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) - #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) -#endif -#if !CYTHON_FAST_THREAD_STATE || PY_VERSION_HEX < 0x02070000 - #define __Pyx_PyThreadState_Current PyThreadState_GET() -#elif PY_VERSION_HEX >= 0x03060000 - #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() -#elif PY_VERSION_HEX >= 0x03000000 - #define __Pyx_PyThreadState_Current PyThreadState_GET() -#else - #define __Pyx_PyThreadState_Current _PyThreadState_Current -#endif -#if PY_VERSION_HEX < 0x030700A2 && !defined(PyThread_tss_create) && !defined(Py_tss_NEEDS_INIT) -#include "pythread.h" -#define Py_tss_NEEDS_INIT 0 -typedef int Py_tss_t; -static CYTHON_INLINE int PyThread_tss_create(Py_tss_t *key) { - *key = PyThread_create_key(); - return 0; -} -static CYTHON_INLINE Py_tss_t * PyThread_tss_alloc(void) { - Py_tss_t *key = (Py_tss_t *)PyObject_Malloc(sizeof(Py_tss_t)); - *key = Py_tss_NEEDS_INIT; - return key; -} -static CYTHON_INLINE void PyThread_tss_free(Py_tss_t *key) { - PyObject_Free(key); -} -static CYTHON_INLINE int PyThread_tss_is_created(Py_tss_t *key) { - return *key != Py_tss_NEEDS_INIT; -} -static CYTHON_INLINE void PyThread_tss_delete(Py_tss_t *key) { - PyThread_delete_key(*key); - *key = Py_tss_NEEDS_INIT; -} -static CYTHON_INLINE int PyThread_tss_set(Py_tss_t *key, void *value) { - return PyThread_set_key_value(*key, value); -} -static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) { - return PyThread_get_key_value(*key); -} -#endif -#if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) -#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) -#else -#define __Pyx_PyDict_NewPresized(n) PyDict_New() -#endif -#if PY_MAJOR_VERSION >= 3 || CYTHON_FUTURE_DIVISION - #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) -#else - #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) -#endif -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 && CYTHON_USE_UNICODE_INTERNALS -#define __Pyx_PyDict_GetItemStr(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) -#else -#define __Pyx_PyDict_GetItemStr(dict, name) PyDict_GetItem(dict, name) -#endif -#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) - #define CYTHON_PEP393_ENABLED 1 - #if defined(PyUnicode_IS_READY) - #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ - 0 : _PyUnicode_Ready((PyObject *)(op))) - #else - #define __Pyx_PyUnicode_READY(op) (0) - #endif - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) - #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) - #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) - #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) - #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) - #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) - #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch) - #if defined(PyUnicode_IS_READY) && defined(PyUnicode_GET_SIZE) - #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03090000 - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : ((PyCompactUnicodeObject *)(u))->wstr_length)) - #else - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) - #endif - #else - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) - #endif -#else - #define CYTHON_PEP393_ENABLED 0 - #define PyUnicode_1BYTE_KIND 1 - #define PyUnicode_2BYTE_KIND 2 - #define PyUnicode_4BYTE_KIND 4 - #define __Pyx_PyUnicode_READY(op) (0) - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) - #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) - #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111) - #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) - #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) - #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) - #define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch) - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) -#endif -#if CYTHON_COMPILING_IN_PYPY - #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) - #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) -#else - #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) - #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ - PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains) - #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check) - #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format) - #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) -#endif -#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyString_Check(b) && !PyString_CheckExact(b)))) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) -#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) -#else - #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) -#endif -#if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII) - #define PyObject_ASCII(o) PyObject_Repr(o) -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyBaseString_Type PyUnicode_Type - #define PyStringObject PyUnicodeObject - #define PyString_Type PyUnicode_Type - #define PyString_Check PyUnicode_Check - #define PyString_CheckExact PyUnicode_CheckExact -#ifndef PyObject_Unicode - #define PyObject_Unicode PyObject_Str -#endif -#endif -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) - #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) -#else - #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) - #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) -#endif -#ifndef PySet_CheckExact - #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) -#endif -#if PY_VERSION_HEX >= 0x030900A4 - #define __Pyx_SET_REFCNT(obj, refcnt) Py_SET_REFCNT(obj, refcnt) - #define __Pyx_SET_SIZE(obj, size) Py_SET_SIZE(obj, size) -#else - #define __Pyx_SET_REFCNT(obj, refcnt) Py_REFCNT(obj) = (refcnt) - #define __Pyx_SET_SIZE(obj, size) Py_SIZE(obj) = (size) -#endif -#if CYTHON_ASSUME_SAFE_MACROS - #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) -#else - #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyIntObject PyLongObject - #define PyInt_Type PyLong_Type - #define PyInt_Check(op) PyLong_Check(op) - #define PyInt_CheckExact(op) PyLong_CheckExact(op) - #define PyInt_FromString PyLong_FromString - #define PyInt_FromUnicode PyLong_FromUnicode - #define PyInt_FromLong PyLong_FromLong - #define PyInt_FromSize_t PyLong_FromSize_t - #define PyInt_FromSsize_t PyLong_FromSsize_t - #define PyInt_AsLong PyLong_AsLong - #define PyInt_AS_LONG PyLong_AS_LONG - #define PyInt_AsSsize_t PyLong_AsSsize_t - #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask - #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask - #define PyNumber_Int PyNumber_Long -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyBoolObject PyLongObject -#endif -#if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY - #ifndef PyUnicode_InternFromString - #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) - #endif -#endif -#if PY_VERSION_HEX < 0x030200A4 - typedef long Py_hash_t; - #define __Pyx_PyInt_FromHash_t PyInt_FromLong - #define __Pyx_PyInt_AsHash_t PyInt_AsLong -#else - #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t - #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t -#endif -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyMethod_New(func, self, klass) ((self) ? ((void)(klass), PyMethod_New(func, self)) : __Pyx_NewRef(func)) -#else - #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) -#endif -#if CYTHON_USE_ASYNC_SLOTS - #if PY_VERSION_HEX >= 0x030500B1 - #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods - #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) - #else - #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) - #endif -#else - #define __Pyx_PyType_AsAsync(obj) NULL -#endif -#ifndef __Pyx_PyAsyncMethodsStruct - typedef struct { - unaryfunc am_await; - unaryfunc am_aiter; - unaryfunc am_anext; - } __Pyx_PyAsyncMethodsStruct; -#endif - -#if defined(WIN32) || defined(MS_WINDOWS) - #define _USE_MATH_DEFINES -#endif -#include -#ifdef NAN -#define __PYX_NAN() ((float) NAN) -#else -static CYTHON_INLINE float __PYX_NAN() { - float value; - memset(&value, 0xFF, sizeof(value)); - return value; -} -#endif -#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) -#define __Pyx_truncl trunc -#else -#define __Pyx_truncl truncl -#endif - -#define __PYX_MARK_ERR_POS(f_index, lineno) \ - { __pyx_filename = __pyx_f[f_index]; (void)__pyx_filename; __pyx_lineno = lineno; (void)__pyx_lineno; __pyx_clineno = __LINE__; (void)__pyx_clineno; } -#define __PYX_ERR(f_index, lineno, Ln_error) \ - { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; } - -#ifndef __PYX_EXTERN_C - #ifdef __cplusplus - #define __PYX_EXTERN_C extern "C" - #else - #define __PYX_EXTERN_C extern - #endif -#endif - -#define __PYX_HAVE__aiohttp___helpers -#define __PYX_HAVE_API__aiohttp___helpers -/* Early includes */ -#ifdef _OPENMP -#include -#endif /* _OPENMP */ - -#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) -#define CYTHON_WITHOUT_ASSERTIONS -#endif - -typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding; - const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; - -#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 -#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0 -#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT (PY_MAJOR_VERSION >= 3 && __PYX_DEFAULT_STRING_ENCODING_IS_UTF8) -#define __PYX_DEFAULT_STRING_ENCODING "" -#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString -#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize -#define __Pyx_uchar_cast(c) ((unsigned char)c) -#define __Pyx_long_cast(x) ((long)x) -#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ - (sizeof(type) < sizeof(Py_ssize_t)) ||\ - (sizeof(type) > sizeof(Py_ssize_t) &&\ - likely(v < (type)PY_SSIZE_T_MAX ||\ - v == (type)PY_SSIZE_T_MAX) &&\ - (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ - v == (type)PY_SSIZE_T_MIN))) ||\ - (sizeof(type) == sizeof(Py_ssize_t) &&\ - (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ - v == (type)PY_SSIZE_T_MAX))) ) -static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { - return (size_t) i < (size_t) limit; -} -#if defined (__cplusplus) && __cplusplus >= 201103L - #include - #define __Pyx_sst_abs(value) std::abs(value) -#elif SIZEOF_INT >= SIZEOF_SIZE_T - #define __Pyx_sst_abs(value) abs(value) -#elif SIZEOF_LONG >= SIZEOF_SIZE_T - #define __Pyx_sst_abs(value) labs(value) -#elif defined (_MSC_VER) - #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) -#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define __Pyx_sst_abs(value) llabs(value) -#elif defined (__GNUC__) - #define __Pyx_sst_abs(value) __builtin_llabs(value) -#else - #define __Pyx_sst_abs(value) ((value<0) ? -value : value) -#endif -static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); -static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); -#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) -#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) -#define __Pyx_PyBytes_FromString PyBytes_FromString -#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); -#if PY_MAJOR_VERSION < 3 - #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString - #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize -#else - #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString - #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize -#endif -#define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyObject_AsWritableString(s) ((char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsWritableSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) -#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) -#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) -#define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) -#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) -static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) { - const Py_UNICODE *u_end = u; - while (*u_end++) ; - return (size_t)(u_end - u - 1); -} -#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) -#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode -#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode -#define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) -#define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) -static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); -static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); -static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); -static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); -#define __Pyx_PySequence_Tuple(obj)\ - (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) -static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); -static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); -#if CYTHON_ASSUME_SAFE_MACROS -#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) -#else -#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) -#endif -#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) -#if PY_MAJOR_VERSION >= 3 -#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) -#else -#define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x)) -#endif -#define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x)) -#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII -static int __Pyx_sys_getdefaultencoding_not_ascii; -static int __Pyx_init_sys_getdefaultencoding_params(void) { - PyObject* sys; - PyObject* default_encoding = NULL; - PyObject* ascii_chars_u = NULL; - PyObject* ascii_chars_b = NULL; - const char* default_encoding_c; - sys = PyImport_ImportModule("sys"); - if (!sys) goto bad; - default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); - Py_DECREF(sys); - if (!default_encoding) goto bad; - default_encoding_c = PyBytes_AsString(default_encoding); - if (!default_encoding_c) goto bad; - if (strcmp(default_encoding_c, "ascii") == 0) { - __Pyx_sys_getdefaultencoding_not_ascii = 0; - } else { - char ascii_chars[128]; - int c; - for (c = 0; c < 128; c++) { - ascii_chars[c] = c; - } - __Pyx_sys_getdefaultencoding_not_ascii = 1; - ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); - if (!ascii_chars_u) goto bad; - ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); - if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { - PyErr_Format( - PyExc_ValueError, - "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", - default_encoding_c); - goto bad; - } - Py_DECREF(ascii_chars_u); - Py_DECREF(ascii_chars_b); - } - Py_DECREF(default_encoding); - return 0; -bad: - Py_XDECREF(default_encoding); - Py_XDECREF(ascii_chars_u); - Py_XDECREF(ascii_chars_b); - return -1; -} -#endif -#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 -#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) -#else -#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) -#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT -static char* __PYX_DEFAULT_STRING_ENCODING; -static int __Pyx_init_sys_getdefaultencoding_params(void) { - PyObject* sys; - PyObject* default_encoding = NULL; - char* default_encoding_c; - sys = PyImport_ImportModule("sys"); - if (!sys) goto bad; - default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); - Py_DECREF(sys); - if (!default_encoding) goto bad; - default_encoding_c = PyBytes_AsString(default_encoding); - if (!default_encoding_c) goto bad; - __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c) + 1); - if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; - strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); - Py_DECREF(default_encoding); - return 0; -bad: - Py_XDECREF(default_encoding); - return -1; -} -#endif -#endif - - -/* Test for GCC > 2.95 */ -#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) - #define likely(x) __builtin_expect(!!(x), 1) - #define unlikely(x) __builtin_expect(!!(x), 0) -#else /* !__GNUC__ or GCC < 2.95 */ - #define likely(x) (x) - #define unlikely(x) (x) -#endif /* __GNUC__ */ -static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } - -static PyObject *__pyx_m = NULL; -static PyObject *__pyx_d; -static PyObject *__pyx_b; -static PyObject *__pyx_cython_runtime = NULL; -static PyObject *__pyx_empty_tuple; -static PyObject *__pyx_empty_bytes; -static PyObject *__pyx_empty_unicode; -static int __pyx_lineno; -static int __pyx_clineno = 0; -static const char * __pyx_cfilenm= __FILE__; -static const char *__pyx_filename; - - -static const char *__pyx_f[] = { - "aiohttp\\_helpers.pyx", - "stringsource", -}; - -/*--- Type declarations ---*/ -struct __pyx_obj_7aiohttp_8_helpers_reify; - -/* "aiohttp/_helpers.pyx":1 - * cdef class reify: # <<<<<<<<<<<<<< - * """Use as a class method decorator. It operates almost exactly like - * the Python `@property` decorator, but it puts the result of the - */ -struct __pyx_obj_7aiohttp_8_helpers_reify { - PyObject_HEAD - PyObject *wrapped; - PyObject *name; -}; - - -/* --- Runtime support code (head) --- */ -/* Refnanny.proto */ -#ifndef CYTHON_REFNANNY - #define CYTHON_REFNANNY 0 -#endif -#if CYTHON_REFNANNY - typedef struct { - void (*INCREF)(void*, PyObject*, int); - void (*DECREF)(void*, PyObject*, int); - void (*GOTREF)(void*, PyObject*, int); - void (*GIVEREF)(void*, PyObject*, int); - void* (*SetupContext)(const char*, int, const char*); - void (*FinishContext)(void**); - } __Pyx_RefNannyAPIStruct; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); - #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; -#ifdef WITH_THREAD - #define __Pyx_RefNannySetupContext(name, acquire_gil)\ - if (acquire_gil) {\ - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ - PyGILState_Release(__pyx_gilstate_save);\ - } else {\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ - } -#else - #define __Pyx_RefNannySetupContext(name, acquire_gil)\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) -#endif - #define __Pyx_RefNannyFinishContext()\ - __Pyx_RefNanny->FinishContext(&__pyx_refnanny) - #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) - #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) - #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) - #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) -#else - #define __Pyx_RefNannyDeclarations - #define __Pyx_RefNannySetupContext(name, acquire_gil) - #define __Pyx_RefNannyFinishContext() - #define __Pyx_INCREF(r) Py_INCREF(r) - #define __Pyx_DECREF(r) Py_DECREF(r) - #define __Pyx_GOTREF(r) - #define __Pyx_GIVEREF(r) - #define __Pyx_XINCREF(r) Py_XINCREF(r) - #define __Pyx_XDECREF(r) Py_XDECREF(r) - #define __Pyx_XGOTREF(r) - #define __Pyx_XGIVEREF(r) -#endif -#define __Pyx_XDECREF_SET(r, v) do {\ - PyObject *tmp = (PyObject *) r;\ - r = v; __Pyx_XDECREF(tmp);\ - } while (0) -#define __Pyx_DECREF_SET(r, v) do {\ - PyObject *tmp = (PyObject *) r;\ - r = v; __Pyx_DECREF(tmp);\ - } while (0) -#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) -#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) - -/* PyObjectGetAttrStr.proto */ -#if CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); -#else -#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) -#endif - -/* GetBuiltinName.proto */ -static PyObject *__Pyx_GetBuiltinName(PyObject *name); - -/* RaiseDoubleKeywords.proto */ -static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); - -/* ParseKeywords.proto */ -static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\ - PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\ - const char* function_name); - -/* RaiseArgTupleInvalid.proto */ -static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, - Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); - -/* GetItemInt.proto */ -#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ - __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) :\ - (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) :\ - __Pyx_GetItemInt_Generic(o, to_py_func(i)))) -#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ - __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ - (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, - int wraparound, int boundscheck); -#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ - __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ - (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, - int wraparound, int boundscheck); -static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, - int is_list, int wraparound, int boundscheck); - -/* ObjectGetItem.proto */ -#if CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject* key); -#else -#define __Pyx_PyObject_GetItem(obj, key) PyObject_GetItem(obj, key) -#endif - -/* GetTopmostException.proto */ -#if CYTHON_USE_EXC_INFO_STACK -static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate); -#endif - -/* PyThreadStateGet.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; -#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; -#define __Pyx_PyErr_Occurred() __pyx_tstate->curexc_type -#else -#define __Pyx_PyThreadState_declare -#define __Pyx_PyThreadState_assign -#define __Pyx_PyErr_Occurred() PyErr_Occurred() -#endif - -/* SaveResetException.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); -#else -#define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) -#define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) -#endif - -/* PyErrExceptionMatches.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) -static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); -#else -#define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) -#endif - -/* GetException.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) -static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#else -static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); -#endif - -/* PyCFunctionFastCall.proto */ -#if CYTHON_FAST_PYCCALL -static CYTHON_INLINE PyObject *__Pyx_PyCFunction_FastCall(PyObject *func, PyObject **args, Py_ssize_t nargs); -#else -#define __Pyx_PyCFunction_FastCall(func, args, nargs) (assert(0), NULL) -#endif - -/* PyFunctionFastCall.proto */ -#if CYTHON_FAST_PYCALL -#define __Pyx_PyFunction_FastCall(func, args, nargs)\ - __Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL) -#if 1 || PY_VERSION_HEX < 0x030600B1 -static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs); -#else -#define __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs) _PyFunction_FastCallDict(func, args, nargs, kwargs) -#endif -#define __Pyx_BUILD_ASSERT_EXPR(cond)\ - (sizeof(char [1 - 2*!(cond)]) - 1) -#ifndef Py_MEMBER_SIZE -#define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member) -#endif - static size_t __pyx_pyframe_localsplus_offset = 0; - #include "frameobject.h" - #define __Pxy_PyFrame_Initialize_Offsets()\ - ((void)__Pyx_BUILD_ASSERT_EXPR(sizeof(PyFrameObject) == offsetof(PyFrameObject, f_localsplus) + Py_MEMBER_SIZE(PyFrameObject, f_localsplus)),\ - (void)(__pyx_pyframe_localsplus_offset = ((size_t)PyFrame_Type.tp_basicsize) - Py_MEMBER_SIZE(PyFrameObject, f_localsplus))) - #define __Pyx_PyFrame_GetLocalsplus(frame)\ - (assert(__pyx_pyframe_localsplus_offset), (PyObject **)(((char *)(frame)) + __pyx_pyframe_localsplus_offset)) -#endif - -/* PyObjectCall.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); -#else -#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) -#endif - -/* PyObjectCall2Args.proto */ -static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); - -/* PyObjectCallMethO.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); -#endif - -/* PyObjectCallOneArg.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); - -/* PyErrFetchRestore.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) -#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) -#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) -#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) -#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); -static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#if CYTHON_COMPILING_IN_CPYTHON -#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) -#else -#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) -#endif -#else -#define __Pyx_PyErr_Clear() PyErr_Clear() -#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) -#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) -#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) -#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) -#endif - -/* RaiseException.proto */ -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); - -/* GetAttr.proto */ -static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); - -/* GetAttr3.proto */ -static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); - -/* PyDictVersioning.proto */ -#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS -#define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1) -#define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) -#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ - (version_var) = __PYX_GET_DICT_VERSION(dict);\ - (cache_var) = (value); -#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ - static PY_UINT64_T __pyx_dict_version = 0;\ - static PyObject *__pyx_dict_cached_value = NULL;\ - if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ - (VAR) = __pyx_dict_cached_value;\ - } else {\ - (VAR) = __pyx_dict_cached_value = (LOOKUP);\ - __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ - }\ -} -static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj); -static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj); -static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version); -#else -#define __PYX_GET_DICT_VERSION(dict) (0) -#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) -#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); -#endif - -/* GetModuleGlobalName.proto */ -#if CYTHON_USE_DICT_VERSIONS -#define __Pyx_GetModuleGlobalName(var, name) {\ - static PY_UINT64_T __pyx_dict_version = 0;\ - static PyObject *__pyx_dict_cached_value = NULL;\ - (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_d))) ?\ - (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ - __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ -} -#define __Pyx_GetModuleGlobalNameUncached(var, name) {\ - PY_UINT64_T __pyx_dict_version;\ - PyObject *__pyx_dict_cached_value;\ - (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ -} -static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); -#else -#define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) -#define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) -static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); -#endif - -/* Import.proto */ -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); - -/* ImportFrom.proto */ -static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); - -/* HasAttr.proto */ -static CYTHON_INLINE int __Pyx_HasAttr(PyObject *, PyObject *); - -/* PyObject_GenericGetAttrNoDict.proto */ -#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 -static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name); -#else -#define __Pyx_PyObject_GenericGetAttrNoDict PyObject_GenericGetAttr -#endif - -/* PyObject_GenericGetAttr.proto */ -#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 -static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name); -#else -#define __Pyx_PyObject_GenericGetAttr PyObject_GenericGetAttr -#endif - -/* PyObjectGetAttrStrNoError.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name); - -/* SetupReduce.proto */ -static int __Pyx_setup_reduce(PyObject* type_obj); - -/* CLineInTraceback.proto */ -#ifdef CYTHON_CLINE_IN_TRACEBACK -#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) -#else -static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); -#endif - -/* CodeObjectCache.proto */ -typedef struct { - PyCodeObject* code_object; - int code_line; -} __Pyx_CodeObjectCacheEntry; -struct __Pyx_CodeObjectCache { - int count; - int max_count; - __Pyx_CodeObjectCacheEntry* entries; -}; -static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); -static PyCodeObject *__pyx_find_code_object(int code_line); -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); - -/* AddTraceback.proto */ -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename); - -/* GCCDiagnostics.proto */ -#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) -#define __Pyx_HAS_GCC_DIAGNOSTIC -#endif - -/* CIntFromPy.proto */ -static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); - -/* CIntToPy.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); - -/* CIntFromPy.proto */ -static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); - -/* FastTypeChecks.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) -static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); -static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); -static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); -#else -#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) -#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) -#define __Pyx_PyErr_GivenExceptionMatches2(err, type1, type2) (PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2)) -#endif -#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) - -/* CheckBinaryVersion.proto */ -static int __Pyx_check_binary_version(void); - -/* InitStrings.proto */ -static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); - - -/* Module declarations from 'aiohttp._helpers' */ -static PyTypeObject *__pyx_ptype_7aiohttp_8_helpers_reify = 0; -static PyObject *__pyx_f_7aiohttp_8_helpers___pyx_unpickle_reify__set_state(struct __pyx_obj_7aiohttp_8_helpers_reify *, PyObject *); /*proto*/ -#define __Pyx_MODULE_NAME "aiohttp._helpers" -extern int __pyx_module_is_main_aiohttp___helpers; -int __pyx_module_is_main_aiohttp___helpers = 0; - -/* Implementation of 'aiohttp._helpers' */ -static PyObject *__pyx_builtin_KeyError; -static PyObject *__pyx_builtin_AttributeError; -static const char __pyx_k_doc[] = "__doc__"; -static const char __pyx_k_new[] = "__new__"; -static const char __pyx_k_dict[] = "__dict__"; -static const char __pyx_k_main[] = "__main__"; -static const char __pyx_k_name[] = "__name__"; -static const char __pyx_k_test[] = "__test__"; -static const char __pyx_k_cache[] = "_cache"; -static const char __pyx_k_reify[] = "reify"; -static const char __pyx_k_import[] = "__import__"; -static const char __pyx_k_pickle[] = "pickle"; -static const char __pyx_k_reduce[] = "__reduce__"; -static const char __pyx_k_update[] = "update"; -static const char __pyx_k_wrapped[] = "wrapped"; -static const char __pyx_k_KeyError[] = "KeyError"; -static const char __pyx_k_getstate[] = "__getstate__"; -static const char __pyx_k_pyx_type[] = "__pyx_type"; -static const char __pyx_k_setstate[] = "__setstate__"; -static const char __pyx_k_pyx_state[] = "__pyx_state"; -static const char __pyx_k_reduce_ex[] = "__reduce_ex__"; -static const char __pyx_k_pyx_result[] = "__pyx_result"; -static const char __pyx_k_PickleError[] = "PickleError"; -static const char __pyx_k_pyx_checksum[] = "__pyx_checksum"; -static const char __pyx_k_stringsource[] = "stringsource"; -static const char __pyx_k_reduce_cython[] = "__reduce_cython__"; -static const char __pyx_k_AttributeError[] = "AttributeError"; -static const char __pyx_k_pyx_PickleError[] = "__pyx_PickleError"; -static const char __pyx_k_setstate_cython[] = "__setstate_cython__"; -static const char __pyx_k_aiohttp__helpers[] = "aiohttp._helpers"; -static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback"; -static const char __pyx_k_pyx_unpickle_reify[] = "__pyx_unpickle_reify"; -static const char __pyx_k_reified_property_is_read_only[] = "reified property is read-only"; -static const char __pyx_k_Incompatible_checksums_s_vs_0x77[] = "Incompatible checksums (%s vs 0x770cb8f = (name, wrapped))"; -static PyObject *__pyx_n_s_AttributeError; -static PyObject *__pyx_kp_s_Incompatible_checksums_s_vs_0x77; -static PyObject *__pyx_n_s_KeyError; -static PyObject *__pyx_n_s_PickleError; -static PyObject *__pyx_n_s_aiohttp__helpers; -static PyObject *__pyx_n_s_cache; -static PyObject *__pyx_n_s_cline_in_traceback; -static PyObject *__pyx_n_s_dict; -static PyObject *__pyx_n_s_doc; -static PyObject *__pyx_n_s_getstate; -static PyObject *__pyx_n_s_import; -static PyObject *__pyx_n_s_main; -static PyObject *__pyx_n_s_name; -static PyObject *__pyx_n_s_new; -static PyObject *__pyx_n_s_pickle; -static PyObject *__pyx_n_s_pyx_PickleError; -static PyObject *__pyx_n_s_pyx_checksum; -static PyObject *__pyx_n_s_pyx_result; -static PyObject *__pyx_n_s_pyx_state; -static PyObject *__pyx_n_s_pyx_type; -static PyObject *__pyx_n_s_pyx_unpickle_reify; -static PyObject *__pyx_n_s_reduce; -static PyObject *__pyx_n_s_reduce_cython; -static PyObject *__pyx_n_s_reduce_ex; -static PyObject *__pyx_kp_u_reified_property_is_read_only; -static PyObject *__pyx_n_s_reify; -static PyObject *__pyx_n_s_setstate; -static PyObject *__pyx_n_s_setstate_cython; -static PyObject *__pyx_kp_s_stringsource; -static PyObject *__pyx_n_s_test; -static PyObject *__pyx_n_s_update; -static PyObject *__pyx_n_s_wrapped; -static int __pyx_pf_7aiohttp_8_helpers_5reify___init__(struct __pyx_obj_7aiohttp_8_helpers_reify *__pyx_v_self, PyObject *__pyx_v_wrapped); /* proto */ -static PyObject *__pyx_pf_7aiohttp_8_helpers_5reify_7__doc_____get__(struct __pyx_obj_7aiohttp_8_helpers_reify *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7aiohttp_8_helpers_5reify_2__get__(struct __pyx_obj_7aiohttp_8_helpers_reify *__pyx_v_self, PyObject *__pyx_v_inst, CYTHON_UNUSED PyObject *__pyx_v_owner); /* proto */ -static int __pyx_pf_7aiohttp_8_helpers_5reify_4__set__(CYTHON_UNUSED struct __pyx_obj_7aiohttp_8_helpers_reify *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v_inst, CYTHON_UNUSED PyObject *__pyx_v_value); /* proto */ -static PyObject *__pyx_pf_7aiohttp_8_helpers_5reify_6__reduce_cython__(struct __pyx_obj_7aiohttp_8_helpers_reify *__pyx_v_self); /* proto */ -static PyObject *__pyx_pf_7aiohttp_8_helpers_5reify_8__setstate_cython__(struct __pyx_obj_7aiohttp_8_helpers_reify *__pyx_v_self, PyObject *__pyx_v___pyx_state); /* proto */ -static PyObject *__pyx_pf_7aiohttp_8_helpers___pyx_unpickle_reify(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state); /* proto */ -static PyObject *__pyx_tp_new_7aiohttp_8_helpers_reify(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_int_124832655; -static PyObject *__pyx_tuple_; -static PyObject *__pyx_tuple__2; -static PyObject *__pyx_codeobj__3; -/* Late includes */ - -/* "aiohttp/_helpers.pyx":13 - * cdef object name - * - * def __init__(self, wrapped): # <<<<<<<<<<<<<< - * self.wrapped = wrapped - * self.name = wrapped.__name__ - */ - -/* Python wrapper */ -static int __pyx_pw_7aiohttp_8_helpers_5reify_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pw_7aiohttp_8_helpers_5reify_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_wrapped = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_wrapped,0}; - PyObject* values[1] = {0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_wrapped)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) __PYX_ERR(0, 13, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - } - __pyx_v_wrapped = values[0]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 13, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._helpers.reify.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_8_helpers_5reify___init__(((struct __pyx_obj_7aiohttp_8_helpers_reify *)__pyx_v_self), __pyx_v_wrapped); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_7aiohttp_8_helpers_5reify___init__(struct __pyx_obj_7aiohttp_8_helpers_reify *__pyx_v_self, PyObject *__pyx_v_wrapped) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__init__", 0); - - /* "aiohttp/_helpers.pyx":14 - * - * def __init__(self, wrapped): - * self.wrapped = wrapped # <<<<<<<<<<<<<< - * self.name = wrapped.__name__ - * - */ - __Pyx_INCREF(__pyx_v_wrapped); - __Pyx_GIVEREF(__pyx_v_wrapped); - __Pyx_GOTREF(__pyx_v_self->wrapped); - __Pyx_DECREF(__pyx_v_self->wrapped); - __pyx_v_self->wrapped = __pyx_v_wrapped; - - /* "aiohttp/_helpers.pyx":15 - * def __init__(self, wrapped): - * self.wrapped = wrapped - * self.name = wrapped.__name__ # <<<<<<<<<<<<<< - * - * @property - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_wrapped, __pyx_n_s_name); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 15, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v_self->name); - __Pyx_DECREF(__pyx_v_self->name); - __pyx_v_self->name = __pyx_t_1; - __pyx_t_1 = 0; - - /* "aiohttp/_helpers.pyx":13 - * cdef object name - * - * def __init__(self, wrapped): # <<<<<<<<<<<<<< - * self.wrapped = wrapped - * self.name = wrapped.__name__ - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._helpers.reify.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_helpers.pyx":18 - * - * @property - * def __doc__(self): # <<<<<<<<<<<<<< - * return self.wrapped.__doc__ - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_8_helpers_5reify_7__doc___1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_8_helpers_5reify_7__doc___1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_8_helpers_5reify_7__doc_____get__(((struct __pyx_obj_7aiohttp_8_helpers_reify *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_8_helpers_5reify_7__doc_____get__(struct __pyx_obj_7aiohttp_8_helpers_reify *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "aiohttp/_helpers.pyx":19 - * @property - * def __doc__(self): - * return self.wrapped.__doc__ # <<<<<<<<<<<<<< - * - * def __get__(self, inst, owner): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_self->wrapped, __pyx_n_s_doc); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 19, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "aiohttp/_helpers.pyx":18 - * - * @property - * def __doc__(self): # <<<<<<<<<<<<<< - * return self.wrapped.__doc__ - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._helpers.reify.__doc__.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_helpers.pyx":21 - * return self.wrapped.__doc__ - * - * def __get__(self, inst, owner): # <<<<<<<<<<<<<< - * try: - * try: - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_8_helpers_5reify_3__get__(PyObject *__pyx_v_self, PyObject *__pyx_v_inst, PyObject *__pyx_v_owner); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_8_helpers_5reify_3__get__(PyObject *__pyx_v_self, PyObject *__pyx_v_inst, PyObject *__pyx_v_owner) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_8_helpers_5reify_2__get__(((struct __pyx_obj_7aiohttp_8_helpers_reify *)__pyx_v_self), ((PyObject *)__pyx_v_inst), ((PyObject *)__pyx_v_owner)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_8_helpers_5reify_2__get__(struct __pyx_obj_7aiohttp_8_helpers_reify *__pyx_v_self, PyObject *__pyx_v_inst, CYTHON_UNUSED PyObject *__pyx_v_owner) { - PyObject *__pyx_v_val = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - int __pyx_t_9; - PyObject *__pyx_t_10 = NULL; - PyObject *__pyx_t_11 = NULL; - PyObject *__pyx_t_12 = NULL; - PyObject *__pyx_t_13 = NULL; - int __pyx_t_14; - int __pyx_t_15; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - - /* "aiohttp/_helpers.pyx":22 - * - * def __get__(self, inst, owner): - * try: # <<<<<<<<<<<<<< - * try: - * return inst._cache[self.name] - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); - __Pyx_XGOTREF(__pyx_t_1); - __Pyx_XGOTREF(__pyx_t_2); - __Pyx_XGOTREF(__pyx_t_3); - /*try:*/ { - - /* "aiohttp/_helpers.pyx":23 - * def __get__(self, inst, owner): - * try: - * try: # <<<<<<<<<<<<<< - * return inst._cache[self.name] - * except KeyError: - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_4, &__pyx_t_5, &__pyx_t_6); - __Pyx_XGOTREF(__pyx_t_4); - __Pyx_XGOTREF(__pyx_t_5); - __Pyx_XGOTREF(__pyx_t_6); - /*try:*/ { - - /* "aiohttp/_helpers.pyx":24 - * try: - * try: - * return inst._cache[self.name] # <<<<<<<<<<<<<< - * except KeyError: - * val = self.wrapped(inst) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_v_inst, __pyx_n_s_cache); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 24, __pyx_L9_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_8 = __Pyx_PyObject_GetItem(__pyx_t_7, __pyx_v_self->name); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 24, __pyx_L9_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __pyx_r = __pyx_t_8; - __pyx_t_8 = 0; - goto __pyx_L13_try_return; - - /* "aiohttp/_helpers.pyx":23 - * def __get__(self, inst, owner): - * try: - * try: # <<<<<<<<<<<<<< - * return inst._cache[self.name] - * except KeyError: - */ - } - __pyx_L9_error:; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - - /* "aiohttp/_helpers.pyx":25 - * try: - * return inst._cache[self.name] - * except KeyError: # <<<<<<<<<<<<<< - * val = self.wrapped(inst) - * inst._cache[self.name] = val - */ - __pyx_t_9 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_KeyError); - if (__pyx_t_9) { - __Pyx_AddTraceback("aiohttp._helpers.reify.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_8, &__pyx_t_7, &__pyx_t_10) < 0) __PYX_ERR(0, 25, __pyx_L11_except_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_GOTREF(__pyx_t_7); - __Pyx_GOTREF(__pyx_t_10); - - /* "aiohttp/_helpers.pyx":26 - * return inst._cache[self.name] - * except KeyError: - * val = self.wrapped(inst) # <<<<<<<<<<<<<< - * inst._cache[self.name] = val - * return val - */ - __Pyx_INCREF(__pyx_v_self->wrapped); - __pyx_t_12 = __pyx_v_self->wrapped; __pyx_t_13 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_12))) { - __pyx_t_13 = PyMethod_GET_SELF(__pyx_t_12); - if (likely(__pyx_t_13)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_12); - __Pyx_INCREF(__pyx_t_13); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_12, function); - } - } - __pyx_t_11 = (__pyx_t_13) ? __Pyx_PyObject_Call2Args(__pyx_t_12, __pyx_t_13, __pyx_v_inst) : __Pyx_PyObject_CallOneArg(__pyx_t_12, __pyx_v_inst); - __Pyx_XDECREF(__pyx_t_13); __pyx_t_13 = 0; - if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 26, __pyx_L11_except_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; - __pyx_v_val = __pyx_t_11; - __pyx_t_11 = 0; - - /* "aiohttp/_helpers.pyx":27 - * except KeyError: - * val = self.wrapped(inst) - * inst._cache[self.name] = val # <<<<<<<<<<<<<< - * return val - * except AttributeError: - */ - __pyx_t_11 = __Pyx_PyObject_GetAttrStr(__pyx_v_inst, __pyx_n_s_cache); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 27, __pyx_L11_except_error) - __Pyx_GOTREF(__pyx_t_11); - if (unlikely(PyObject_SetItem(__pyx_t_11, __pyx_v_self->name, __pyx_v_val) < 0)) __PYX_ERR(0, 27, __pyx_L11_except_error) - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - - /* "aiohttp/_helpers.pyx":28 - * val = self.wrapped(inst) - * inst._cache[self.name] = val - * return val # <<<<<<<<<<<<<< - * except AttributeError: - * if inst is None: - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_val); - __pyx_r = __pyx_v_val; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - goto __pyx_L12_except_return; - } - goto __pyx_L11_except_error; - __pyx_L11_except_error:; - - /* "aiohttp/_helpers.pyx":23 - * def __get__(self, inst, owner): - * try: - * try: # <<<<<<<<<<<<<< - * return inst._cache[self.name] - * except KeyError: - */ - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_XGIVEREF(__pyx_t_5); - __Pyx_XGIVEREF(__pyx_t_6); - __Pyx_ExceptionReset(__pyx_t_4, __pyx_t_5, __pyx_t_6); - goto __pyx_L3_error; - __pyx_L13_try_return:; - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_XGIVEREF(__pyx_t_5); - __Pyx_XGIVEREF(__pyx_t_6); - __Pyx_ExceptionReset(__pyx_t_4, __pyx_t_5, __pyx_t_6); - goto __pyx_L7_try_return; - __pyx_L12_except_return:; - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_XGIVEREF(__pyx_t_5); - __Pyx_XGIVEREF(__pyx_t_6); - __Pyx_ExceptionReset(__pyx_t_4, __pyx_t_5, __pyx_t_6); - goto __pyx_L7_try_return; - } - - /* "aiohttp/_helpers.pyx":22 - * - * def __get__(self, inst, owner): - * try: # <<<<<<<<<<<<<< - * try: - * return inst._cache[self.name] - */ - } - __pyx_L3_error:; - __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_XDECREF(__pyx_t_12); __pyx_t_12 = 0; - __Pyx_XDECREF(__pyx_t_13); __pyx_t_13 = 0; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - - /* "aiohttp/_helpers.pyx":29 - * inst._cache[self.name] = val - * return val - * except AttributeError: # <<<<<<<<<<<<<< - * if inst is None: - * return self - */ - __pyx_t_9 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_AttributeError); - if (__pyx_t_9) { - __Pyx_AddTraceback("aiohttp._helpers.reify.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_10, &__pyx_t_7, &__pyx_t_8) < 0) __PYX_ERR(0, 29, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_GOTREF(__pyx_t_7); - __Pyx_GOTREF(__pyx_t_8); - - /* "aiohttp/_helpers.pyx":30 - * return val - * except AttributeError: - * if inst is None: # <<<<<<<<<<<<<< - * return self - * raise - */ - __pyx_t_14 = (__pyx_v_inst == Py_None); - __pyx_t_15 = (__pyx_t_14 != 0); - if (__pyx_t_15) { - - /* "aiohttp/_helpers.pyx":31 - * except AttributeError: - * if inst is None: - * return self # <<<<<<<<<<<<<< - * raise - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_self)); - __pyx_r = ((PyObject *)__pyx_v_self); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - goto __pyx_L6_except_return; - - /* "aiohttp/_helpers.pyx":30 - * return val - * except AttributeError: - * if inst is None: # <<<<<<<<<<<<<< - * return self - * raise - */ - } - - /* "aiohttp/_helpers.pyx":32 - * if inst is None: - * return self - * raise # <<<<<<<<<<<<<< - * - * def __set__(self, inst, value): - */ - __Pyx_GIVEREF(__pyx_t_10); - __Pyx_GIVEREF(__pyx_t_7); - __Pyx_XGIVEREF(__pyx_t_8); - __Pyx_ErrRestoreWithState(__pyx_t_10, __pyx_t_7, __pyx_t_8); - __pyx_t_10 = 0; __pyx_t_7 = 0; __pyx_t_8 = 0; - __PYX_ERR(0, 32, __pyx_L5_except_error) - } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; - - /* "aiohttp/_helpers.pyx":22 - * - * def __get__(self, inst, owner): - * try: # <<<<<<<<<<<<<< - * try: - * return inst._cache[self.name] - */ - __Pyx_XGIVEREF(__pyx_t_1); - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); - goto __pyx_L1_error; - __pyx_L7_try_return:; - __Pyx_XGIVEREF(__pyx_t_1); - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); - goto __pyx_L0; - __pyx_L6_except_return:; - __Pyx_XGIVEREF(__pyx_t_1); - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); - goto __pyx_L0; - } - - /* "aiohttp/_helpers.pyx":21 - * return self.wrapped.__doc__ - * - * def __get__(self, inst, owner): # <<<<<<<<<<<<<< - * try: - * try: - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_XDECREF(__pyx_t_11); - __Pyx_XDECREF(__pyx_t_12); - __Pyx_XDECREF(__pyx_t_13); - __Pyx_AddTraceback("aiohttp._helpers.reify.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_val); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_helpers.pyx":34 - * raise - * - * def __set__(self, inst, value): # <<<<<<<<<<<<<< - * raise AttributeError("reified property is read-only") - */ - -/* Python wrapper */ -static int __pyx_pw_7aiohttp_8_helpers_5reify_5__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_inst, PyObject *__pyx_v_value); /*proto*/ -static int __pyx_pw_7aiohttp_8_helpers_5reify_5__set__(PyObject *__pyx_v_self, PyObject *__pyx_v_inst, PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__set__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_8_helpers_5reify_4__set__(((struct __pyx_obj_7aiohttp_8_helpers_reify *)__pyx_v_self), ((PyObject *)__pyx_v_inst), ((PyObject *)__pyx_v_value)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_7aiohttp_8_helpers_5reify_4__set__(CYTHON_UNUSED struct __pyx_obj_7aiohttp_8_helpers_reify *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v_inst, CYTHON_UNUSED PyObject *__pyx_v_value) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__set__", 0); - - /* "aiohttp/_helpers.pyx":35 - * - * def __set__(self, inst, value): - * raise AttributeError("reified property is read-only") # <<<<<<<<<<<<<< - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_AttributeError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 35, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(0, 35, __pyx_L1_error) - - /* "aiohttp/_helpers.pyx":34 - * raise - * - * def __set__(self, inst, value): # <<<<<<<<<<<<<< - * raise AttributeError("reified property is read-only") - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._helpers.reify.__set__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * cdef tuple state - * cdef object _dict - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_8_helpers_5reify_7__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_8_helpers_5reify_7__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_8_helpers_5reify_6__reduce_cython__(((struct __pyx_obj_7aiohttp_8_helpers_reify *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_8_helpers_5reify_6__reduce_cython__(struct __pyx_obj_7aiohttp_8_helpers_reify *__pyx_v_self) { - PyObject *__pyx_v_state = 0; - PyObject *__pyx_v__dict = 0; - int __pyx_v_use_setstate; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - PyObject *__pyx_t_6 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce_cython__", 0); - - /* "(tree fragment)":5 - * cdef object _dict - * cdef bint use_setstate - * state = (self.name, self.wrapped) # <<<<<<<<<<<<<< - * _dict = getattr(self, '__dict__', None) - * if _dict is not None: - */ - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_self->name); - __Pyx_GIVEREF(__pyx_v_self->name); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_self->name); - __Pyx_INCREF(__pyx_v_self->wrapped); - __Pyx_GIVEREF(__pyx_v_self->wrapped); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_self->wrapped); - __pyx_v_state = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "(tree fragment)":6 - * cdef bint use_setstate - * state = (self.name, self.wrapped) - * _dict = getattr(self, '__dict__', None) # <<<<<<<<<<<<<< - * if _dict is not None: - * state += (_dict,) - */ - __pyx_t_1 = __Pyx_GetAttr3(((PyObject *)__pyx_v_self), __pyx_n_s_dict, Py_None); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v__dict = __pyx_t_1; - __pyx_t_1 = 0; - - /* "(tree fragment)":7 - * state = (self.name, self.wrapped) - * _dict = getattr(self, '__dict__', None) - * if _dict is not None: # <<<<<<<<<<<<<< - * state += (_dict,) - * use_setstate = True - */ - __pyx_t_2 = (__pyx_v__dict != Py_None); - __pyx_t_3 = (__pyx_t_2 != 0); - if (__pyx_t_3) { - - /* "(tree fragment)":8 - * _dict = getattr(self, '__dict__', None) - * if _dict is not None: - * state += (_dict,) # <<<<<<<<<<<<<< - * use_setstate = True - * else: - */ - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 8, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v__dict); - __Pyx_GIVEREF(__pyx_v__dict); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v__dict); - __pyx_t_4 = PyNumber_InPlaceAdd(__pyx_v_state, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 8, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF_SET(__pyx_v_state, ((PyObject*)__pyx_t_4)); - __pyx_t_4 = 0; - - /* "(tree fragment)":9 - * if _dict is not None: - * state += (_dict,) - * use_setstate = True # <<<<<<<<<<<<<< - * else: - * use_setstate = self.name is not None or self.wrapped is not None - */ - __pyx_v_use_setstate = 1; - - /* "(tree fragment)":7 - * state = (self.name, self.wrapped) - * _dict = getattr(self, '__dict__', None) - * if _dict is not None: # <<<<<<<<<<<<<< - * state += (_dict,) - * use_setstate = True - */ - goto __pyx_L3; - } - - /* "(tree fragment)":11 - * use_setstate = True - * else: - * use_setstate = self.name is not None or self.wrapped is not None # <<<<<<<<<<<<<< - * if use_setstate: - * return __pyx_unpickle_reify, (type(self), 0x770cb8f, None), state - */ - /*else*/ { - __pyx_t_2 = (__pyx_v_self->name != Py_None); - __pyx_t_5 = (__pyx_t_2 != 0); - if (!__pyx_t_5) { - } else { - __pyx_t_3 = __pyx_t_5; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_5 = (__pyx_v_self->wrapped != Py_None); - __pyx_t_2 = (__pyx_t_5 != 0); - __pyx_t_3 = __pyx_t_2; - __pyx_L4_bool_binop_done:; - __pyx_v_use_setstate = __pyx_t_3; - } - __pyx_L3:; - - /* "(tree fragment)":12 - * else: - * use_setstate = self.name is not None or self.wrapped is not None - * if use_setstate: # <<<<<<<<<<<<<< - * return __pyx_unpickle_reify, (type(self), 0x770cb8f, None), state - * else: - */ - __pyx_t_3 = (__pyx_v_use_setstate != 0); - if (__pyx_t_3) { - - /* "(tree fragment)":13 - * use_setstate = self.name is not None or self.wrapped is not None - * if use_setstate: - * return __pyx_unpickle_reify, (type(self), 0x770cb8f, None), state # <<<<<<<<<<<<<< - * else: - * return __pyx_unpickle_reify, (type(self), 0x770cb8f, state) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_pyx_unpickle_reify); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - __Pyx_INCREF(__pyx_int_124832655); - __Pyx_GIVEREF(__pyx_int_124832655); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_124832655); - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - PyTuple_SET_ITEM(__pyx_t_1, 2, Py_None); - __pyx_t_6 = PyTuple_New(3); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_1); - __Pyx_INCREF(__pyx_v_state); - __Pyx_GIVEREF(__pyx_v_state); - PyTuple_SET_ITEM(__pyx_t_6, 2, __pyx_v_state); - __pyx_t_4 = 0; - __pyx_t_1 = 0; - __pyx_r = __pyx_t_6; - __pyx_t_6 = 0; - goto __pyx_L0; - - /* "(tree fragment)":12 - * else: - * use_setstate = self.name is not None or self.wrapped is not None - * if use_setstate: # <<<<<<<<<<<<<< - * return __pyx_unpickle_reify, (type(self), 0x770cb8f, None), state - * else: - */ - } - - /* "(tree fragment)":15 - * return __pyx_unpickle_reify, (type(self), 0x770cb8f, None), state - * else: - * return __pyx_unpickle_reify, (type(self), 0x770cb8f, state) # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * __pyx_unpickle_reify__set_state(self, __pyx_state) - */ - /*else*/ { - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_n_s_pyx_unpickle_reify); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 15, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 15, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - __Pyx_INCREF(__pyx_int_124832655); - __Pyx_GIVEREF(__pyx_int_124832655); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_124832655); - __Pyx_INCREF(__pyx_v_state); - __Pyx_GIVEREF(__pyx_v_state); - PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_state); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 15, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_6); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_1); - __pyx_t_6 = 0; - __pyx_t_1 = 0; - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - } - - /* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * cdef tuple state - * cdef object _dict - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("aiohttp._helpers.reify.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_state); - __Pyx_XDECREF(__pyx_v__dict); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":16 - * else: - * return __pyx_unpickle_reify, (type(self), 0x770cb8f, state) - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * __pyx_unpickle_reify__set_state(self, __pyx_state) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_8_helpers_5reify_9__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_8_helpers_5reify_9__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_8_helpers_5reify_8__setstate_cython__(((struct __pyx_obj_7aiohttp_8_helpers_reify *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_8_helpers_5reify_8__setstate_cython__(struct __pyx_obj_7aiohttp_8_helpers_reify *__pyx_v_self, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setstate_cython__", 0); - - /* "(tree fragment)":17 - * return __pyx_unpickle_reify, (type(self), 0x770cb8f, state) - * def __setstate_cython__(self, __pyx_state): - * __pyx_unpickle_reify__set_state(self, __pyx_state) # <<<<<<<<<<<<<< - */ - if (!(likely(PyTuple_CheckExact(__pyx_v___pyx_state))||((__pyx_v___pyx_state) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(1, 17, __pyx_L1_error) - __pyx_t_1 = __pyx_f_7aiohttp_8_helpers___pyx_unpickle_reify__set_state(__pyx_v_self, ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 17, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "(tree fragment)":16 - * else: - * return __pyx_unpickle_reify, (type(self), 0x770cb8f, state) - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * __pyx_unpickle_reify__set_state(self, __pyx_state) - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._helpers.reify.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":1 - * def __pyx_unpickle_reify(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * cdef object __pyx_PickleError - * cdef object __pyx_result - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_8_helpers_1__pyx_unpickle_reify(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyMethodDef __pyx_mdef_7aiohttp_8_helpers_1__pyx_unpickle_reify = {"__pyx_unpickle_reify", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_7aiohttp_8_helpers_1__pyx_unpickle_reify, METH_VARARGS|METH_KEYWORDS, 0}; -static PyObject *__pyx_pw_7aiohttp_8_helpers_1__pyx_unpickle_reify(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v___pyx_type = 0; - long __pyx_v___pyx_checksum; - PyObject *__pyx_v___pyx_state = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__pyx_unpickle_reify (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pyx_type,&__pyx_n_s_pyx_checksum,&__pyx_n_s_pyx_state,0}; - PyObject* values[3] = {0,0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_type)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_checksum)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_reify", 1, 3, 3, 1); __PYX_ERR(1, 1, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_state)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_reify", 1, 3, 3, 2); __PYX_ERR(1, 1, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__pyx_unpickle_reify") < 0)) __PYX_ERR(1, 1, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - } - __pyx_v___pyx_type = values[0]; - __pyx_v___pyx_checksum = __Pyx_PyInt_As_long(values[1]); if (unlikely((__pyx_v___pyx_checksum == (long)-1) && PyErr_Occurred())) __PYX_ERR(1, 1, __pyx_L3_error) - __pyx_v___pyx_state = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_reify", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(1, 1, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._helpers.__pyx_unpickle_reify", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_8_helpers___pyx_unpickle_reify(__pyx_self, __pyx_v___pyx_type, __pyx_v___pyx_checksum, __pyx_v___pyx_state); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_8_helpers___pyx_unpickle_reify(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_v___pyx_PickleError = 0; - PyObject *__pyx_v___pyx_result = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__pyx_unpickle_reify", 0); - - /* "(tree fragment)":4 - * cdef object __pyx_PickleError - * cdef object __pyx_result - * if __pyx_checksum != 0x770cb8f: # <<<<<<<<<<<<<< - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (%s vs 0x770cb8f = (name, wrapped))" % __pyx_checksum) - */ - __pyx_t_1 = ((__pyx_v___pyx_checksum != 0x770cb8f) != 0); - if (__pyx_t_1) { - - /* "(tree fragment)":5 - * cdef object __pyx_result - * if __pyx_checksum != 0x770cb8f: - * from pickle import PickleError as __pyx_PickleError # <<<<<<<<<<<<<< - * raise __pyx_PickleError("Incompatible checksums (%s vs 0x770cb8f = (name, wrapped))" % __pyx_checksum) - * __pyx_result = reify.__new__(__pyx_type) - */ - __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_n_s_PickleError); - __Pyx_GIVEREF(__pyx_n_s_PickleError); - PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_PickleError); - __pyx_t_3 = __Pyx_Import(__pyx_n_s_pickle, __pyx_t_2, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_3, __pyx_n_s_PickleError); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_2); - __pyx_v___pyx_PickleError = __pyx_t_2; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "(tree fragment)":6 - * if __pyx_checksum != 0x770cb8f: - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (%s vs 0x770cb8f = (name, wrapped))" % __pyx_checksum) # <<<<<<<<<<<<<< - * __pyx_result = reify.__new__(__pyx_type) - * if __pyx_state is not None: - */ - __pyx_t_2 = __Pyx_PyInt_From_long(__pyx_v___pyx_checksum); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Incompatible_checksums_s_vs_0x77, __pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_INCREF(__pyx_v___pyx_PickleError); - __pyx_t_2 = __pyx_v___pyx_PickleError; __pyx_t_5 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - __pyx_t_3 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_5, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 6, __pyx_L1_error) - - /* "(tree fragment)":4 - * cdef object __pyx_PickleError - * cdef object __pyx_result - * if __pyx_checksum != 0x770cb8f: # <<<<<<<<<<<<<< - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (%s vs 0x770cb8f = (name, wrapped))" % __pyx_checksum) - */ - } - - /* "(tree fragment)":7 - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (%s vs 0x770cb8f = (name, wrapped))" % __pyx_checksum) - * __pyx_result = reify.__new__(__pyx_type) # <<<<<<<<<<<<<< - * if __pyx_state is not None: - * __pyx_unpickle_reify__set_state( __pyx_result, __pyx_state) - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_ptype_7aiohttp_8_helpers_reify), __pyx_n_s_new); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 7, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - __pyx_t_3 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_4, __pyx_v___pyx_type) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v___pyx_type); - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 7, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v___pyx_result = __pyx_t_3; - __pyx_t_3 = 0; - - /* "(tree fragment)":8 - * raise __pyx_PickleError("Incompatible checksums (%s vs 0x770cb8f = (name, wrapped))" % __pyx_checksum) - * __pyx_result = reify.__new__(__pyx_type) - * if __pyx_state is not None: # <<<<<<<<<<<<<< - * __pyx_unpickle_reify__set_state( __pyx_result, __pyx_state) - * return __pyx_result - */ - __pyx_t_1 = (__pyx_v___pyx_state != Py_None); - __pyx_t_6 = (__pyx_t_1 != 0); - if (__pyx_t_6) { - - /* "(tree fragment)":9 - * __pyx_result = reify.__new__(__pyx_type) - * if __pyx_state is not None: - * __pyx_unpickle_reify__set_state( __pyx_result, __pyx_state) # <<<<<<<<<<<<<< - * return __pyx_result - * cdef __pyx_unpickle_reify__set_state(reify __pyx_result, tuple __pyx_state): - */ - if (!(likely(PyTuple_CheckExact(__pyx_v___pyx_state))||((__pyx_v___pyx_state) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(1, 9, __pyx_L1_error) - __pyx_t_3 = __pyx_f_7aiohttp_8_helpers___pyx_unpickle_reify__set_state(((struct __pyx_obj_7aiohttp_8_helpers_reify *)__pyx_v___pyx_result), ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 9, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "(tree fragment)":8 - * raise __pyx_PickleError("Incompatible checksums (%s vs 0x770cb8f = (name, wrapped))" % __pyx_checksum) - * __pyx_result = reify.__new__(__pyx_type) - * if __pyx_state is not None: # <<<<<<<<<<<<<< - * __pyx_unpickle_reify__set_state( __pyx_result, __pyx_state) - * return __pyx_result - */ - } - - /* "(tree fragment)":10 - * if __pyx_state is not None: - * __pyx_unpickle_reify__set_state( __pyx_result, __pyx_state) - * return __pyx_result # <<<<<<<<<<<<<< - * cdef __pyx_unpickle_reify__set_state(reify __pyx_result, tuple __pyx_state): - * __pyx_result.name = __pyx_state[0]; __pyx_result.wrapped = __pyx_state[1] - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v___pyx_result); - __pyx_r = __pyx_v___pyx_result; - goto __pyx_L0; - - /* "(tree fragment)":1 - * def __pyx_unpickle_reify(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * cdef object __pyx_PickleError - * cdef object __pyx_result - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("aiohttp._helpers.__pyx_unpickle_reify", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v___pyx_PickleError); - __Pyx_XDECREF(__pyx_v___pyx_result); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":11 - * __pyx_unpickle_reify__set_state( __pyx_result, __pyx_state) - * return __pyx_result - * cdef __pyx_unpickle_reify__set_state(reify __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< - * __pyx_result.name = __pyx_state[0]; __pyx_result.wrapped = __pyx_state[1] - * if len(__pyx_state) > 2 and hasattr(__pyx_result, '__dict__'): - */ - -static PyObject *__pyx_f_7aiohttp_8_helpers___pyx_unpickle_reify__set_state(struct __pyx_obj_7aiohttp_8_helpers_reify *__pyx_v___pyx_result, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - Py_ssize_t __pyx_t_3; - int __pyx_t_4; - int __pyx_t_5; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__pyx_unpickle_reify__set_state", 0); - - /* "(tree fragment)":12 - * return __pyx_result - * cdef __pyx_unpickle_reify__set_state(reify __pyx_result, tuple __pyx_state): - * __pyx_result.name = __pyx_state[0]; __pyx_result.wrapped = __pyx_state[1] # <<<<<<<<<<<<<< - * if len(__pyx_state) > 2 and hasattr(__pyx_result, '__dict__'): - * __pyx_result.__dict__.update(__pyx_state[2]) - */ - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 12, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v___pyx_result->name); - __Pyx_DECREF(__pyx_v___pyx_result->name); - __pyx_v___pyx_result->name = __pyx_t_1; - __pyx_t_1 = 0; - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 12, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v___pyx_result->wrapped); - __Pyx_DECREF(__pyx_v___pyx_result->wrapped); - __pyx_v___pyx_result->wrapped = __pyx_t_1; - __pyx_t_1 = 0; - - /* "(tree fragment)":13 - * cdef __pyx_unpickle_reify__set_state(reify __pyx_result, tuple __pyx_state): - * __pyx_result.name = __pyx_state[0]; __pyx_result.wrapped = __pyx_state[1] - * if len(__pyx_state) > 2 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< - * __pyx_result.__dict__.update(__pyx_state[2]) - */ - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - __PYX_ERR(1, 13, __pyx_L1_error) - } - __pyx_t_3 = PyTuple_GET_SIZE(__pyx_v___pyx_state); if (unlikely(__pyx_t_3 == ((Py_ssize_t)-1))) __PYX_ERR(1, 13, __pyx_L1_error) - __pyx_t_4 = ((__pyx_t_3 > 2) != 0); - if (__pyx_t_4) { - } else { - __pyx_t_2 = __pyx_t_4; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_4 = __Pyx_HasAttr(((PyObject *)__pyx_v___pyx_result), __pyx_n_s_dict); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 13, __pyx_L1_error) - __pyx_t_5 = (__pyx_t_4 != 0); - __pyx_t_2 = __pyx_t_5; - __pyx_L4_bool_binop_done:; - if (__pyx_t_2) { - - /* "(tree fragment)":14 - * __pyx_result.name = __pyx_state[0]; __pyx_result.wrapped = __pyx_state[1] - * if len(__pyx_state) > 2 and hasattr(__pyx_result, '__dict__'): - * __pyx_result.__dict__.update(__pyx_state[2]) # <<<<<<<<<<<<<< - */ - __pyx_t_6 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v___pyx_result), __pyx_n_s_dict); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_update); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 14, __pyx_L1_error) - } - __pyx_t_6 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 2, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_8 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_7))) { - __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_7); - if (likely(__pyx_t_8)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); - __Pyx_INCREF(__pyx_t_8); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_7, function); - } - } - __pyx_t_1 = (__pyx_t_8) ? __Pyx_PyObject_Call2Args(__pyx_t_7, __pyx_t_8, __pyx_t_6) : __Pyx_PyObject_CallOneArg(__pyx_t_7, __pyx_t_6); - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "(tree fragment)":13 - * cdef __pyx_unpickle_reify__set_state(reify __pyx_result, tuple __pyx_state): - * __pyx_result.name = __pyx_state[0]; __pyx_result.wrapped = __pyx_state[1] - * if len(__pyx_state) > 2 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< - * __pyx_result.__dict__.update(__pyx_state[2]) - */ - } - - /* "(tree fragment)":11 - * __pyx_unpickle_reify__set_state( __pyx_result, __pyx_state) - * return __pyx_result - * cdef __pyx_unpickle_reify__set_state(reify __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< - * __pyx_result.name = __pyx_state[0]; __pyx_result.wrapped = __pyx_state[1] - * if len(__pyx_state) > 2 and hasattr(__pyx_result, '__dict__'): - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("aiohttp._helpers.__pyx_unpickle_reify__set_state", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_tp_new_7aiohttp_8_helpers_reify(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { - struct __pyx_obj_7aiohttp_8_helpers_reify *p; - PyObject *o; - if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { - o = (*t->tp_alloc)(t, 0); - } else { - o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); - } - if (unlikely(!o)) return 0; - p = ((struct __pyx_obj_7aiohttp_8_helpers_reify *)o); - p->wrapped = Py_None; Py_INCREF(Py_None); - p->name = Py_None; Py_INCREF(Py_None); - return o; -} - -static void __pyx_tp_dealloc_7aiohttp_8_helpers_reify(PyObject *o) { - struct __pyx_obj_7aiohttp_8_helpers_reify *p = (struct __pyx_obj_7aiohttp_8_helpers_reify *)o; - #if CYTHON_USE_TP_FINALIZE - if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { - if (PyObject_CallFinalizerFromDealloc(o)) return; - } - #endif - PyObject_GC_UnTrack(o); - Py_CLEAR(p->wrapped); - Py_CLEAR(p->name); - (*Py_TYPE(o)->tp_free)(o); -} - -static int __pyx_tp_traverse_7aiohttp_8_helpers_reify(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_7aiohttp_8_helpers_reify *p = (struct __pyx_obj_7aiohttp_8_helpers_reify *)o; - if (p->wrapped) { - e = (*v)(p->wrapped, a); if (e) return e; - } - if (p->name) { - e = (*v)(p->name, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear_7aiohttp_8_helpers_reify(PyObject *o) { - PyObject* tmp; - struct __pyx_obj_7aiohttp_8_helpers_reify *p = (struct __pyx_obj_7aiohttp_8_helpers_reify *)o; - tmp = ((PyObject*)p->wrapped); - p->wrapped = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->name); - p->name = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - return 0; -} - -static PyObject *__pyx_tp_descr_get_7aiohttp_8_helpers_reify(PyObject *o, PyObject *i, PyObject *c) { - PyObject *r = 0; - if (!i) i = Py_None; - if (!c) c = Py_None; - r = __pyx_pw_7aiohttp_8_helpers_5reify_3__get__(o, i, c); - return r; -} - -static int __pyx_tp_descr_set_7aiohttp_8_helpers_reify(PyObject *o, PyObject *i, PyObject *v) { - if (v) { - return __pyx_pw_7aiohttp_8_helpers_5reify_5__set__(o, i, v); - } - else { - PyErr_SetString(PyExc_NotImplementedError, "__delete__"); - return -1; - } -} - -static PyObject *__pyx_getprop_7aiohttp_8_helpers_5reify___doc__(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7aiohttp_8_helpers_5reify_7__doc___1__get__(o); -} - -static PyMethodDef __pyx_methods_7aiohttp_8_helpers_reify[] = { - {"__reduce_cython__", (PyCFunction)__pyx_pw_7aiohttp_8_helpers_5reify_7__reduce_cython__, METH_NOARGS, 0}, - {"__setstate_cython__", (PyCFunction)__pyx_pw_7aiohttp_8_helpers_5reify_9__setstate_cython__, METH_O, 0}, - {0, 0, 0, 0} -}; - -static struct PyGetSetDef __pyx_getsets_7aiohttp_8_helpers_reify[] = { - {(char *)"__doc__", __pyx_getprop_7aiohttp_8_helpers_5reify___doc__, 0, (char *)0, 0}, - {0, 0, 0, 0, 0} -}; - -static PyTypeObject __pyx_type_7aiohttp_8_helpers_reify = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._helpers.reify", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_8_helpers_reify), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_8_helpers_reify, /*tp_dealloc*/ - #if PY_VERSION_HEX < 0x030800b4 - 0, /*tp_print*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 - 0, /*tp_vectorcall_offset*/ - #endif - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - "Use as a class method decorator. It operates almost exactly like\n the Python `@property` decorator, but it puts the result of the\n method it decorates into the instance dict after the first call,\n effectively replacing the function it decorates with an instance\n variable. It is, in Python parlance, a data descriptor.\n\n ", /*tp_doc*/ - __pyx_tp_traverse_7aiohttp_8_helpers_reify, /*tp_traverse*/ - __pyx_tp_clear_7aiohttp_8_helpers_reify, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7aiohttp_8_helpers_reify, /*tp_methods*/ - 0, /*tp_members*/ - __pyx_getsets_7aiohttp_8_helpers_reify, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - __pyx_tp_descr_get_7aiohttp_8_helpers_reify, /*tp_descr_get*/ - __pyx_tp_descr_set_7aiohttp_8_helpers_reify, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - __pyx_pw_7aiohttp_8_helpers_5reify_1__init__, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_8_helpers_reify, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif - #if PY_VERSION_HEX >= 0x030800b1 - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif -}; - -static PyMethodDef __pyx_methods[] = { - {0, 0, 0, 0} -}; - -#if PY_MAJOR_VERSION >= 3 -#if CYTHON_PEP489_MULTI_PHASE_INIT -static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ -static int __pyx_pymod_exec__helpers(PyObject* module); /*proto*/ -static PyModuleDef_Slot __pyx_moduledef_slots[] = { - {Py_mod_create, (void*)__pyx_pymod_create}, - {Py_mod_exec, (void*)__pyx_pymod_exec__helpers}, - {0, NULL} -}; -#endif - -static struct PyModuleDef __pyx_moduledef = { - PyModuleDef_HEAD_INIT, - "_helpers", - 0, /* m_doc */ - #if CYTHON_PEP489_MULTI_PHASE_INIT - 0, /* m_size */ - #else - -1, /* m_size */ - #endif - __pyx_methods /* m_methods */, - #if CYTHON_PEP489_MULTI_PHASE_INIT - __pyx_moduledef_slots, /* m_slots */ - #else - NULL, /* m_reload */ - #endif - NULL, /* m_traverse */ - NULL, /* m_clear */ - NULL /* m_free */ -}; -#endif -#ifndef CYTHON_SMALL_CODE -#if defined(__clang__) - #define CYTHON_SMALL_CODE -#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) - #define CYTHON_SMALL_CODE __attribute__((cold)) -#else - #define CYTHON_SMALL_CODE -#endif -#endif - -static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_n_s_AttributeError, __pyx_k_AttributeError, sizeof(__pyx_k_AttributeError), 0, 0, 1, 1}, - {&__pyx_kp_s_Incompatible_checksums_s_vs_0x77, __pyx_k_Incompatible_checksums_s_vs_0x77, sizeof(__pyx_k_Incompatible_checksums_s_vs_0x77), 0, 0, 1, 0}, - {&__pyx_n_s_KeyError, __pyx_k_KeyError, sizeof(__pyx_k_KeyError), 0, 0, 1, 1}, - {&__pyx_n_s_PickleError, __pyx_k_PickleError, sizeof(__pyx_k_PickleError), 0, 0, 1, 1}, - {&__pyx_n_s_aiohttp__helpers, __pyx_k_aiohttp__helpers, sizeof(__pyx_k_aiohttp__helpers), 0, 0, 1, 1}, - {&__pyx_n_s_cache, __pyx_k_cache, sizeof(__pyx_k_cache), 0, 0, 1, 1}, - {&__pyx_n_s_cline_in_traceback, __pyx_k_cline_in_traceback, sizeof(__pyx_k_cline_in_traceback), 0, 0, 1, 1}, - {&__pyx_n_s_dict, __pyx_k_dict, sizeof(__pyx_k_dict), 0, 0, 1, 1}, - {&__pyx_n_s_doc, __pyx_k_doc, sizeof(__pyx_k_doc), 0, 0, 1, 1}, - {&__pyx_n_s_getstate, __pyx_k_getstate, sizeof(__pyx_k_getstate), 0, 0, 1, 1}, - {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, - {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, - {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, - {&__pyx_n_s_new, __pyx_k_new, sizeof(__pyx_k_new), 0, 0, 1, 1}, - {&__pyx_n_s_pickle, __pyx_k_pickle, sizeof(__pyx_k_pickle), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_PickleError, __pyx_k_pyx_PickleError, sizeof(__pyx_k_pyx_PickleError), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_checksum, __pyx_k_pyx_checksum, sizeof(__pyx_k_pyx_checksum), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_result, __pyx_k_pyx_result, sizeof(__pyx_k_pyx_result), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_state, __pyx_k_pyx_state, sizeof(__pyx_k_pyx_state), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_type, __pyx_k_pyx_type, sizeof(__pyx_k_pyx_type), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_unpickle_reify, __pyx_k_pyx_unpickle_reify, sizeof(__pyx_k_pyx_unpickle_reify), 0, 0, 1, 1}, - {&__pyx_n_s_reduce, __pyx_k_reduce, sizeof(__pyx_k_reduce), 0, 0, 1, 1}, - {&__pyx_n_s_reduce_cython, __pyx_k_reduce_cython, sizeof(__pyx_k_reduce_cython), 0, 0, 1, 1}, - {&__pyx_n_s_reduce_ex, __pyx_k_reduce_ex, sizeof(__pyx_k_reduce_ex), 0, 0, 1, 1}, - {&__pyx_kp_u_reified_property_is_read_only, __pyx_k_reified_property_is_read_only, sizeof(__pyx_k_reified_property_is_read_only), 0, 1, 0, 0}, - {&__pyx_n_s_reify, __pyx_k_reify, sizeof(__pyx_k_reify), 0, 0, 1, 1}, - {&__pyx_n_s_setstate, __pyx_k_setstate, sizeof(__pyx_k_setstate), 0, 0, 1, 1}, - {&__pyx_n_s_setstate_cython, __pyx_k_setstate_cython, sizeof(__pyx_k_setstate_cython), 0, 0, 1, 1}, - {&__pyx_kp_s_stringsource, __pyx_k_stringsource, sizeof(__pyx_k_stringsource), 0, 0, 1, 0}, - {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, - {&__pyx_n_s_update, __pyx_k_update, sizeof(__pyx_k_update), 0, 0, 1, 1}, - {&__pyx_n_s_wrapped, __pyx_k_wrapped, sizeof(__pyx_k_wrapped), 0, 0, 1, 1}, - {0, 0, 0, 0, 0, 0, 0} -}; -static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_KeyError = __Pyx_GetBuiltinName(__pyx_n_s_KeyError); if (!__pyx_builtin_KeyError) __PYX_ERR(0, 25, __pyx_L1_error) - __pyx_builtin_AttributeError = __Pyx_GetBuiltinName(__pyx_n_s_AttributeError); if (!__pyx_builtin_AttributeError) __PYX_ERR(0, 29, __pyx_L1_error) - return 0; - __pyx_L1_error:; - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); - - /* "aiohttp/_helpers.pyx":35 - * - * def __set__(self, inst, value): - * raise AttributeError("reified property is read-only") # <<<<<<<<<<<<<< - */ - __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_u_reified_property_is_read_only); if (unlikely(!__pyx_tuple_)) __PYX_ERR(0, 35, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple_); - __Pyx_GIVEREF(__pyx_tuple_); - - /* "(tree fragment)":1 - * def __pyx_unpickle_reify(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * cdef object __pyx_PickleError - * cdef object __pyx_result - */ - __pyx_tuple__2 = PyTuple_Pack(5, __pyx_n_s_pyx_type, __pyx_n_s_pyx_checksum, __pyx_n_s_pyx_state, __pyx_n_s_pyx_PickleError, __pyx_n_s_pyx_result); if (unlikely(!__pyx_tuple__2)) __PYX_ERR(1, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__2); - __Pyx_GIVEREF(__pyx_tuple__2); - __pyx_codeobj__3 = (PyObject*)__Pyx_PyCode_New(3, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__2, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_stringsource, __pyx_n_s_pyx_unpickle_reify, 1, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__3)) __PYX_ERR(1, 1, __pyx_L1_error) - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_RefNannyFinishContext(); - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) { - if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error); - __pyx_int_124832655 = PyInt_FromLong(124832655L); if (unlikely(!__pyx_int_124832655)) __PYX_ERR(0, 1, __pyx_L1_error) - return 0; - __pyx_L1_error:; - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(void); /*proto*/ - -static int __Pyx_modinit_global_init_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0); - /*--- Global init code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_variable_export_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0); - /*--- Variable export code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_function_export_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0); - /*--- Function export code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_type_init_code(void) { - __Pyx_RefNannyDeclarations - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); - /*--- Type init code ---*/ - if (PyType_Ready(&__pyx_type_7aiohttp_8_helpers_reify) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type_7aiohttp_8_helpers_reify.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_7aiohttp_8_helpers_reify.tp_dictoffset && __pyx_type_7aiohttp_8_helpers_reify.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type_7aiohttp_8_helpers_reify.tp_getattro = __Pyx_PyObject_GenericGetAttr; - } - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_reify, (PyObject *)&__pyx_type_7aiohttp_8_helpers_reify) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - if (__Pyx_setup_reduce((PyObject*)&__pyx_type_7aiohttp_8_helpers_reify) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_ptype_7aiohttp_8_helpers_reify = &__pyx_type_7aiohttp_8_helpers_reify; - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_RefNannyFinishContext(); - return -1; -} - -static int __Pyx_modinit_type_import_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); - /*--- Type import code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_variable_import_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0); - /*--- Variable import code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_function_import_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0); - /*--- Function import code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - - -#ifndef CYTHON_NO_PYINIT_EXPORT -#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC -#elif PY_MAJOR_VERSION < 3 -#ifdef __cplusplus -#define __Pyx_PyMODINIT_FUNC extern "C" void -#else -#define __Pyx_PyMODINIT_FUNC void -#endif -#else -#ifdef __cplusplus -#define __Pyx_PyMODINIT_FUNC extern "C" PyObject * -#else -#define __Pyx_PyMODINIT_FUNC PyObject * -#endif -#endif - - -#if PY_MAJOR_VERSION < 3 -__Pyx_PyMODINIT_FUNC init_helpers(void) CYTHON_SMALL_CODE; /*proto*/ -__Pyx_PyMODINIT_FUNC init_helpers(void) -#else -__Pyx_PyMODINIT_FUNC PyInit__helpers(void) CYTHON_SMALL_CODE; /*proto*/ -__Pyx_PyMODINIT_FUNC PyInit__helpers(void) -#if CYTHON_PEP489_MULTI_PHASE_INIT -{ - return PyModuleDef_Init(&__pyx_moduledef); -} -static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { - #if PY_VERSION_HEX >= 0x030700A1 - static PY_INT64_T main_interpreter_id = -1; - PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); - if (main_interpreter_id == -1) { - main_interpreter_id = current_id; - return (unlikely(current_id == -1)) ? -1 : 0; - } else if (unlikely(main_interpreter_id != current_id)) - #else - static PyInterpreterState *main_interpreter = NULL; - PyInterpreterState *current_interpreter = PyThreadState_Get()->interp; - if (!main_interpreter) { - main_interpreter = current_interpreter; - } else if (unlikely(main_interpreter != current_interpreter)) - #endif - { - PyErr_SetString( - PyExc_ImportError, - "Interpreter change detected - this module can only be loaded into one interpreter per process."); - return -1; - } - return 0; -} -static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) { - PyObject *value = PyObject_GetAttrString(spec, from_name); - int result = 0; - if (likely(value)) { - if (allow_none || value != Py_None) { - result = PyDict_SetItemString(moddict, to_name, value); - } - Py_DECREF(value); - } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Clear(); - } else { - result = -1; - } - return result; -} -static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, CYTHON_UNUSED PyModuleDef *def) { - PyObject *module = NULL, *moddict, *modname; - if (__Pyx_check_single_interpreter()) - return NULL; - if (__pyx_m) - return __Pyx_NewRef(__pyx_m); - modname = PyObject_GetAttrString(spec, "name"); - if (unlikely(!modname)) goto bad; - module = PyModule_NewObject(modname); - Py_DECREF(modname); - if (unlikely(!module)) goto bad; - moddict = PyModule_GetDict(module); - if (unlikely(!moddict)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; - return module; -bad: - Py_XDECREF(module); - return NULL; -} - - -static CYTHON_SMALL_CODE int __pyx_pymod_exec__helpers(PyObject *__pyx_pyinit_module) -#endif -#endif -{ - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannyDeclarations - #if CYTHON_PEP489_MULTI_PHASE_INIT - if (__pyx_m) { - if (__pyx_m == __pyx_pyinit_module) return 0; - PyErr_SetString(PyExc_RuntimeError, "Module '_helpers' has already been imported. Re-initialisation is not supported."); - return -1; - } - #elif PY_MAJOR_VERSION >= 3 - if (__pyx_m) return __Pyx_NewRef(__pyx_m); - #endif - #if CYTHON_REFNANNY -__Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); -if (!__Pyx_RefNanny) { - PyErr_Clear(); - __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); - if (!__Pyx_RefNanny) - Py_FatalError("failed to import 'refnanny' module"); -} -#endif - __Pyx_RefNannySetupContext("__Pyx_PyMODINIT_FUNC PyInit__helpers(void)", 0); - if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #ifdef __Pxy_PyFrame_Initialize_Offsets - __Pxy_PyFrame_Initialize_Offsets(); - #endif - __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) - #ifdef __Pyx_CyFunction_USED - if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_FusedFunction_USED - if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_Coroutine_USED - if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_Generator_USED - if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_AsyncGen_USED - if (__pyx_AsyncGen_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_StopAsyncIteration_USED - if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - /*--- Library function declarations ---*/ - /*--- Threads initialization code ---*/ - #if defined(WITH_THREAD) && PY_VERSION_HEX < 0x030700F0 && defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS - PyEval_InitThreads(); - #endif - /*--- Module creation code ---*/ - #if CYTHON_PEP489_MULTI_PHASE_INIT - __pyx_m = __pyx_pyinit_module; - Py_INCREF(__pyx_m); - #else - #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4("_helpers", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); - #else - __pyx_m = PyModule_Create(&__pyx_moduledef); - #endif - if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_d); - __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_b); - __pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_cython_runtime); - if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error); - /*--- Initialize various global constants etc. ---*/ - if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) - if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - if (__pyx_module_is_main_aiohttp___helpers) { - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_name, __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - } - #if PY_MAJOR_VERSION >= 3 - { - PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) - if (!PyDict_GetItemString(modules, "aiohttp._helpers")) { - if (unlikely(PyDict_SetItemString(modules, "aiohttp._helpers", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error) - } - } - #endif - /*--- Builtin init code ---*/ - if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - /*--- Constants init code ---*/ - if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - /*--- Global type/function init code ---*/ - (void)__Pyx_modinit_global_init_code(); - (void)__Pyx_modinit_variable_export_code(); - (void)__Pyx_modinit_function_export_code(); - if (unlikely(__Pyx_modinit_type_init_code() < 0)) __PYX_ERR(0, 1, __pyx_L1_error) - (void)__Pyx_modinit_type_import_code(); - (void)__Pyx_modinit_variable_import_code(); - (void)__Pyx_modinit_function_import_code(); - /*--- Execution code ---*/ - #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) - if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - - /* "(tree fragment)":1 - * def __pyx_unpickle_reify(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * cdef object __pyx_PickleError - * cdef object __pyx_result - */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7aiohttp_8_helpers_1__pyx_unpickle_reify, NULL, __pyx_n_s_aiohttp__helpers); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_pyx_unpickle_reify, __pyx_t_1) < 0) __PYX_ERR(1, 1, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_helpers.pyx":1 - * cdef class reify: # <<<<<<<<<<<<<< - * """Use as a class method decorator. It operates almost exactly like - * the Python `@property` decorator, but it puts the result of the - */ - __pyx_t_1 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /*--- Wrapped vars code ---*/ - - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - if (__pyx_m) { - if (__pyx_d) { - __Pyx_AddTraceback("init aiohttp._helpers", __pyx_clineno, __pyx_lineno, __pyx_filename); - } - Py_CLEAR(__pyx_m); - } else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_ImportError, "init aiohttp._helpers"); - } - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - #if CYTHON_PEP489_MULTI_PHASE_INIT - return (__pyx_m != NULL) ? 0 : -1; - #elif PY_MAJOR_VERSION >= 3 - return __pyx_m; - #else - return; - #endif -} - -/* --- Runtime support code --- */ -/* Refnanny */ -#if CYTHON_REFNANNY -static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { - PyObject *m = NULL, *p = NULL; - void *r = NULL; - m = PyImport_ImportModule(modname); - if (!m) goto end; - p = PyObject_GetAttrString(m, "RefNannyAPI"); - if (!p) goto end; - r = PyLong_AsVoidPtr(p); -end: - Py_XDECREF(p); - Py_XDECREF(m); - return (__Pyx_RefNannyAPIStruct *)r; -} -#endif - -/* PyObjectGetAttrStr */ -#if CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { - PyTypeObject* tp = Py_TYPE(obj); - if (likely(tp->tp_getattro)) - return tp->tp_getattro(obj, attr_name); -#if PY_MAJOR_VERSION < 3 - if (likely(tp->tp_getattr)) - return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); -#endif - return PyObject_GetAttr(obj, attr_name); -} -#endif - -/* GetBuiltinName */ -static PyObject *__Pyx_GetBuiltinName(PyObject *name) { - PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); - if (unlikely(!result)) { - PyErr_Format(PyExc_NameError, -#if PY_MAJOR_VERSION >= 3 - "name '%U' is not defined", name); -#else - "name '%.200s' is not defined", PyString_AS_STRING(name)); -#endif - } - return result; -} - -/* RaiseDoubleKeywords */ -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, - PyObject* kw_name) -{ - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION >= 3 - "%s() got multiple values for keyword argument '%U'", func_name, kw_name); - #else - "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AsString(kw_name)); - #endif -} - -/* ParseKeywords */ -static int __Pyx_ParseOptionalKeywords( - PyObject *kwds, - PyObject **argnames[], - PyObject *kwds2, - PyObject *values[], - Py_ssize_t num_pos_args, - const char* function_name) -{ - PyObject *key = 0, *value = 0; - Py_ssize_t pos = 0; - PyObject*** name; - PyObject*** first_kw_arg = argnames + num_pos_args; - while (PyDict_Next(kwds, &pos, &key, &value)) { - name = first_kw_arg; - while (*name && (**name != key)) name++; - if (*name) { - values[name-argnames] = value; - continue; - } - name = first_kw_arg; - #if PY_MAJOR_VERSION < 3 - if (likely(PyString_Check(key))) { - while (*name) { - if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) - && _PyString_Eq(**name, key)) { - values[name-argnames] = value; - break; - } - name++; - } - if (*name) continue; - else { - PyObject*** argname = argnames; - while (argname != first_kw_arg) { - if ((**argname == key) || ( - (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) - && _PyString_Eq(**argname, key))) { - goto arg_passed_twice; - } - argname++; - } - } - } else - #endif - if (likely(PyUnicode_Check(key))) { - while (*name) { - int cmp = (**name == key) ? 0 : - #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 - (__Pyx_PyUnicode_GET_LENGTH(**name) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : - #endif - PyUnicode_Compare(**name, key); - if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; - if (cmp == 0) { - values[name-argnames] = value; - break; - } - name++; - } - if (*name) continue; - else { - PyObject*** argname = argnames; - while (argname != first_kw_arg) { - int cmp = (**argname == key) ? 0 : - #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 - (__Pyx_PyUnicode_GET_LENGTH(**argname) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : - #endif - PyUnicode_Compare(**argname, key); - if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; - if (cmp == 0) goto arg_passed_twice; - argname++; - } - } - } else - goto invalid_keyword_type; - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; - } - } - return 0; -arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, key); - goto bad; -invalid_keyword_type: - PyErr_Format(PyExc_TypeError, - "%.200s() keywords must be strings", function_name); - goto bad; -invalid_keyword: - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION < 3 - "%.200s() got an unexpected keyword argument '%.200s'", - function_name, PyString_AsString(key)); - #else - "%s() got an unexpected keyword argument '%U'", - function_name, key); - #endif -bad: - return -1; -} - -/* RaiseArgTupleInvalid */ -static void __Pyx_RaiseArgtupleInvalid( - const char* func_name, - int exact, - Py_ssize_t num_min, - Py_ssize_t num_max, - Py_ssize_t num_found) -{ - Py_ssize_t num_expected; - const char *more_or_less; - if (num_found < num_min) { - num_expected = num_min; - more_or_less = "at least"; - } else { - num_expected = num_max; - more_or_less = "at most"; - } - if (exact) { - more_or_less = "exactly"; - } - PyErr_Format(PyExc_TypeError, - "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", - func_name, more_or_less, num_expected, - (num_expected == 1) ? "" : "s", num_found); -} - -/* GetItemInt */ -static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { - PyObject *r; - if (!j) return NULL; - r = PyObject_GetItem(o, j); - Py_DECREF(j); - return r; -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, - CYTHON_NCP_UNUSED int wraparound, - CYTHON_NCP_UNUSED int boundscheck) { -#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - Py_ssize_t wrapped_i = i; - if (wraparound & unlikely(i < 0)) { - wrapped_i += PyList_GET_SIZE(o); - } - if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyList_GET_SIZE(o)))) { - PyObject *r = PyList_GET_ITEM(o, wrapped_i); - Py_INCREF(r); - return r; - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -#else - return PySequence_GetItem(o, i); -#endif -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, - CYTHON_NCP_UNUSED int wraparound, - CYTHON_NCP_UNUSED int boundscheck) { -#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - Py_ssize_t wrapped_i = i; - if (wraparound & unlikely(i < 0)) { - wrapped_i += PyTuple_GET_SIZE(o); - } - if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, wrapped_i); - Py_INCREF(r); - return r; - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -#else - return PySequence_GetItem(o, i); -#endif -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, - CYTHON_NCP_UNUSED int wraparound, - CYTHON_NCP_UNUSED int boundscheck) { -#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS && CYTHON_USE_TYPE_SLOTS - if (is_list || PyList_CheckExact(o)) { - Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); - if ((!boundscheck) || (likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o))))) { - PyObject *r = PyList_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } - else if (PyTuple_CheckExact(o)) { - Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); - if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } else { - PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; - if (likely(m && m->sq_item)) { - if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { - Py_ssize_t l = m->sq_length(o); - if (likely(l >= 0)) { - i += l; - } else { - if (!PyErr_ExceptionMatches(PyExc_OverflowError)) - return NULL; - PyErr_Clear(); - } - } - return m->sq_item(o, i); - } - } -#else - if (is_list || PySequence_Check(o)) { - return PySequence_GetItem(o, i); - } -#endif - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -} - -/* ObjectGetItem */ -#if CYTHON_USE_TYPE_SLOTS -static PyObject *__Pyx_PyObject_GetIndex(PyObject *obj, PyObject* index) { - PyObject *runerr; - Py_ssize_t key_value; - PySequenceMethods *m = Py_TYPE(obj)->tp_as_sequence; - if (unlikely(!(m && m->sq_item))) { - PyErr_Format(PyExc_TypeError, "'%.200s' object is not subscriptable", Py_TYPE(obj)->tp_name); - return NULL; - } - key_value = __Pyx_PyIndex_AsSsize_t(index); - if (likely(key_value != -1 || !(runerr = PyErr_Occurred()))) { - return __Pyx_GetItemInt_Fast(obj, key_value, 0, 1, 1); - } - if (PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) { - PyErr_Clear(); - PyErr_Format(PyExc_IndexError, "cannot fit '%.200s' into an index-sized integer", Py_TYPE(index)->tp_name); - } - return NULL; -} -static PyObject *__Pyx_PyObject_GetItem(PyObject *obj, PyObject* key) { - PyMappingMethods *m = Py_TYPE(obj)->tp_as_mapping; - if (likely(m && m->mp_subscript)) { - return m->mp_subscript(obj, key); - } - return __Pyx_PyObject_GetIndex(obj, key); -} -#endif - -/* GetTopmostException */ -#if CYTHON_USE_EXC_INFO_STACK -static _PyErr_StackItem * -__Pyx_PyErr_GetTopmostException(PyThreadState *tstate) -{ - _PyErr_StackItem *exc_info = tstate->exc_info; - while ((exc_info->exc_type == NULL || exc_info->exc_type == Py_None) && - exc_info->previous_item != NULL) - { - exc_info = exc_info->previous_item; - } - return exc_info; -} -#endif - -/* SaveResetException */ -#if CYTHON_FAST_THREAD_STATE -static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { - #if CYTHON_USE_EXC_INFO_STACK - _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); - *type = exc_info->exc_type; - *value = exc_info->exc_value; - *tb = exc_info->exc_traceback; - #else - *type = tstate->exc_type; - *value = tstate->exc_value; - *tb = tstate->exc_traceback; - #endif - Py_XINCREF(*type); - Py_XINCREF(*value); - Py_XINCREF(*tb); -} -static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - #if CYTHON_USE_EXC_INFO_STACK - _PyErr_StackItem *exc_info = tstate->exc_info; - tmp_type = exc_info->exc_type; - tmp_value = exc_info->exc_value; - tmp_tb = exc_info->exc_traceback; - exc_info->exc_type = type; - exc_info->exc_value = value; - exc_info->exc_traceback = tb; - #else - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - tstate->exc_type = type; - tstate->exc_value = value; - tstate->exc_traceback = tb; - #endif - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -} -#endif - -/* PyErrExceptionMatches */ -#if CYTHON_FAST_THREAD_STATE -static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { - Py_ssize_t i, n; - n = PyTuple_GET_SIZE(tuple); -#if PY_MAJOR_VERSION >= 3 - for (i=0; icurexc_type; - if (exc_type == err) return 1; - if (unlikely(!exc_type)) return 0; - if (unlikely(PyTuple_Check(err))) - return __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); - return __Pyx_PyErr_GivenExceptionMatches(exc_type, err); -} -#endif - -/* GetException */ -#if CYTHON_FAST_THREAD_STATE -static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) -#else -static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) -#endif -{ - PyObject *local_type, *local_value, *local_tb; -#if CYTHON_FAST_THREAD_STATE - PyObject *tmp_type, *tmp_value, *tmp_tb; - local_type = tstate->curexc_type; - local_value = tstate->curexc_value; - local_tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; -#else - PyErr_Fetch(&local_type, &local_value, &local_tb); -#endif - PyErr_NormalizeException(&local_type, &local_value, &local_tb); -#if CYTHON_FAST_THREAD_STATE - if (unlikely(tstate->curexc_type)) -#else - if (unlikely(PyErr_Occurred())) -#endif - goto bad; - #if PY_MAJOR_VERSION >= 3 - if (local_tb) { - if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) - goto bad; - } - #endif - Py_XINCREF(local_tb); - Py_XINCREF(local_type); - Py_XINCREF(local_value); - *type = local_type; - *value = local_value; - *tb = local_tb; -#if CYTHON_FAST_THREAD_STATE - #if CYTHON_USE_EXC_INFO_STACK - { - _PyErr_StackItem *exc_info = tstate->exc_info; - tmp_type = exc_info->exc_type; - tmp_value = exc_info->exc_value; - tmp_tb = exc_info->exc_traceback; - exc_info->exc_type = local_type; - exc_info->exc_value = local_value; - exc_info->exc_traceback = local_tb; - } - #else - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - tstate->exc_type = local_type; - tstate->exc_value = local_value; - tstate->exc_traceback = local_tb; - #endif - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -#else - PyErr_SetExcInfo(local_type, local_value, local_tb); -#endif - return 0; -bad: - *type = 0; - *value = 0; - *tb = 0; - Py_XDECREF(local_type); - Py_XDECREF(local_value); - Py_XDECREF(local_tb); - return -1; -} - -/* PyCFunctionFastCall */ -#if CYTHON_FAST_PYCCALL -static CYTHON_INLINE PyObject * __Pyx_PyCFunction_FastCall(PyObject *func_obj, PyObject **args, Py_ssize_t nargs) { - PyCFunctionObject *func = (PyCFunctionObject*)func_obj; - PyCFunction meth = PyCFunction_GET_FUNCTION(func); - PyObject *self = PyCFunction_GET_SELF(func); - int flags = PyCFunction_GET_FLAGS(func); - assert(PyCFunction_Check(func)); - assert(METH_FASTCALL == (flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))); - assert(nargs >= 0); - assert(nargs == 0 || args != NULL); - /* _PyCFunction_FastCallDict() must not be called with an exception set, - because it may clear it (directly or indirectly) and so the - caller loses its exception */ - assert(!PyErr_Occurred()); - if ((PY_VERSION_HEX < 0x030700A0) || unlikely(flags & METH_KEYWORDS)) { - return (*((__Pyx_PyCFunctionFastWithKeywords)(void*)meth)) (self, args, nargs, NULL); - } else { - return (*((__Pyx_PyCFunctionFast)(void*)meth)) (self, args, nargs); - } -} -#endif - -/* PyFunctionFastCall */ -#if CYTHON_FAST_PYCALL -static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na, - PyObject *globals) { - PyFrameObject *f; - PyThreadState *tstate = __Pyx_PyThreadState_Current; - PyObject **fastlocals; - Py_ssize_t i; - PyObject *result; - assert(globals != NULL); - /* XXX Perhaps we should create a specialized - PyFrame_New() that doesn't take locals, but does - take builtins without sanity checking them. - */ - assert(tstate != NULL); - f = PyFrame_New(tstate, co, globals, NULL); - if (f == NULL) { - return NULL; - } - fastlocals = __Pyx_PyFrame_GetLocalsplus(f); - for (i = 0; i < na; i++) { - Py_INCREF(*args); - fastlocals[i] = *args++; - } - result = PyEval_EvalFrameEx(f,0); - ++tstate->recursion_depth; - Py_DECREF(f); - --tstate->recursion_depth; - return result; -} -#if 1 || PY_VERSION_HEX < 0x030600B1 -static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) { - PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); - PyObject *globals = PyFunction_GET_GLOBALS(func); - PyObject *argdefs = PyFunction_GET_DEFAULTS(func); - PyObject *closure; -#if PY_MAJOR_VERSION >= 3 - PyObject *kwdefs; -#endif - PyObject *kwtuple, **k; - PyObject **d; - Py_ssize_t nd; - Py_ssize_t nk; - PyObject *result; - assert(kwargs == NULL || PyDict_Check(kwargs)); - nk = kwargs ? PyDict_Size(kwargs) : 0; - if (Py_EnterRecursiveCall((char*)" while calling a Python object")) { - return NULL; - } - if ( -#if PY_MAJOR_VERSION >= 3 - co->co_kwonlyargcount == 0 && -#endif - likely(kwargs == NULL || nk == 0) && - co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { - if (argdefs == NULL && co->co_argcount == nargs) { - result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals); - goto done; - } - else if (nargs == 0 && argdefs != NULL - && co->co_argcount == Py_SIZE(argdefs)) { - /* function called with no arguments, but all parameters have - a default value: use default values as arguments .*/ - args = &PyTuple_GET_ITEM(argdefs, 0); - result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals); - goto done; - } - } - if (kwargs != NULL) { - Py_ssize_t pos, i; - kwtuple = PyTuple_New(2 * nk); - if (kwtuple == NULL) { - result = NULL; - goto done; - } - k = &PyTuple_GET_ITEM(kwtuple, 0); - pos = i = 0; - while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) { - Py_INCREF(k[i]); - Py_INCREF(k[i+1]); - i += 2; - } - nk = i / 2; - } - else { - kwtuple = NULL; - k = NULL; - } - closure = PyFunction_GET_CLOSURE(func); -#if PY_MAJOR_VERSION >= 3 - kwdefs = PyFunction_GET_KW_DEFAULTS(func); -#endif - if (argdefs != NULL) { - d = &PyTuple_GET_ITEM(argdefs, 0); - nd = Py_SIZE(argdefs); - } - else { - d = NULL; - nd = 0; - } -#if PY_MAJOR_VERSION >= 3 - result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL, - args, (int)nargs, - k, (int)nk, - d, (int)nd, kwdefs, closure); -#else - result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL, - args, (int)nargs, - k, (int)nk, - d, (int)nd, closure); -#endif - Py_XDECREF(kwtuple); -done: - Py_LeaveRecursiveCall(); - return result; -} -#endif -#endif - -/* PyObjectCall */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { - PyObject *result; - ternaryfunc call = Py_TYPE(func)->tp_call; - if (unlikely(!call)) - return PyObject_Call(func, arg, kw); - if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) - return NULL; - result = (*call)(func, arg, kw); - Py_LeaveRecursiveCall(); - if (unlikely(!result) && unlikely(!PyErr_Occurred())) { - PyErr_SetString( - PyExc_SystemError, - "NULL result without error in PyObject_Call"); - } - return result; -} -#endif - -/* PyObjectCall2Args */ -static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2) { - PyObject *args, *result = NULL; - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(function)) { - PyObject *args[2] = {arg1, arg2}; - return __Pyx_PyFunction_FastCall(function, args, 2); - } - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(function)) { - PyObject *args[2] = {arg1, arg2}; - return __Pyx_PyCFunction_FastCall(function, args, 2); - } - #endif - args = PyTuple_New(2); - if (unlikely(!args)) goto done; - Py_INCREF(arg1); - PyTuple_SET_ITEM(args, 0, arg1); - Py_INCREF(arg2); - PyTuple_SET_ITEM(args, 1, arg2); - Py_INCREF(function); - result = __Pyx_PyObject_Call(function, args, NULL); - Py_DECREF(args); - Py_DECREF(function); -done: - return result; -} - -/* PyObjectCallMethO */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { - PyObject *self, *result; - PyCFunction cfunc; - cfunc = PyCFunction_GET_FUNCTION(func); - self = PyCFunction_GET_SELF(func); - if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) - return NULL; - result = cfunc(self, arg); - Py_LeaveRecursiveCall(); - if (unlikely(!result) && unlikely(!PyErr_Occurred())) { - PyErr_SetString( - PyExc_SystemError, - "NULL result without error in PyObject_Call"); - } - return result; -} -#endif - -/* PyObjectCallOneArg */ -#if CYTHON_COMPILING_IN_CPYTHON -static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { - PyObject *result; - PyObject *args = PyTuple_New(1); - if (unlikely(!args)) return NULL; - Py_INCREF(arg); - PyTuple_SET_ITEM(args, 0, arg); - result = __Pyx_PyObject_Call(func, args, NULL); - Py_DECREF(args); - return result; -} -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { -#if CYTHON_FAST_PYCALL - if (PyFunction_Check(func)) { - return __Pyx_PyFunction_FastCall(func, &arg, 1); - } -#endif - if (likely(PyCFunction_Check(func))) { - if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { - return __Pyx_PyObject_CallMethO(func, arg); -#if CYTHON_FAST_PYCCALL - } else if (__Pyx_PyFastCFunction_Check(func)) { - return __Pyx_PyCFunction_FastCall(func, &arg, 1); -#endif - } - } - return __Pyx__PyObject_CallOneArg(func, arg); -} -#else -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { - PyObject *result; - PyObject *args = PyTuple_Pack(1, arg); - if (unlikely(!args)) return NULL; - result = __Pyx_PyObject_Call(func, args, NULL); - Py_DECREF(args); - return result; -} -#endif - -/* PyErrFetchRestore */ -#if CYTHON_FAST_THREAD_STATE -static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - tmp_type = tstate->curexc_type; - tmp_value = tstate->curexc_value; - tmp_tb = tstate->curexc_traceback; - tstate->curexc_type = type; - tstate->curexc_value = value; - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -} -static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { - *type = tstate->curexc_type; - *value = tstate->curexc_value; - *tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; -} -#endif - -/* RaiseException */ -#if PY_MAJOR_VERSION < 3 -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, - CYTHON_UNUSED PyObject *cause) { - __Pyx_PyThreadState_declare - Py_XINCREF(type); - if (!value || value == Py_None) - value = NULL; - else - Py_INCREF(value); - if (!tb || tb == Py_None) - tb = NULL; - else { - Py_INCREF(tb); - if (!PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - } - if (PyType_Check(type)) { -#if CYTHON_COMPILING_IN_PYPY - if (!value) { - Py_INCREF(Py_None); - value = Py_None; - } -#endif - PyErr_NormalizeException(&type, &value, &tb); - } else { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto raise_error; - } - value = type; - type = (PyObject*) Py_TYPE(type); - Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; - } - } - __Pyx_PyThreadState_assign - __Pyx_ErrRestore(type, value, tb); - return; -raise_error: - Py_XDECREF(value); - Py_XDECREF(type); - Py_XDECREF(tb); - return; -} -#else -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - PyObject* owned_instance = NULL; - if (tb == Py_None) { - tb = 0; - } else if (tb && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto bad; - } - if (value == Py_None) - value = 0; - if (PyExceptionInstance_Check(type)) { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto bad; - } - value = type; - type = (PyObject*) Py_TYPE(value); - } else if (PyExceptionClass_Check(type)) { - PyObject *instance_class = NULL; - if (value && PyExceptionInstance_Check(value)) { - instance_class = (PyObject*) Py_TYPE(value); - if (instance_class != type) { - int is_subclass = PyObject_IsSubclass(instance_class, type); - if (!is_subclass) { - instance_class = NULL; - } else if (unlikely(is_subclass == -1)) { - goto bad; - } else { - type = instance_class; - } - } - } - if (!instance_class) { - PyObject *args; - if (!value) - args = PyTuple_New(0); - else if (PyTuple_Check(value)) { - Py_INCREF(value); - args = value; - } else - args = PyTuple_Pack(1, value); - if (!args) - goto bad; - owned_instance = PyObject_Call(type, args, NULL); - Py_DECREF(args); - if (!owned_instance) - goto bad; - value = owned_instance; - if (!PyExceptionInstance_Check(value)) { - PyErr_Format(PyExc_TypeError, - "calling %R should have returned an instance of " - "BaseException, not %R", - type, Py_TYPE(value)); - goto bad; - } - } - } else { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto bad; - } - if (cause) { - PyObject *fixed_cause; - if (cause == Py_None) { - fixed_cause = NULL; - } else if (PyExceptionClass_Check(cause)) { - fixed_cause = PyObject_CallObject(cause, NULL); - if (fixed_cause == NULL) - goto bad; - } else if (PyExceptionInstance_Check(cause)) { - fixed_cause = cause; - Py_INCREF(fixed_cause); - } else { - PyErr_SetString(PyExc_TypeError, - "exception causes must derive from " - "BaseException"); - goto bad; - } - PyException_SetCause(value, fixed_cause); - } - PyErr_SetObject(type, value); - if (tb) { -#if CYTHON_COMPILING_IN_PYPY - PyObject *tmp_type, *tmp_value, *tmp_tb; - PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); - Py_INCREF(tb); - PyErr_Restore(tmp_type, tmp_value, tb); - Py_XDECREF(tmp_tb); -#else - PyThreadState *tstate = __Pyx_PyThreadState_Current; - PyObject* tmp_tb = tstate->curexc_traceback; - if (tb != tmp_tb) { - Py_INCREF(tb); - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_tb); - } -#endif - } -bad: - Py_XDECREF(owned_instance); - return; -} -#endif - -/* GetAttr */ -static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { -#if CYTHON_USE_TYPE_SLOTS -#if PY_MAJOR_VERSION >= 3 - if (likely(PyUnicode_Check(n))) -#else - if (likely(PyString_Check(n))) -#endif - return __Pyx_PyObject_GetAttrStr(o, n); -#endif - return PyObject_GetAttr(o, n); -} - -/* GetAttr3 */ -static PyObject *__Pyx_GetAttr3Default(PyObject *d) { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - if (unlikely(!__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) - return NULL; - __Pyx_PyErr_Clear(); - Py_INCREF(d); - return d; -} -static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) { - PyObject *r = __Pyx_GetAttr(o, n); - return (likely(r)) ? r : __Pyx_GetAttr3Default(d); -} - -/* PyDictVersioning */ -#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) { - PyObject *dict = Py_TYPE(obj)->tp_dict; - return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0; -} -static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) { - PyObject **dictptr = NULL; - Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset; - if (offset) { -#if CYTHON_COMPILING_IN_CPYTHON - dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj); -#else - dictptr = _PyObject_GetDictPtr(obj); -#endif - } - return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0; -} -static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) { - PyObject *dict = Py_TYPE(obj)->tp_dict; - if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict))) - return 0; - return obj_dict_version == __Pyx_get_object_dict_version(obj); -} -#endif - -/* GetModuleGlobalName */ -#if CYTHON_USE_DICT_VERSIONS -static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) -#else -static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) -#endif -{ - PyObject *result; -#if !CYTHON_AVOID_BORROWED_REFS -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 - result = _PyDict_GetItem_KnownHash(__pyx_d, name, ((PyASCIIObject *) name)->hash); - __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) - if (likely(result)) { - return __Pyx_NewRef(result); - } else if (unlikely(PyErr_Occurred())) { - return NULL; - } -#else - result = PyDict_GetItem(__pyx_d, name); - __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) - if (likely(result)) { - return __Pyx_NewRef(result); - } -#endif -#else - result = PyObject_GetItem(__pyx_d, name); - __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) - if (likely(result)) { - return __Pyx_NewRef(result); - } - PyErr_Clear(); -#endif - return __Pyx_GetBuiltinName(name); -} - -/* Import */ -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { - PyObject *empty_list = 0; - PyObject *module = 0; - PyObject *global_dict = 0; - PyObject *empty_dict = 0; - PyObject *list; - #if PY_MAJOR_VERSION < 3 - PyObject *py_import; - py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); - if (!py_import) - goto bad; - #endif - if (from_list) - list = from_list; - else { - empty_list = PyList_New(0); - if (!empty_list) - goto bad; - list = empty_list; - } - global_dict = PyModule_GetDict(__pyx_m); - if (!global_dict) - goto bad; - empty_dict = PyDict_New(); - if (!empty_dict) - goto bad; - { - #if PY_MAJOR_VERSION >= 3 - if (level == -1) { - if ((1) && (strchr(__Pyx_MODULE_NAME, '.'))) { - module = PyImport_ImportModuleLevelObject( - name, global_dict, empty_dict, list, 1); - if (!module) { - if (!PyErr_ExceptionMatches(PyExc_ImportError)) - goto bad; - PyErr_Clear(); - } - } - level = 0; - } - #endif - if (!module) { - #if PY_MAJOR_VERSION < 3 - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, (PyObject *)NULL); - Py_DECREF(py_level); - #else - module = PyImport_ImportModuleLevelObject( - name, global_dict, empty_dict, list, level); - #endif - } - } -bad: - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(py_import); - #endif - Py_XDECREF(empty_list); - Py_XDECREF(empty_dict); - return module; -} - -/* ImportFrom */ -static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { - PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); - if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Format(PyExc_ImportError, - #if PY_MAJOR_VERSION < 3 - "cannot import name %.230s", PyString_AS_STRING(name)); - #else - "cannot import name %S", name); - #endif - } - return value; -} - -/* HasAttr */ -static CYTHON_INLINE int __Pyx_HasAttr(PyObject *o, PyObject *n) { - PyObject *r; - if (unlikely(!__Pyx_PyBaseString_Check(n))) { - PyErr_SetString(PyExc_TypeError, - "hasattr(): attribute name must be string"); - return -1; - } - r = __Pyx_GetAttr(o, n); - if (unlikely(!r)) { - PyErr_Clear(); - return 0; - } else { - Py_DECREF(r); - return 1; - } -} - -/* PyObject_GenericGetAttrNoDict */ -#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 -static PyObject *__Pyx_RaiseGenericGetAttributeError(PyTypeObject *tp, PyObject *attr_name) { - PyErr_Format(PyExc_AttributeError, -#if PY_MAJOR_VERSION >= 3 - "'%.50s' object has no attribute '%U'", - tp->tp_name, attr_name); -#else - "'%.50s' object has no attribute '%.400s'", - tp->tp_name, PyString_AS_STRING(attr_name)); -#endif - return NULL; -} -static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name) { - PyObject *descr; - PyTypeObject *tp = Py_TYPE(obj); - if (unlikely(!PyString_Check(attr_name))) { - return PyObject_GenericGetAttr(obj, attr_name); - } - assert(!tp->tp_dictoffset); - descr = _PyType_Lookup(tp, attr_name); - if (unlikely(!descr)) { - return __Pyx_RaiseGenericGetAttributeError(tp, attr_name); - } - Py_INCREF(descr); - #if PY_MAJOR_VERSION < 3 - if (likely(PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_HAVE_CLASS))) - #endif - { - descrgetfunc f = Py_TYPE(descr)->tp_descr_get; - if (unlikely(f)) { - PyObject *res = f(descr, obj, (PyObject *)tp); - Py_DECREF(descr); - return res; - } - } - return descr; -} -#endif - -/* PyObject_GenericGetAttr */ -#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 -static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name) { - if (unlikely(Py_TYPE(obj)->tp_dictoffset)) { - return PyObject_GenericGetAttr(obj, attr_name); - } - return __Pyx_PyObject_GenericGetAttrNoDict(obj, attr_name); -} -#endif - -/* PyObjectGetAttrStrNoError */ -static void __Pyx_PyObject_GetAttrStr_ClearAttributeError(void) { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - if (likely(__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) - __Pyx_PyErr_Clear(); -} -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name) { - PyObject *result; -#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_TYPE_SLOTS && PY_VERSION_HEX >= 0x030700B1 - PyTypeObject* tp = Py_TYPE(obj); - if (likely(tp->tp_getattro == PyObject_GenericGetAttr)) { - return _PyObject_GenericGetAttrWithDict(obj, attr_name, NULL, 1); - } -#endif - result = __Pyx_PyObject_GetAttrStr(obj, attr_name); - if (unlikely(!result)) { - __Pyx_PyObject_GetAttrStr_ClearAttributeError(); - } - return result; -} - -/* SetupReduce */ -static int __Pyx_setup_reduce_is_named(PyObject* meth, PyObject* name) { - int ret; - PyObject *name_attr; - name_attr = __Pyx_PyObject_GetAttrStr(meth, __pyx_n_s_name); - if (likely(name_attr)) { - ret = PyObject_RichCompareBool(name_attr, name, Py_EQ); - } else { - ret = -1; - } - if (unlikely(ret < 0)) { - PyErr_Clear(); - ret = 0; - } - Py_XDECREF(name_attr); - return ret; -} -static int __Pyx_setup_reduce(PyObject* type_obj) { - int ret = 0; - PyObject *object_reduce = NULL; - PyObject *object_reduce_ex = NULL; - PyObject *reduce = NULL; - PyObject *reduce_ex = NULL; - PyObject *reduce_cython = NULL; - PyObject *setstate = NULL; - PyObject *setstate_cython = NULL; -#if CYTHON_USE_PYTYPE_LOOKUP - if (_PyType_Lookup((PyTypeObject*)type_obj, __pyx_n_s_getstate)) goto __PYX_GOOD; -#else - if (PyObject_HasAttr(type_obj, __pyx_n_s_getstate)) goto __PYX_GOOD; -#endif -#if CYTHON_USE_PYTYPE_LOOKUP - object_reduce_ex = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; -#else - object_reduce_ex = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; -#endif - reduce_ex = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce_ex); if (unlikely(!reduce_ex)) goto __PYX_BAD; - if (reduce_ex == object_reduce_ex) { -#if CYTHON_USE_PYTYPE_LOOKUP - object_reduce = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_reduce); if (!object_reduce) goto __PYX_BAD; -#else - object_reduce = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce); if (!object_reduce) goto __PYX_BAD; -#endif - reduce = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce); if (unlikely(!reduce)) goto __PYX_BAD; - if (reduce == object_reduce || __Pyx_setup_reduce_is_named(reduce, __pyx_n_s_reduce_cython)) { - reduce_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_n_s_reduce_cython); - if (likely(reduce_cython)) { - ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce, reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; - ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; - } else if (reduce == object_reduce || PyErr_Occurred()) { - goto __PYX_BAD; - } - setstate = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_setstate); - if (!setstate) PyErr_Clear(); - if (!setstate || __Pyx_setup_reduce_is_named(setstate, __pyx_n_s_setstate_cython)) { - setstate_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_n_s_setstate_cython); - if (likely(setstate_cython)) { - ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate, setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; - ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; - } else if (!setstate || PyErr_Occurred()) { - goto __PYX_BAD; - } - } - PyType_Modified((PyTypeObject*)type_obj); - } - } - goto __PYX_GOOD; -__PYX_BAD: - if (!PyErr_Occurred()) - PyErr_Format(PyExc_RuntimeError, "Unable to initialize pickling for %s", ((PyTypeObject*)type_obj)->tp_name); - ret = -1; -__PYX_GOOD: -#if !CYTHON_USE_PYTYPE_LOOKUP - Py_XDECREF(object_reduce); - Py_XDECREF(object_reduce_ex); -#endif - Py_XDECREF(reduce); - Py_XDECREF(reduce_ex); - Py_XDECREF(reduce_cython); - Py_XDECREF(setstate); - Py_XDECREF(setstate_cython); - return ret; -} - -/* CLineInTraceback */ -#ifndef CYTHON_CLINE_IN_TRACEBACK -static int __Pyx_CLineForTraceback(CYTHON_NCP_UNUSED PyThreadState *tstate, int c_line) { - PyObject *use_cline; - PyObject *ptype, *pvalue, *ptraceback; -#if CYTHON_COMPILING_IN_CPYTHON - PyObject **cython_runtime_dict; -#endif - if (unlikely(!__pyx_cython_runtime)) { - return c_line; - } - __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); -#if CYTHON_COMPILING_IN_CPYTHON - cython_runtime_dict = _PyObject_GetDictPtr(__pyx_cython_runtime); - if (likely(cython_runtime_dict)) { - __PYX_PY_DICT_LOOKUP_IF_MODIFIED( - use_cline, *cython_runtime_dict, - __Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_n_s_cline_in_traceback)) - } else -#endif - { - PyObject *use_cline_obj = __Pyx_PyObject_GetAttrStr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback); - if (use_cline_obj) { - use_cline = PyObject_Not(use_cline_obj) ? Py_False : Py_True; - Py_DECREF(use_cline_obj); - } else { - PyErr_Clear(); - use_cline = NULL; - } - } - if (!use_cline) { - c_line = 0; - PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False); - } - else if (use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { - c_line = 0; - } - __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); - return c_line; -} -#endif - -/* CodeObjectCache */ -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { - int start = 0, mid = 0, end = count - 1; - if (end >= 0 && code_line > entries[end].code_line) { - return count; - } - while (start < end) { - mid = start + (end - start) / 2; - if (code_line < entries[mid].code_line) { - end = mid; - } else if (code_line > entries[mid].code_line) { - start = mid + 1; - } else { - return mid; - } - } - if (code_line <= entries[mid].code_line) { - return mid; - } else { - return mid + 1; - } -} -static PyCodeObject *__pyx_find_code_object(int code_line) { - PyCodeObject* code_object; - int pos; - if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { - return NULL; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { - return NULL; - } - code_object = __pyx_code_cache.entries[pos].code_object; - Py_INCREF(code_object); - return code_object; -} -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { - int pos, i; - __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; - if (unlikely(!code_line)) { - return; - } - if (unlikely(!entries)) { - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); - if (likely(entries)) { - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = 64; - __pyx_code_cache.count = 1; - entries[0].code_line = code_line; - entries[0].code_object = code_object; - Py_INCREF(code_object); - } - return; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { - PyCodeObject* tmp = entries[pos].code_object; - entries[pos].code_object = code_object; - Py_DECREF(tmp); - return; - } - if (__pyx_code_cache.count == __pyx_code_cache.max_count) { - int new_max = __pyx_code_cache.max_count + 64; - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( - __pyx_code_cache.entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry)); - if (unlikely(!entries)) { - return; - } - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = new_max; - } - for (i=__pyx_code_cache.count; i>pos; i--) { - entries[i] = entries[i-1]; - } - entries[pos].code_line = code_line; - entries[pos].code_object = code_object; - __pyx_code_cache.count++; - Py_INCREF(code_object); -} - -/* AddTraceback */ -#include "compile.h" -#include "frameobject.h" -#include "traceback.h" -static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( - const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyObject *py_srcfile = 0; - PyObject *py_funcname = 0; - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(filename); - #else - py_srcfile = PyUnicode_FromString(filename); - #endif - if (!py_srcfile) goto bad; - if (c_line) { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #endif - } - else { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromString(funcname); - #else - py_funcname = PyUnicode_FromString(funcname); - #endif - } - if (!py_funcname) goto bad; - py_code = __Pyx_PyCode_New( - 0, - 0, - 0, - 0, - 0, - __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ - py_srcfile, /*PyObject *filename,*/ - py_funcname, /*PyObject *name,*/ - py_line, - __pyx_empty_bytes /*PyObject *lnotab*/ - ); - Py_DECREF(py_srcfile); - Py_DECREF(py_funcname); - return py_code; -bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); - return NULL; -} -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - PyThreadState *tstate = __Pyx_PyThreadState_Current; - if (c_line) { - c_line = __Pyx_CLineForTraceback(tstate, c_line); - } - py_code = __pyx_find_code_object(c_line ? -c_line : py_line); - if (!py_code) { - py_code = __Pyx_CreateCodeObjectForTraceback( - funcname, c_line, py_line, filename); - if (!py_code) goto bad; - __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); - } - py_frame = PyFrame_New( - tstate, /*PyThreadState *tstate,*/ - py_code, /*PyCodeObject *code,*/ - __pyx_d, /*PyObject *globals,*/ - 0 /*PyObject *locals*/ - ); - if (!py_frame) goto bad; - __Pyx_PyFrame_SetLineNumber(py_frame, py_line); - PyTraceBack_Here(py_frame); -bad: - Py_XDECREF(py_code); - Py_XDECREF(py_frame); -} - -/* CIntFromPyVerify */ -#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ - __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) -#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ - __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) -#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ - {\ - func_type value = func_value;\ - if (sizeof(target_type) < sizeof(func_type)) {\ - if (unlikely(value != (func_type) (target_type) value)) {\ - func_type zero = 0;\ - if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ - return (target_type) -1;\ - if (is_unsigned && unlikely(value < zero))\ - goto raise_neg_overflow;\ - else\ - goto raise_overflow;\ - }\ - }\ - return (target_type) value;\ - } - -/* CIntFromPy */ -static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - const long neg_one = (long) -1, const_zero = (long) 0; -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic pop -#endif - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - if (sizeof(long) < sizeof(long)) { - __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) - } else { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - goto raise_neg_overflow; - } - return (long) val; - } - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (long) 0; - case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0]) - case 2: - if (8 * sizeof(long) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) { - return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - case 3: - if (8 * sizeof(long) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) { - return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - case 4: - if (8 * sizeof(long) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) { - return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - } -#endif -#if CYTHON_COMPILING_IN_CPYTHON - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } -#else - { - int result = PyObject_RichCompareBool(x, Py_False, Py_LT); - if (unlikely(result < 0)) - return (long) -1; - if (unlikely(result == 1)) - goto raise_neg_overflow; - } -#endif - if (sizeof(long) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) -#endif - } - } else { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (long) 0; - case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0])) - case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0]) - case -2: - if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 2: - if (8 * sizeof(long) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case -3: - if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 3: - if (8 * sizeof(long) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case -4: - if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 4: - if (8 * sizeof(long) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - } -#endif - if (sizeof(long) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) -#endif - } - } - { -#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); -#else - long val; - PyObject *v = __Pyx_PyNumber_IntOrLong(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } -#endif - return (long) -1; - } - } else { - long val; - PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); - if (!tmp) return (long) -1; - val = __Pyx_PyInt_As_long(tmp); - Py_DECREF(tmp); - return val; - } -raise_overflow: - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to long"); - return (long) -1; -raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long) -1; -} - -/* CIntToPy */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - const long neg_one = (long) -1, const_zero = (long) 0; -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic pop -#endif - const int is_unsigned = neg_one > const_zero; - if (is_unsigned) { - if (sizeof(long) < sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof(long) <= sizeof(unsigned long)) { - return PyLong_FromUnsignedLong((unsigned long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); -#endif - } - } else { - if (sizeof(long) <= sizeof(long)) { - return PyInt_FromLong((long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { - return PyLong_FromLongLong((PY_LONG_LONG) value); -#endif - } - } - { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&value; - return _PyLong_FromByteArray(bytes, sizeof(long), - little, !is_unsigned); - } -} - -/* CIntFromPy */ -static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - const int neg_one = (int) -1, const_zero = (int) 0; -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic pop -#endif - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - if (sizeof(int) < sizeof(long)) { - __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) - } else { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - goto raise_neg_overflow; - } - return (int) val; - } - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (int) 0; - case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0]) - case 2: - if (8 * sizeof(int) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) { - return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - case 3: - if (8 * sizeof(int) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) { - return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - case 4: - if (8 * sizeof(int) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) { - return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - } -#endif -#if CYTHON_COMPILING_IN_CPYTHON - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } -#else - { - int result = PyObject_RichCompareBool(x, Py_False, Py_LT); - if (unlikely(result < 0)) - return (int) -1; - if (unlikely(result == 1)) - goto raise_neg_overflow; - } -#endif - if (sizeof(int) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) -#endif - } - } else { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (int) 0; - case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0])) - case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0]) - case -2: - if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 2: - if (8 * sizeof(int) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case -3: - if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 3: - if (8 * sizeof(int) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case -4: - if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 4: - if (8 * sizeof(int) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { - return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - } -#endif - if (sizeof(int) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) -#endif - } - } - { -#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); -#else - int val; - PyObject *v = __Pyx_PyNumber_IntOrLong(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } -#endif - return (int) -1; - } - } else { - int val; - PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); - if (!tmp) return (int) -1; - val = __Pyx_PyInt_As_int(tmp); - Py_DECREF(tmp); - return val; - } -raise_overflow: - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to int"); - return (int) -1; -raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to int"); - return (int) -1; -} - -/* FastTypeChecks */ -#if CYTHON_COMPILING_IN_CPYTHON -static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { - while (a) { - a = a->tp_base; - if (a == b) - return 1; - } - return b == &PyBaseObject_Type; -} -static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { - PyObject *mro; - if (a == b) return 1; - mro = a->tp_mro; - if (likely(mro)) { - Py_ssize_t i, n; - n = PyTuple_GET_SIZE(mro); - for (i = 0; i < n; i++) { - if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) - return 1; - } - return 0; - } - return __Pyx_InBases(a, b); -} -#if PY_MAJOR_VERSION == 2 -static int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject* exc_type2) { - PyObject *exception, *value, *tb; - int res; - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ErrFetch(&exception, &value, &tb); - res = exc_type1 ? PyObject_IsSubclass(err, exc_type1) : 0; - if (unlikely(res == -1)) { - PyErr_WriteUnraisable(err); - res = 0; - } - if (!res) { - res = PyObject_IsSubclass(err, exc_type2); - if (unlikely(res == -1)) { - PyErr_WriteUnraisable(err); - res = 0; - } - } - __Pyx_ErrRestore(exception, value, tb); - return res; -} -#else -static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { - int res = exc_type1 ? __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type1) : 0; - if (!res) { - res = __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); - } - return res; -} -#endif -static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { - Py_ssize_t i, n; - assert(PyExceptionClass_Check(exc_type)); - n = PyTuple_GET_SIZE(tuple); -#if PY_MAJOR_VERSION >= 3 - for (i=0; ip) { - #if PY_MAJOR_VERSION < 3 - if (t->is_unicode) { - *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); - } else if (t->intern) { - *t->p = PyString_InternFromString(t->s); - } else { - *t->p = PyString_FromStringAndSize(t->s, t->n - 1); - } - #else - if (t->is_unicode | t->is_str) { - if (t->intern) { - *t->p = PyUnicode_InternFromString(t->s); - } else if (t->encoding) { - *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); - } else { - *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); - } - } else { - *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); - } - #endif - if (!*t->p) - return -1; - if (PyObject_Hash(*t->p) == -1) - return -1; - ++t; - } - return 0; -} - -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { - return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); -} -static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { - Py_ssize_t ignore; - return __Pyx_PyObject_AsStringAndSize(o, &ignore); -} -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT -#if !CYTHON_PEP393_ENABLED -static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { - char* defenc_c; - PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); - if (!defenc) return NULL; - defenc_c = PyBytes_AS_STRING(defenc); -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - { - char* end = defenc_c + PyBytes_GET_SIZE(defenc); - char* c; - for (c = defenc_c; c < end; c++) { - if ((unsigned char) (*c) >= 128) { - PyUnicode_AsASCIIString(o); - return NULL; - } - } - } -#endif - *length = PyBytes_GET_SIZE(defenc); - return defenc_c; -} -#else -static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { - if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - if (likely(PyUnicode_IS_ASCII(o))) { - *length = PyUnicode_GET_LENGTH(o); - return PyUnicode_AsUTF8(o); - } else { - PyUnicode_AsASCIIString(o); - return NULL; - } -#else - return PyUnicode_AsUTF8AndSize(o, length); -#endif -} -#endif -#endif -static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT - if ( -#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - __Pyx_sys_getdefaultencoding_not_ascii && -#endif - PyUnicode_Check(o)) { - return __Pyx_PyUnicode_AsStringAndSize(o, length); - } else -#endif -#if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) - if (PyByteArray_Check(o)) { - *length = PyByteArray_GET_SIZE(o); - return PyByteArray_AS_STRING(o); - } else -#endif - { - char* result; - int r = PyBytes_AsStringAndSize(o, &result, length); - if (unlikely(r < 0)) { - return NULL; - } else { - return result; - } - } -} -static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { - int is_true = x == Py_True; - if (is_true | (x == Py_False) | (x == Py_None)) return is_true; - else return PyObject_IsTrue(x); -} -static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { - int retval; - if (unlikely(!x)) return -1; - retval = __Pyx_PyObject_IsTrue(x); - Py_DECREF(x); - return retval; -} -static PyObject* __Pyx_PyNumber_IntOrLongWrongResultType(PyObject* result, const char* type_name) { -#if PY_MAJOR_VERSION >= 3 - if (PyLong_Check(result)) { - if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, - "__int__ returned non-int (type %.200s). " - "The ability to return an instance of a strict subclass of int " - "is deprecated, and may be removed in a future version of Python.", - Py_TYPE(result)->tp_name)) { - Py_DECREF(result); - return NULL; - } - return result; - } -#endif - PyErr_Format(PyExc_TypeError, - "__%.4s__ returned non-%.4s (type %.200s)", - type_name, type_name, Py_TYPE(result)->tp_name); - Py_DECREF(result); - return NULL; -} -static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { -#if CYTHON_USE_TYPE_SLOTS - PyNumberMethods *m; -#endif - const char *name = NULL; - PyObject *res = NULL; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x) || PyLong_Check(x))) -#else - if (likely(PyLong_Check(x))) -#endif - return __Pyx_NewRef(x); -#if CYTHON_USE_TYPE_SLOTS - m = Py_TYPE(x)->tp_as_number; - #if PY_MAJOR_VERSION < 3 - if (m && m->nb_int) { - name = "int"; - res = m->nb_int(x); - } - else if (m && m->nb_long) { - name = "long"; - res = m->nb_long(x); - } - #else - if (likely(m && m->nb_int)) { - name = "int"; - res = m->nb_int(x); - } - #endif -#else - if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { - res = PyNumber_Int(x); - } -#endif - if (likely(res)) { -#if PY_MAJOR_VERSION < 3 - if (unlikely(!PyInt_Check(res) && !PyLong_Check(res))) { -#else - if (unlikely(!PyLong_CheckExact(res))) { -#endif - return __Pyx_PyNumber_IntOrLongWrongResultType(res, name); - } - } - else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, - "an integer is required"); - } - return res; -} -static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { - Py_ssize_t ival; - PyObject *x; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_CheckExact(b))) { - if (sizeof(Py_ssize_t) >= sizeof(long)) - return PyInt_AS_LONG(b); - else - return PyInt_AsSsize_t(b); - } -#endif - if (likely(PyLong_CheckExact(b))) { - #if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)b)->ob_digit; - const Py_ssize_t size = Py_SIZE(b); - if (likely(__Pyx_sst_abs(size) <= 1)) { - ival = likely(size) ? digits[0] : 0; - if (size == -1) ival = -ival; - return ival; - } else { - switch (size) { - case 2: - if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { - return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -2: - if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case 3: - if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { - return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -3: - if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case 4: - if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { - return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -4: - if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - } - } - #endif - return PyLong_AsSsize_t(b); - } - x = PyNumber_Index(b); - if (!x) return -1; - ival = PyInt_AsSsize_t(x); - Py_DECREF(x); - return ival; -} -static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { - return b ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False); -} -static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { - return PyInt_FromSize_t(ival); -} - - -#endif /* Py_PYTHON_H */ diff --git a/.venv/Lib/site-packages/aiohttp/_helpers.cp38-win_amd64.pyd b/.venv/Lib/site-packages/aiohttp/_helpers.cp38-win_amd64.pyd deleted file mode 100644 index 1710e42..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/_helpers.cp38-win_amd64.pyd and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/_helpers.pyi b/.venv/Lib/site-packages/aiohttp/_helpers.pyi deleted file mode 100644 index 1e35893..0000000 --- a/.venv/Lib/site-packages/aiohttp/_helpers.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from typing import Any - -class reify: - def __init__(self, wrapped: Any) -> None: ... - def __get__(self, inst: Any, owner: Any) -> Any: ... - def __set__(self, inst: Any, value: Any) -> None: ... diff --git a/.venv/Lib/site-packages/aiohttp/_helpers.pyx b/.venv/Lib/site-packages/aiohttp/_helpers.pyx deleted file mode 100644 index 665f367..0000000 --- a/.venv/Lib/site-packages/aiohttp/_helpers.pyx +++ /dev/null @@ -1,35 +0,0 @@ -cdef class reify: - """Use as a class method decorator. It operates almost exactly like - the Python `@property` decorator, but it puts the result of the - method it decorates into the instance dict after the first call, - effectively replacing the function it decorates with an instance - variable. It is, in Python parlance, a data descriptor. - - """ - - cdef object wrapped - cdef object name - - def __init__(self, wrapped): - self.wrapped = wrapped - self.name = wrapped.__name__ - - @property - def __doc__(self): - return self.wrapped.__doc__ - - def __get__(self, inst, owner): - try: - try: - return inst._cache[self.name] - except KeyError: - val = self.wrapped(inst) - inst._cache[self.name] = val - return val - except AttributeError: - if inst is None: - return self - raise - - def __set__(self, inst, value): - raise AttributeError("reified property is read-only") diff --git a/.venv/Lib/site-packages/aiohttp/_http_parser.c b/.venv/Lib/site-packages/aiohttp/_http_parser.c deleted file mode 100644 index 640de7b..0000000 --- a/.venv/Lib/site-packages/aiohttp/_http_parser.c +++ /dev/null @@ -1,23880 +0,0 @@ -/* Generated by Cython 0.29.24 */ - -#ifndef PY_SSIZE_T_CLEAN -#define PY_SSIZE_T_CLEAN -#endif /* PY_SSIZE_T_CLEAN */ -#include "Python.h" -#ifndef Py_PYTHON_H - #error Python headers needed to compile C extensions, please install development version of Python. -#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03030000) - #error Cython requires Python 2.6+ or Python 3.3+. -#else -#define CYTHON_ABI "0_29_24" -#define CYTHON_HEX_VERSION 0x001D18F0 -#define CYTHON_FUTURE_DIVISION 1 -#include -#ifndef offsetof - #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) -#endif -#if !defined(WIN32) && !defined(MS_WINDOWS) - #ifndef __stdcall - #define __stdcall - #endif - #ifndef __cdecl - #define __cdecl - #endif - #ifndef __fastcall - #define __fastcall - #endif -#endif -#ifndef DL_IMPORT - #define DL_IMPORT(t) t -#endif -#ifndef DL_EXPORT - #define DL_EXPORT(t) t -#endif -#define __PYX_COMMA , -#ifndef HAVE_LONG_LONG - #if PY_VERSION_HEX >= 0x02070000 - #define HAVE_LONG_LONG - #endif -#endif -#ifndef PY_LONG_LONG - #define PY_LONG_LONG LONG_LONG -#endif -#ifndef Py_HUGE_VAL - #define Py_HUGE_VAL HUGE_VAL -#endif -#ifdef PYPY_VERSION - #define CYTHON_COMPILING_IN_PYPY 1 - #define CYTHON_COMPILING_IN_PYSTON 0 - #define CYTHON_COMPILING_IN_CPYTHON 0 - #undef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 0 - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #if PY_VERSION_HEX < 0x03050000 - #undef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 0 - #elif !defined(CYTHON_USE_ASYNC_SLOTS) - #define CYTHON_USE_ASYNC_SLOTS 1 - #endif - #undef CYTHON_USE_PYLIST_INTERNALS - #define CYTHON_USE_PYLIST_INTERNALS 0 - #undef CYTHON_USE_UNICODE_INTERNALS - #define CYTHON_USE_UNICODE_INTERNALS 0 - #undef CYTHON_USE_UNICODE_WRITER - #define CYTHON_USE_UNICODE_WRITER 0 - #undef CYTHON_USE_PYLONG_INTERNALS - #define CYTHON_USE_PYLONG_INTERNALS 0 - #undef CYTHON_AVOID_BORROWED_REFS - #define CYTHON_AVOID_BORROWED_REFS 1 - #undef CYTHON_ASSUME_SAFE_MACROS - #define CYTHON_ASSUME_SAFE_MACROS 0 - #undef CYTHON_UNPACK_METHODS - #define CYTHON_UNPACK_METHODS 0 - #undef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 0 - #undef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL 0 - #undef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT 0 - #undef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE 0 - #undef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS 0 - #undef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK 0 -#elif defined(PYSTON_VERSION) - #define CYTHON_COMPILING_IN_PYPY 0 - #define CYTHON_COMPILING_IN_PYSTON 1 - #define CYTHON_COMPILING_IN_CPYTHON 0 - #ifndef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 1 - #endif - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #undef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 0 - #undef CYTHON_USE_PYLIST_INTERNALS - #define CYTHON_USE_PYLIST_INTERNALS 0 - #ifndef CYTHON_USE_UNICODE_INTERNALS - #define CYTHON_USE_UNICODE_INTERNALS 1 - #endif - #undef CYTHON_USE_UNICODE_WRITER - #define CYTHON_USE_UNICODE_WRITER 0 - #undef CYTHON_USE_PYLONG_INTERNALS - #define CYTHON_USE_PYLONG_INTERNALS 0 - #ifndef CYTHON_AVOID_BORROWED_REFS - #define CYTHON_AVOID_BORROWED_REFS 0 - #endif - #ifndef CYTHON_ASSUME_SAFE_MACROS - #define CYTHON_ASSUME_SAFE_MACROS 1 - #endif - #ifndef CYTHON_UNPACK_METHODS - #define CYTHON_UNPACK_METHODS 1 - #endif - #undef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 0 - #undef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL 0 - #undef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT 0 - #undef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE 0 - #undef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS 0 - #undef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK 0 -#else - #define CYTHON_COMPILING_IN_PYPY 0 - #define CYTHON_COMPILING_IN_PYSTON 0 - #define CYTHON_COMPILING_IN_CPYTHON 1 - #ifndef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 1 - #endif - #if PY_VERSION_HEX < 0x02070000 - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #elif !defined(CYTHON_USE_PYTYPE_LOOKUP) - #define CYTHON_USE_PYTYPE_LOOKUP 1 - #endif - #if PY_MAJOR_VERSION < 3 - #undef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 0 - #elif !defined(CYTHON_USE_ASYNC_SLOTS) - #define CYTHON_USE_ASYNC_SLOTS 1 - #endif - #if PY_VERSION_HEX < 0x02070000 - #undef CYTHON_USE_PYLONG_INTERNALS - #define CYTHON_USE_PYLONG_INTERNALS 0 - #elif !defined(CYTHON_USE_PYLONG_INTERNALS) - #define CYTHON_USE_PYLONG_INTERNALS 1 - #endif - #ifndef CYTHON_USE_PYLIST_INTERNALS - #define CYTHON_USE_PYLIST_INTERNALS 1 - #endif - #ifndef CYTHON_USE_UNICODE_INTERNALS - #define CYTHON_USE_UNICODE_INTERNALS 1 - #endif - #if PY_VERSION_HEX < 0x030300F0 - #undef CYTHON_USE_UNICODE_WRITER - #define CYTHON_USE_UNICODE_WRITER 0 - #elif !defined(CYTHON_USE_UNICODE_WRITER) - #define CYTHON_USE_UNICODE_WRITER 1 - #endif - #ifndef CYTHON_AVOID_BORROWED_REFS - #define CYTHON_AVOID_BORROWED_REFS 0 - #endif - #ifndef CYTHON_ASSUME_SAFE_MACROS - #define CYTHON_ASSUME_SAFE_MACROS 1 - #endif - #ifndef CYTHON_UNPACK_METHODS - #define CYTHON_UNPACK_METHODS 1 - #endif - #ifndef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 1 - #endif - #ifndef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL 1 - #endif - #ifndef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT (PY_VERSION_HEX >= 0x03050000) - #endif - #ifndef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE (PY_VERSION_HEX >= 0x030400a1) - #endif - #ifndef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX >= 0x030600B1) - #endif - #ifndef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK (PY_VERSION_HEX >= 0x030700A3) - #endif -#endif -#if !defined(CYTHON_FAST_PYCCALL) -#define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) -#endif -#if CYTHON_USE_PYLONG_INTERNALS - #include "longintrepr.h" - #undef SHIFT - #undef BASE - #undef MASK - #ifdef SIZEOF_VOID_P - enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; - #endif -#endif -#ifndef __has_attribute - #define __has_attribute(x) 0 -#endif -#ifndef __has_cpp_attribute - #define __has_cpp_attribute(x) 0 -#endif -#ifndef CYTHON_RESTRICT - #if defined(__GNUC__) - #define CYTHON_RESTRICT __restrict__ - #elif defined(_MSC_VER) && _MSC_VER >= 1400 - #define CYTHON_RESTRICT __restrict - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_RESTRICT restrict - #else - #define CYTHON_RESTRICT - #endif -#endif -#ifndef CYTHON_UNUSED -# if defined(__GNUC__) -# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) -# define CYTHON_UNUSED __attribute__ ((__unused__)) -# else -# define CYTHON_UNUSED -# endif -# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) -# define CYTHON_UNUSED __attribute__ ((__unused__)) -# else -# define CYTHON_UNUSED -# endif -#endif -#ifndef CYTHON_MAYBE_UNUSED_VAR -# if defined(__cplusplus) - template void CYTHON_MAYBE_UNUSED_VAR( const T& ) { } -# else -# define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x) -# endif -#endif -#ifndef CYTHON_NCP_UNUSED -# if CYTHON_COMPILING_IN_CPYTHON -# define CYTHON_NCP_UNUSED -# else -# define CYTHON_NCP_UNUSED CYTHON_UNUSED -# endif -#endif -#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) -#ifdef _MSC_VER - #ifndef _MSC_STDINT_H_ - #if _MSC_VER < 1300 - typedef unsigned char uint8_t; - typedef unsigned int uint32_t; - #else - typedef unsigned __int8 uint8_t; - typedef unsigned __int32 uint32_t; - #endif - #endif -#else - #include -#endif -#ifndef CYTHON_FALLTHROUGH - #if defined(__cplusplus) && __cplusplus >= 201103L - #if __has_cpp_attribute(fallthrough) - #define CYTHON_FALLTHROUGH [[fallthrough]] - #elif __has_cpp_attribute(clang::fallthrough) - #define CYTHON_FALLTHROUGH [[clang::fallthrough]] - #elif __has_cpp_attribute(gnu::fallthrough) - #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] - #endif - #endif - #ifndef CYTHON_FALLTHROUGH - #if __has_attribute(fallthrough) - #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) - #else - #define CYTHON_FALLTHROUGH - #endif - #endif - #if defined(__clang__ ) && defined(__apple_build_version__) - #if __apple_build_version__ < 7000000 - #undef CYTHON_FALLTHROUGH - #define CYTHON_FALLTHROUGH - #endif - #endif -#endif - -#ifndef CYTHON_INLINE - #if defined(__clang__) - #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) - #elif defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline - #else - #define CYTHON_INLINE - #endif -#endif - -#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) - #define Py_OptimizeFlag 0 -#endif -#define __PYX_BUILD_PY_SSIZE_T "n" -#define CYTHON_FORMAT_SSIZE_T "z" -#if PY_MAJOR_VERSION < 3 - #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) - #define __Pyx_DefaultClassType PyClass_Type -#else - #define __Pyx_BUILTIN_MODULE_NAME "builtins" -#if PY_VERSION_HEX >= 0x030800A4 && PY_VERSION_HEX < 0x030800B2 - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a, 0, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) -#else - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) -#endif - #define __Pyx_DefaultClassType PyType_Type -#endif -#ifndef Py_TPFLAGS_CHECKTYPES - #define Py_TPFLAGS_CHECKTYPES 0 -#endif -#ifndef Py_TPFLAGS_HAVE_INDEX - #define Py_TPFLAGS_HAVE_INDEX 0 -#endif -#ifndef Py_TPFLAGS_HAVE_NEWBUFFER - #define Py_TPFLAGS_HAVE_NEWBUFFER 0 -#endif -#ifndef Py_TPFLAGS_HAVE_FINALIZE - #define Py_TPFLAGS_HAVE_FINALIZE 0 -#endif -#ifndef METH_STACKLESS - #define METH_STACKLESS 0 -#endif -#if PY_VERSION_HEX <= 0x030700A3 || !defined(METH_FASTCALL) - #ifndef METH_FASTCALL - #define METH_FASTCALL 0x80 - #endif - typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); - typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, - Py_ssize_t nargs, PyObject *kwnames); -#else - #define __Pyx_PyCFunctionFast _PyCFunctionFast - #define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords -#endif -#if CYTHON_FAST_PYCCALL -#define __Pyx_PyFastCFunction_Check(func)\ - ((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))))) -#else -#define __Pyx_PyFastCFunction_Check(func) 0 -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) - #define PyObject_Malloc(s) PyMem_Malloc(s) - #define PyObject_Free(p) PyMem_Free(p) - #define PyObject_Realloc(p) PyMem_Realloc(p) -#endif -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030400A1 - #define PyMem_RawMalloc(n) PyMem_Malloc(n) - #define PyMem_RawRealloc(p, n) PyMem_Realloc(p, n) - #define PyMem_RawFree(p) PyMem_Free(p) -#endif -#if CYTHON_COMPILING_IN_PYSTON - #define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co) - #define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno) -#else - #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) - #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) -#endif -#if !CYTHON_FAST_THREAD_STATE || PY_VERSION_HEX < 0x02070000 - #define __Pyx_PyThreadState_Current PyThreadState_GET() -#elif PY_VERSION_HEX >= 0x03060000 - #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() -#elif PY_VERSION_HEX >= 0x03000000 - #define __Pyx_PyThreadState_Current PyThreadState_GET() -#else - #define __Pyx_PyThreadState_Current _PyThreadState_Current -#endif -#if PY_VERSION_HEX < 0x030700A2 && !defined(PyThread_tss_create) && !defined(Py_tss_NEEDS_INIT) -#include "pythread.h" -#define Py_tss_NEEDS_INIT 0 -typedef int Py_tss_t; -static CYTHON_INLINE int PyThread_tss_create(Py_tss_t *key) { - *key = PyThread_create_key(); - return 0; -} -static CYTHON_INLINE Py_tss_t * PyThread_tss_alloc(void) { - Py_tss_t *key = (Py_tss_t *)PyObject_Malloc(sizeof(Py_tss_t)); - *key = Py_tss_NEEDS_INIT; - return key; -} -static CYTHON_INLINE void PyThread_tss_free(Py_tss_t *key) { - PyObject_Free(key); -} -static CYTHON_INLINE int PyThread_tss_is_created(Py_tss_t *key) { - return *key != Py_tss_NEEDS_INIT; -} -static CYTHON_INLINE void PyThread_tss_delete(Py_tss_t *key) { - PyThread_delete_key(*key); - *key = Py_tss_NEEDS_INIT; -} -static CYTHON_INLINE int PyThread_tss_set(Py_tss_t *key, void *value) { - return PyThread_set_key_value(*key, value); -} -static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) { - return PyThread_get_key_value(*key); -} -#endif -#if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) -#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) -#else -#define __Pyx_PyDict_NewPresized(n) PyDict_New() -#endif -#if PY_MAJOR_VERSION >= 3 || CYTHON_FUTURE_DIVISION - #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) -#else - #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) -#endif -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 && CYTHON_USE_UNICODE_INTERNALS -#define __Pyx_PyDict_GetItemStr(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) -#else -#define __Pyx_PyDict_GetItemStr(dict, name) PyDict_GetItem(dict, name) -#endif -#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) - #define CYTHON_PEP393_ENABLED 1 - #if defined(PyUnicode_IS_READY) - #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ - 0 : _PyUnicode_Ready((PyObject *)(op))) - #else - #define __Pyx_PyUnicode_READY(op) (0) - #endif - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) - #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) - #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) - #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) - #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) - #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) - #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch) - #if defined(PyUnicode_IS_READY) && defined(PyUnicode_GET_SIZE) - #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03090000 - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : ((PyCompactUnicodeObject *)(u))->wstr_length)) - #else - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) - #endif - #else - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) - #endif -#else - #define CYTHON_PEP393_ENABLED 0 - #define PyUnicode_1BYTE_KIND 1 - #define PyUnicode_2BYTE_KIND 2 - #define PyUnicode_4BYTE_KIND 4 - #define __Pyx_PyUnicode_READY(op) (0) - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) - #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) - #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111) - #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) - #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) - #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) - #define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch) - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) -#endif -#if CYTHON_COMPILING_IN_PYPY - #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) - #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) -#else - #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) - #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ - PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains) - #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check) - #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format) - #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) -#endif -#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyString_Check(b) && !PyString_CheckExact(b)))) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) -#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) -#else - #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) -#endif -#if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII) - #define PyObject_ASCII(o) PyObject_Repr(o) -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyBaseString_Type PyUnicode_Type - #define PyStringObject PyUnicodeObject - #define PyString_Type PyUnicode_Type - #define PyString_Check PyUnicode_Check - #define PyString_CheckExact PyUnicode_CheckExact -#ifndef PyObject_Unicode - #define PyObject_Unicode PyObject_Str -#endif -#endif -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) - #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) -#else - #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) - #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) -#endif -#ifndef PySet_CheckExact - #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) -#endif -#if PY_VERSION_HEX >= 0x030900A4 - #define __Pyx_SET_REFCNT(obj, refcnt) Py_SET_REFCNT(obj, refcnt) - #define __Pyx_SET_SIZE(obj, size) Py_SET_SIZE(obj, size) -#else - #define __Pyx_SET_REFCNT(obj, refcnt) Py_REFCNT(obj) = (refcnt) - #define __Pyx_SET_SIZE(obj, size) Py_SIZE(obj) = (size) -#endif -#if CYTHON_ASSUME_SAFE_MACROS - #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) -#else - #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyIntObject PyLongObject - #define PyInt_Type PyLong_Type - #define PyInt_Check(op) PyLong_Check(op) - #define PyInt_CheckExact(op) PyLong_CheckExact(op) - #define PyInt_FromString PyLong_FromString - #define PyInt_FromUnicode PyLong_FromUnicode - #define PyInt_FromLong PyLong_FromLong - #define PyInt_FromSize_t PyLong_FromSize_t - #define PyInt_FromSsize_t PyLong_FromSsize_t - #define PyInt_AsLong PyLong_AsLong - #define PyInt_AS_LONG PyLong_AS_LONG - #define PyInt_AsSsize_t PyLong_AsSsize_t - #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask - #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask - #define PyNumber_Int PyNumber_Long -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyBoolObject PyLongObject -#endif -#if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY - #ifndef PyUnicode_InternFromString - #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) - #endif -#endif -#if PY_VERSION_HEX < 0x030200A4 - typedef long Py_hash_t; - #define __Pyx_PyInt_FromHash_t PyInt_FromLong - #define __Pyx_PyInt_AsHash_t PyInt_AsLong -#else - #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t - #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t -#endif -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyMethod_New(func, self, klass) ((self) ? ((void)(klass), PyMethod_New(func, self)) : __Pyx_NewRef(func)) -#else - #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) -#endif -#if CYTHON_USE_ASYNC_SLOTS - #if PY_VERSION_HEX >= 0x030500B1 - #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods - #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) - #else - #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) - #endif -#else - #define __Pyx_PyType_AsAsync(obj) NULL -#endif -#ifndef __Pyx_PyAsyncMethodsStruct - typedef struct { - unaryfunc am_await; - unaryfunc am_aiter; - unaryfunc am_anext; - } __Pyx_PyAsyncMethodsStruct; -#endif - -#if defined(WIN32) || defined(MS_WINDOWS) - #define _USE_MATH_DEFINES -#endif -#include -#ifdef NAN -#define __PYX_NAN() ((float) NAN) -#else -static CYTHON_INLINE float __PYX_NAN() { - float value; - memset(&value, 0xFF, sizeof(value)); - return value; -} -#endif -#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) -#define __Pyx_truncl trunc -#else -#define __Pyx_truncl truncl -#endif - -#define __PYX_MARK_ERR_POS(f_index, lineno) \ - { __pyx_filename = __pyx_f[f_index]; (void)__pyx_filename; __pyx_lineno = lineno; (void)__pyx_lineno; __pyx_clineno = __LINE__; (void)__pyx_clineno; } -#define __PYX_ERR(f_index, lineno, Ln_error) \ - { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; } - -#ifndef __PYX_EXTERN_C - #ifdef __cplusplus - #define __PYX_EXTERN_C extern "C" - #else - #define __PYX_EXTERN_C extern - #endif -#endif - -#define __PYX_HAVE__aiohttp___http_parser -#define __PYX_HAVE_API__aiohttp___http_parser -/* Early includes */ -#include -#include -#include "pythread.h" -#include -#include -#include "../vendor/llhttp/build/llhttp.h" -#include "_find_header.h" -#ifdef _OPENMP -#include -#endif /* _OPENMP */ - -#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) -#define CYTHON_WITHOUT_ASSERTIONS -#endif - -typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding; - const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; - -#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 -#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0 -#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT (PY_MAJOR_VERSION >= 3 && __PYX_DEFAULT_STRING_ENCODING_IS_UTF8) -#define __PYX_DEFAULT_STRING_ENCODING "" -#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString -#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize -#define __Pyx_uchar_cast(c) ((unsigned char)c) -#define __Pyx_long_cast(x) ((long)x) -#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ - (sizeof(type) < sizeof(Py_ssize_t)) ||\ - (sizeof(type) > sizeof(Py_ssize_t) &&\ - likely(v < (type)PY_SSIZE_T_MAX ||\ - v == (type)PY_SSIZE_T_MAX) &&\ - (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ - v == (type)PY_SSIZE_T_MIN))) ||\ - (sizeof(type) == sizeof(Py_ssize_t) &&\ - (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ - v == (type)PY_SSIZE_T_MAX))) ) -static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { - return (size_t) i < (size_t) limit; -} -#if defined (__cplusplus) && __cplusplus >= 201103L - #include - #define __Pyx_sst_abs(value) std::abs(value) -#elif SIZEOF_INT >= SIZEOF_SIZE_T - #define __Pyx_sst_abs(value) abs(value) -#elif SIZEOF_LONG >= SIZEOF_SIZE_T - #define __Pyx_sst_abs(value) labs(value) -#elif defined (_MSC_VER) - #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) -#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define __Pyx_sst_abs(value) llabs(value) -#elif defined (__GNUC__) - #define __Pyx_sst_abs(value) __builtin_llabs(value) -#else - #define __Pyx_sst_abs(value) ((value<0) ? -value : value) -#endif -static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); -static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); -#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) -#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) -#define __Pyx_PyBytes_FromString PyBytes_FromString -#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); -#if PY_MAJOR_VERSION < 3 - #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString - #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize -#else - #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString - #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize -#endif -#define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyObject_AsWritableString(s) ((char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsWritableSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) -#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) -#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) -#define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) -#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) -static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) { - const Py_UNICODE *u_end = u; - while (*u_end++) ; - return (size_t)(u_end - u - 1); -} -#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) -#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode -#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode -#define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) -#define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) -static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); -static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); -static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); -static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); -#define __Pyx_PySequence_Tuple(obj)\ - (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) -static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); -static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); -#if CYTHON_ASSUME_SAFE_MACROS -#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) -#else -#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) -#endif -#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) -#if PY_MAJOR_VERSION >= 3 -#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) -#else -#define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x)) -#endif -#define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x)) -#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII -static int __Pyx_sys_getdefaultencoding_not_ascii; -static int __Pyx_init_sys_getdefaultencoding_params(void) { - PyObject* sys; - PyObject* default_encoding = NULL; - PyObject* ascii_chars_u = NULL; - PyObject* ascii_chars_b = NULL; - const char* default_encoding_c; - sys = PyImport_ImportModule("sys"); - if (!sys) goto bad; - default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); - Py_DECREF(sys); - if (!default_encoding) goto bad; - default_encoding_c = PyBytes_AsString(default_encoding); - if (!default_encoding_c) goto bad; - if (strcmp(default_encoding_c, "ascii") == 0) { - __Pyx_sys_getdefaultencoding_not_ascii = 0; - } else { - char ascii_chars[128]; - int c; - for (c = 0; c < 128; c++) { - ascii_chars[c] = c; - } - __Pyx_sys_getdefaultencoding_not_ascii = 1; - ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); - if (!ascii_chars_u) goto bad; - ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); - if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { - PyErr_Format( - PyExc_ValueError, - "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", - default_encoding_c); - goto bad; - } - Py_DECREF(ascii_chars_u); - Py_DECREF(ascii_chars_b); - } - Py_DECREF(default_encoding); - return 0; -bad: - Py_XDECREF(default_encoding); - Py_XDECREF(ascii_chars_u); - Py_XDECREF(ascii_chars_b); - return -1; -} -#endif -#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 -#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) -#else -#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) -#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT -static char* __PYX_DEFAULT_STRING_ENCODING; -static int __Pyx_init_sys_getdefaultencoding_params(void) { - PyObject* sys; - PyObject* default_encoding = NULL; - char* default_encoding_c; - sys = PyImport_ImportModule("sys"); - if (!sys) goto bad; - default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); - Py_DECREF(sys); - if (!default_encoding) goto bad; - default_encoding_c = PyBytes_AsString(default_encoding); - if (!default_encoding_c) goto bad; - __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c) + 1); - if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; - strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); - Py_DECREF(default_encoding); - return 0; -bad: - Py_XDECREF(default_encoding); - return -1; -} -#endif -#endif - - -/* Test for GCC > 2.95 */ -#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) - #define likely(x) __builtin_expect(!!(x), 1) - #define unlikely(x) __builtin_expect(!!(x), 0) -#else /* !__GNUC__ or GCC < 2.95 */ - #define likely(x) (x) - #define unlikely(x) (x) -#endif /* __GNUC__ */ -static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } - -static PyObject *__pyx_m = NULL; -static PyObject *__pyx_d; -static PyObject *__pyx_b; -static PyObject *__pyx_cython_runtime = NULL; -static PyObject *__pyx_empty_tuple; -static PyObject *__pyx_empty_bytes; -static PyObject *__pyx_empty_unicode; -static int __pyx_lineno; -static int __pyx_clineno = 0; -static const char * __pyx_cfilenm= __FILE__; -static const char *__pyx_filename; - - -static const char *__pyx_f[] = { - "aiohttp\\_http_parser.pyx", - "stringsource", - "type.pxd", - "bool.pxd", - "complex.pxd", - "aiohttp\\_headers.pxi", -}; - -/*--- Type declarations ---*/ -struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage; -struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage; -struct __pyx_obj_7aiohttp_12_http_parser_HttpParser; -struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParser; -struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParser; -struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct____repr__; -struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr; -struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__; -struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr; -struct __pyx_opt_args_7aiohttp_12_http_parser_10HttpParser__init; - -/* "aiohttp/_http_parser.pyx":328 - * - * cdef _init( - * self, cparser.llhttp_type mode, # <<<<<<<<<<<<<< - * object protocol, object loop, int limit, - * object timer=None, - */ -struct __pyx_opt_args_7aiohttp_12_http_parser_10HttpParser__init { - int __pyx_n; - PyObject *timer; - size_t max_line_size; - size_t max_headers; - size_t max_field_size; - PyObject *payload_exception; - int response_with_body; - int read_until_eof; - int auto_decompress; -}; - -/* "aiohttp/_http_parser.pyx":110 - * - * @cython.freelist(DEFAULT_FREELIST_SIZE) - * cdef class RawRequestMessage: # <<<<<<<<<<<<<< - * cdef readonly str method - * cdef readonly str path - */ -struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage { - PyObject_HEAD - PyObject *method; - PyObject *path; - PyObject *version; - PyObject *headers; - PyObject *raw_headers; - PyObject *should_close; - PyObject *compression; - PyObject *upgrade; - PyObject *chunked; - PyObject *url; -}; - - -/* "aiohttp/_http_parser.pyx":210 - * - * @cython.freelist(DEFAULT_FREELIST_SIZE) - * cdef class RawResponseMessage: # <<<<<<<<<<<<<< - * cdef readonly object version # HttpVersion - * cdef readonly int code - */ -struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage { - PyObject_HEAD - PyObject *version; - int code; - PyObject *reason; - PyObject *headers; - PyObject *raw_headers; - PyObject *should_close; - PyObject *compression; - PyObject *upgrade; - PyObject *chunked; -}; - - -/* "aiohttp/_http_parser.pyx":272 - * - * @cython.internal - * cdef class HttpParser: # <<<<<<<<<<<<<< - * - * cdef: - */ -struct __pyx_obj_7aiohttp_12_http_parser_HttpParser { - PyObject_HEAD - struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser *__pyx_vtab; - llhttp_t *_cparser; - llhttp_settings_t *_csettings; - PyObject *_raw_name; - PyObject *_raw_value; - int _has_value; - PyObject *_protocol; - PyObject *_loop; - PyObject *_timer; - size_t _max_line_size; - size_t _max_field_size; - size_t _max_headers; - int _response_with_body; - int _read_until_eof; - int _started; - PyObject *_url; - PyObject *_buf; - PyObject *_path; - PyObject *_reason; - PyObject *_headers; - PyObject *_raw_headers; - int _upgraded; - PyObject *_messages; - PyObject *_payload; - int _payload_error; - PyObject *_payload_exception; - PyObject *_last_error; - int _auto_decompress; - int _limit; - PyObject *_content_encoding; - Py_buffer py_buf; -}; - - -/* "aiohttp/_http_parser.pyx":568 - * - * - * cdef class HttpRequestParser(HttpParser): # <<<<<<<<<<<<<< - * - * def __init__( - */ -struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParser { - struct __pyx_obj_7aiohttp_12_http_parser_HttpParser __pyx_base; -}; - - -/* "aiohttp/_http_parser.pyx":621 - * - * - * cdef class HttpResponseParser(HttpParser): # <<<<<<<<<<<<<< - * - * def __init__( - */ -struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParser { - struct __pyx_obj_7aiohttp_12_http_parser_HttpParser __pyx_base; -}; - - -/* "aiohttp/_http_parser.pyx":135 - * self.url = url - * - * def __repr__(self): # <<<<<<<<<<<<<< - * info = [] - * info.append(("method", self.method)) - */ -struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct____repr__ { - PyObject_HEAD - PyObject *__pyx_v_info; -}; - - -/* "aiohttp/_http_parser.pyx":147 - * info.append(("chunked", self.chunked)) - * info.append(("url", self.url)) - * sinfo = ', '.join(name + '=' + repr(val) for name, val in info) # <<<<<<<<<<<<<< - * return '' - * - */ -struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr { - PyObject_HEAD - struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct____repr__ *__pyx_outer_scope; - PyObject *__pyx_v_name; - PyObject *__pyx_v_val; -}; - - -/* "aiohttp/_http_parser.pyx":233 - * self.chunked = chunked - * - * def __repr__(self): # <<<<<<<<<<<<<< - * info = [] - * info.append(("version", self.version)) - */ -struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__ { - PyObject_HEAD - PyObject *__pyx_v_info; -}; - - -/* "aiohttp/_http_parser.pyx":244 - * info.append(("upgrade", self.upgrade)) - * info.append(("chunked", self.chunked)) - * sinfo = ', '.join(name + '=' + repr(val) for name, val in info) # <<<<<<<<<<<<<< - * return '' - * - */ -struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr { - PyObject_HEAD - struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__ *__pyx_outer_scope; - PyObject *__pyx_v_name; - PyObject *__pyx_v_val; -}; - - - -/* "aiohttp/_http_parser.pyx":272 - * - * @cython.internal - * cdef class HttpParser: # <<<<<<<<<<<<<< - * - * cdef: - */ - -struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser { - PyObject *(*_init)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *, enum llhttp_type, PyObject *, PyObject *, int, struct __pyx_opt_args_7aiohttp_12_http_parser_10HttpParser__init *__pyx_optional_args); - PyObject *(*_process_header)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *); - PyObject *(*_on_header_field)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *, char *, size_t); - PyObject *(*_on_header_value)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *, char *, size_t); - PyObject *(*_on_headers_complete)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *); - PyObject *(*_on_message_complete)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *); - PyObject *(*_on_chunk_header)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *); - PyObject *(*_on_chunk_complete)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *); - PyObject *(*_on_status_complete)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *); - PyObject *(*http_version)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *); -}; -static struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser *__pyx_vtabptr_7aiohttp_12_http_parser_HttpParser; -static CYTHON_INLINE PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser_http_version(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *); - - -/* "aiohttp/_http_parser.pyx":568 - * - * - * cdef class HttpRequestParser(HttpParser): # <<<<<<<<<<<<<< - * - * def __init__( - */ - -struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpRequestParser { - struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser __pyx_base; -}; -static struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpRequestParser *__pyx_vtabptr_7aiohttp_12_http_parser_HttpRequestParser; - - -/* "aiohttp/_http_parser.pyx":621 - * - * - * cdef class HttpResponseParser(HttpParser): # <<<<<<<<<<<<<< - * - * def __init__( - */ - -struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpResponseParser { - struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser __pyx_base; -}; -static struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpResponseParser *__pyx_vtabptr_7aiohttp_12_http_parser_HttpResponseParser; - -/* --- Runtime support code (head) --- */ -/* Refnanny.proto */ -#ifndef CYTHON_REFNANNY - #define CYTHON_REFNANNY 0 -#endif -#if CYTHON_REFNANNY - typedef struct { - void (*INCREF)(void*, PyObject*, int); - void (*DECREF)(void*, PyObject*, int); - void (*GOTREF)(void*, PyObject*, int); - void (*GIVEREF)(void*, PyObject*, int); - void* (*SetupContext)(const char*, int, const char*); - void (*FinishContext)(void**); - } __Pyx_RefNannyAPIStruct; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); - #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; -#ifdef WITH_THREAD - #define __Pyx_RefNannySetupContext(name, acquire_gil)\ - if (acquire_gil) {\ - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ - PyGILState_Release(__pyx_gilstate_save);\ - } else {\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ - } -#else - #define __Pyx_RefNannySetupContext(name, acquire_gil)\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) -#endif - #define __Pyx_RefNannyFinishContext()\ - __Pyx_RefNanny->FinishContext(&__pyx_refnanny) - #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) - #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) - #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) - #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) -#else - #define __Pyx_RefNannyDeclarations - #define __Pyx_RefNannySetupContext(name, acquire_gil) - #define __Pyx_RefNannyFinishContext() - #define __Pyx_INCREF(r) Py_INCREF(r) - #define __Pyx_DECREF(r) Py_DECREF(r) - #define __Pyx_GOTREF(r) - #define __Pyx_GIVEREF(r) - #define __Pyx_XINCREF(r) Py_XINCREF(r) - #define __Pyx_XDECREF(r) Py_XDECREF(r) - #define __Pyx_XGOTREF(r) - #define __Pyx_XGIVEREF(r) -#endif -#define __Pyx_XDECREF_SET(r, v) do {\ - PyObject *tmp = (PyObject *) r;\ - r = v; __Pyx_XDECREF(tmp);\ - } while (0) -#define __Pyx_DECREF_SET(r, v) do {\ - PyObject *tmp = (PyObject *) r;\ - r = v; __Pyx_DECREF(tmp);\ - } while (0) -#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) -#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) - -/* PyObjectGetAttrStr.proto */ -#if CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); -#else -#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) -#endif - -/* GetBuiltinName.proto */ -static PyObject *__Pyx_GetBuiltinName(PyObject *name); - -/* GetItemInt.proto */ -#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ - __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) :\ - (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) :\ - __Pyx_GetItemInt_Generic(o, to_py_func(i)))) -#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ - __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ - (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, - int wraparound, int boundscheck); -#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ - __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ - (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, - int wraparound, int boundscheck); -static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, - int is_list, int wraparound, int boundscheck); - -/* decode_c_string_utf16.proto */ -static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors) { - int byteorder = 0; - return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); -} -static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16LE(const char *s, Py_ssize_t size, const char *errors) { - int byteorder = -1; - return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); -} -static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16BE(const char *s, Py_ssize_t size, const char *errors) { - int byteorder = 1; - return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); -} - -/* decode_c_bytes.proto */ -static CYTHON_INLINE PyObject* __Pyx_decode_c_bytes( - const char* cstring, Py_ssize_t length, Py_ssize_t start, Py_ssize_t stop, - const char* encoding, const char* errors, - PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); - -/* decode_bytes.proto */ -static CYTHON_INLINE PyObject* __Pyx_decode_bytes( - PyObject* string, Py_ssize_t start, Py_ssize_t stop, - const char* encoding, const char* errors, - PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { - return __Pyx_decode_c_bytes( - PyBytes_AS_STRING(string), PyBytes_GET_SIZE(string), - start, stop, encoding, errors, decode_func); -} - -/* RaiseArgTupleInvalid.proto */ -static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, - Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); - -/* RaiseDoubleKeywords.proto */ -static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); - -/* ParseKeywords.proto */ -static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\ - PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\ - const char* function_name); - -/* None.proto */ -static CYTHON_INLINE void __Pyx_RaiseClosureNameError(const char *varname); - -/* RaiseTooManyValuesToUnpack.proto */ -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); - -/* RaiseNeedMoreValuesToUnpack.proto */ -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); - -/* IterFinish.proto */ -static CYTHON_INLINE int __Pyx_IterFinish(void); - -/* UnpackItemEndCheck.proto */ -static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); - -/* ListCompAppend.proto */ -#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS -static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { - PyListObject* L = (PyListObject*) list; - Py_ssize_t len = Py_SIZE(list); - if (likely(L->allocated > len)) { - Py_INCREF(x); - PyList_SET_ITEM(list, len, x); - __Pyx_SET_SIZE(list, len + 1); - return 0; - } - return PyList_Append(list, x); -} -#else -#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) -#endif - -/* ListAppend.proto */ -#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS -static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { - PyListObject* L = (PyListObject*) list; - Py_ssize_t len = Py_SIZE(list); - if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { - Py_INCREF(x); - PyList_SET_ITEM(list, len, x); - __Pyx_SET_SIZE(list, len + 1); - return 0; - } - return PyList_Append(list, x); -} -#else -#define __Pyx_PyList_Append(L,x) PyList_Append(L,x) -#endif - -/* KeywordStringCheck.proto */ -static int __Pyx_CheckKeywordStrings(PyObject *kwdict, const char* function_name, int kw_allowed); - -/* ExtTypeTest.proto */ -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); - -/* PyDictContains.proto */ -static CYTHON_INLINE int __Pyx_PyDict_ContainsTF(PyObject* item, PyObject* dict, int eq) { - int result = PyDict_Contains(dict, item); - return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); -} - -/* DictGetItem.proto */ -#if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY -static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key); -#define __Pyx_PyObject_Dict_GetItem(obj, name)\ - (likely(PyDict_CheckExact(obj)) ?\ - __Pyx_PyDict_GetItem(obj, name) : PyObject_GetItem(obj, name)) -#else -#define __Pyx_PyDict_GetItem(d, key) PyObject_GetItem(d, key) -#define __Pyx_PyObject_Dict_GetItem(obj, name) PyObject_GetItem(obj, name) -#endif - -/* PyErrExceptionMatches.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) -static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); -#else -#define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) -#endif - -/* PyThreadStateGet.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; -#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; -#define __Pyx_PyErr_Occurred() __pyx_tstate->curexc_type -#else -#define __Pyx_PyThreadState_declare -#define __Pyx_PyThreadState_assign -#define __Pyx_PyErr_Occurred() PyErr_Occurred() -#endif - -/* PyErrFetchRestore.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) -#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) -#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) -#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) -#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); -static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#if CYTHON_COMPILING_IN_CPYTHON -#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) -#else -#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) -#endif -#else -#define __Pyx_PyErr_Clear() PyErr_Clear() -#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) -#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) -#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) -#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) -#endif - -/* GetAttr.proto */ -static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); - -/* GetAttr3.proto */ -static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); - -/* PyDictVersioning.proto */ -#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS -#define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1) -#define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) -#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ - (version_var) = __PYX_GET_DICT_VERSION(dict);\ - (cache_var) = (value); -#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ - static PY_UINT64_T __pyx_dict_version = 0;\ - static PyObject *__pyx_dict_cached_value = NULL;\ - if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ - (VAR) = __pyx_dict_cached_value;\ - } else {\ - (VAR) = __pyx_dict_cached_value = (LOOKUP);\ - __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ - }\ -} -static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj); -static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj); -static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version); -#else -#define __PYX_GET_DICT_VERSION(dict) (0) -#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) -#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); -#endif - -/* GetModuleGlobalName.proto */ -#if CYTHON_USE_DICT_VERSIONS -#define __Pyx_GetModuleGlobalName(var, name) {\ - static PY_UINT64_T __pyx_dict_version = 0;\ - static PyObject *__pyx_dict_cached_value = NULL;\ - (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_d))) ?\ - (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ - __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ -} -#define __Pyx_GetModuleGlobalNameUncached(var, name) {\ - PY_UINT64_T __pyx_dict_version;\ - PyObject *__pyx_dict_cached_value;\ - (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ -} -static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); -#else -#define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) -#define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) -static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); -#endif - -/* PyFunctionFastCall.proto */ -#if CYTHON_FAST_PYCALL -#define __Pyx_PyFunction_FastCall(func, args, nargs)\ - __Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL) -#if 1 || PY_VERSION_HEX < 0x030600B1 -static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs); -#else -#define __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs) _PyFunction_FastCallDict(func, args, nargs, kwargs) -#endif -#define __Pyx_BUILD_ASSERT_EXPR(cond)\ - (sizeof(char [1 - 2*!(cond)]) - 1) -#ifndef Py_MEMBER_SIZE -#define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member) -#endif - static size_t __pyx_pyframe_localsplus_offset = 0; - #include "frameobject.h" - #define __Pxy_PyFrame_Initialize_Offsets()\ - ((void)__Pyx_BUILD_ASSERT_EXPR(sizeof(PyFrameObject) == offsetof(PyFrameObject, f_localsplus) + Py_MEMBER_SIZE(PyFrameObject, f_localsplus)),\ - (void)(__pyx_pyframe_localsplus_offset = ((size_t)PyFrame_Type.tp_basicsize) - Py_MEMBER_SIZE(PyFrameObject, f_localsplus))) - #define __Pyx_PyFrame_GetLocalsplus(frame)\ - (assert(__pyx_pyframe_localsplus_offset), (PyObject **)(((char *)(frame)) + __pyx_pyframe_localsplus_offset)) -#endif - -/* PyObjectCall.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); -#else -#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) -#endif - -/* PyObjectCallMethO.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); -#endif - -/* PyObjectCallNoArg.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); -#else -#define __Pyx_PyObject_CallNoArg(func) __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL) -#endif - -/* PyCFunctionFastCall.proto */ -#if CYTHON_FAST_PYCCALL -static CYTHON_INLINE PyObject *__Pyx_PyCFunction_FastCall(PyObject *func, PyObject **args, Py_ssize_t nargs); -#else -#define __Pyx_PyCFunction_FastCall(func, args, nargs) (assert(0), NULL) -#endif - -/* PyObjectCallOneArg.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); - -/* PyObjectCall2Args.proto */ -static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); - -/* PySequenceContains.proto */ -static CYTHON_INLINE int __Pyx_PySequence_ContainsTF(PyObject* item, PyObject* seq, int eq) { - int result = PySequence_Contains(seq, item); - return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); -} - -/* RaiseException.proto */ -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); - -/* IncludeStringH.proto */ -#include - -/* BytesEquals.proto */ -static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); - -/* UnicodeEquals.proto */ -static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); - -/* SliceObject.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice( - PyObject* obj, Py_ssize_t cstart, Py_ssize_t cstop, - PyObject** py_start, PyObject** py_stop, PyObject** py_slice, - int has_cstart, int has_cstop, int wraparound); - -/* decode_bytearray.proto */ -static CYTHON_INLINE PyObject* __Pyx_decode_bytearray( - PyObject* string, Py_ssize_t start, Py_ssize_t stop, - const char* encoding, const char* errors, - PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { - return __Pyx_decode_c_bytes( - PyByteArray_AS_STRING(string), PyByteArray_GET_SIZE(string), - start, stop, encoding, errors, decode_func); -} - -/* PyUnicode_Substring.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_Substring( - PyObject* text, Py_ssize_t start, Py_ssize_t stop); - -/* GetException.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) -static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#else -static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); -#endif - -/* SwapException.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_ExceptionSwap(type, value, tb) __Pyx__ExceptionSwap(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#else -static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); -#endif - -/* GetTopmostException.proto */ -#if CYTHON_USE_EXC_INFO_STACK -static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate); -#endif - -/* SaveResetException.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); -#else -#define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) -#define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) -#endif - -/* Import.proto */ -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); - -/* ImportFrom.proto */ -static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); - -/* HasAttr.proto */ -static CYTHON_INLINE int __Pyx_HasAttr(PyObject *, PyObject *); - -/* PyObject_GenericGetAttrNoDict.proto */ -#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 -static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name); -#else -#define __Pyx_PyObject_GenericGetAttrNoDict PyObject_GenericGetAttr -#endif - -/* PyObject_GenericGetAttr.proto */ -#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 -static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name); -#else -#define __Pyx_PyObject_GenericGetAttr PyObject_GenericGetAttr -#endif - -/* PyObjectGetAttrStrNoError.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name); - -/* SetupReduce.proto */ -static int __Pyx_setup_reduce(PyObject* type_obj); - -/* SetVTable.proto */ -static int __Pyx_SetVtable(PyObject *dict, void *vtable); - -/* TypeImport.proto */ -#ifndef __PYX_HAVE_RT_ImportType_proto -#define __PYX_HAVE_RT_ImportType_proto -enum __Pyx_ImportType_CheckSize { - __Pyx_ImportType_CheckSize_Error = 0, - __Pyx_ImportType_CheckSize_Warn = 1, - __Pyx_ImportType_CheckSize_Ignore = 2 -}; -static PyTypeObject *__Pyx_ImportType(PyObject* module, const char *module_name, const char *class_name, size_t size, enum __Pyx_ImportType_CheckSize check_size); -#endif - -/* decode_c_string.proto */ -static CYTHON_INLINE PyObject* __Pyx_decode_c_string( - const char* cstring, Py_ssize_t start, Py_ssize_t stop, - const char* encoding, const char* errors, - PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); - -/* CLineInTraceback.proto */ -#ifdef CYTHON_CLINE_IN_TRACEBACK -#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) -#else -static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); -#endif - -/* CodeObjectCache.proto */ -typedef struct { - PyCodeObject* code_object; - int code_line; -} __Pyx_CodeObjectCacheEntry; -struct __Pyx_CodeObjectCache { - int count; - int max_count; - __Pyx_CodeObjectCacheEntry* entries; -}; -static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); -static PyCodeObject *__pyx_find_code_object(int code_line); -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); - -/* AddTraceback.proto */ -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename); - -/* GCCDiagnostics.proto */ -#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) -#define __Pyx_HAS_GCC_DIAGNOSTIC -#endif - -/* CIntToPy.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); - -/* CIntFromPy.proto */ -static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); - -/* CIntFromPy.proto */ -static CYTHON_INLINE enum llhttp_method __Pyx_PyInt_As_enum__llhttp_method(PyObject *); - -/* CIntFromPy.proto */ -static CYTHON_INLINE size_t __Pyx_PyInt_As_size_t(PyObject *); - -/* CIntFromPy.proto */ -static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); - -/* CIntToPy.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_uint8_t(uint8_t value); - -/* CIntToPy.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); - -/* FastTypeChecks.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) -static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); -static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); -static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); -#else -#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) -#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) -#define __Pyx_PyErr_GivenExceptionMatches2(err, type1, type2) (PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2)) -#endif -#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) - -/* FetchCommonType.proto */ -static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type); - -/* PyObjectGetMethod.proto */ -static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method); - -/* PyObjectCallMethod1.proto */ -static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg); - -/* CoroutineBase.proto */ -typedef PyObject *(*__pyx_coroutine_body_t)(PyObject *, PyThreadState *, PyObject *); -#if CYTHON_USE_EXC_INFO_STACK -#define __Pyx_ExcInfoStruct _PyErr_StackItem -#else -typedef struct { - PyObject *exc_type; - PyObject *exc_value; - PyObject *exc_traceback; -} __Pyx_ExcInfoStruct; -#endif -typedef struct { - PyObject_HEAD - __pyx_coroutine_body_t body; - PyObject *closure; - __Pyx_ExcInfoStruct gi_exc_state; - PyObject *gi_weakreflist; - PyObject *classobj; - PyObject *yieldfrom; - PyObject *gi_name; - PyObject *gi_qualname; - PyObject *gi_modulename; - PyObject *gi_code; - PyObject *gi_frame; - int resume_label; - char is_running; -} __pyx_CoroutineObject; -static __pyx_CoroutineObject *__Pyx__Coroutine_New( - PyTypeObject *type, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, - PyObject *name, PyObject *qualname, PyObject *module_name); -static __pyx_CoroutineObject *__Pyx__Coroutine_NewInit( - __pyx_CoroutineObject *gen, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, - PyObject *name, PyObject *qualname, PyObject *module_name); -static CYTHON_INLINE void __Pyx_Coroutine_ExceptionClear(__Pyx_ExcInfoStruct *self); -static int __Pyx_Coroutine_clear(PyObject *self); -static PyObject *__Pyx_Coroutine_Send(PyObject *self, PyObject *value); -static PyObject *__Pyx_Coroutine_Close(PyObject *self); -static PyObject *__Pyx_Coroutine_Throw(PyObject *gen, PyObject *args); -#if CYTHON_USE_EXC_INFO_STACK -#define __Pyx_Coroutine_SwapException(self) -#define __Pyx_Coroutine_ResetAndClearException(self) __Pyx_Coroutine_ExceptionClear(&(self)->gi_exc_state) -#else -#define __Pyx_Coroutine_SwapException(self) {\ - __Pyx_ExceptionSwap(&(self)->gi_exc_state.exc_type, &(self)->gi_exc_state.exc_value, &(self)->gi_exc_state.exc_traceback);\ - __Pyx_Coroutine_ResetFrameBackpointer(&(self)->gi_exc_state);\ - } -#define __Pyx_Coroutine_ResetAndClearException(self) {\ - __Pyx_ExceptionReset((self)->gi_exc_state.exc_type, (self)->gi_exc_state.exc_value, (self)->gi_exc_state.exc_traceback);\ - (self)->gi_exc_state.exc_type = (self)->gi_exc_state.exc_value = (self)->gi_exc_state.exc_traceback = NULL;\ - } -#endif -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyGen_FetchStopIterationValue(pvalue)\ - __Pyx_PyGen__FetchStopIterationValue(__pyx_tstate, pvalue) -#else -#define __Pyx_PyGen_FetchStopIterationValue(pvalue)\ - __Pyx_PyGen__FetchStopIterationValue(__Pyx_PyThreadState_Current, pvalue) -#endif -static int __Pyx_PyGen__FetchStopIterationValue(PyThreadState *tstate, PyObject **pvalue); -static CYTHON_INLINE void __Pyx_Coroutine_ResetFrameBackpointer(__Pyx_ExcInfoStruct *exc_state); - -/* PatchModuleWithCoroutine.proto */ -static PyObject* __Pyx_Coroutine_patch_module(PyObject* module, const char* py_code); - -/* PatchGeneratorABC.proto */ -static int __Pyx_patch_abc(void); - -/* Generator.proto */ -#define __Pyx_Generator_USED -static PyTypeObject *__pyx_GeneratorType = 0; -#define __Pyx_Generator_CheckExact(obj) (Py_TYPE(obj) == __pyx_GeneratorType) -#define __Pyx_Generator_New(body, code, closure, name, qualname, module_name)\ - __Pyx__Coroutine_New(__pyx_GeneratorType, body, code, closure, name, qualname, module_name) -static PyObject *__Pyx_Generator_Next(PyObject *self); -static int __pyx_Generator_init(void); - -/* CheckBinaryVersion.proto */ -static int __Pyx_check_binary_version(void); - -/* InitStrings.proto */ -static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); - -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__init(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self, enum llhttp_type __pyx_v_mode, PyObject *__pyx_v_protocol, PyObject *__pyx_v_loop, int __pyx_v_limit, struct __pyx_opt_args_7aiohttp_12_http_parser_10HttpParser__init *__pyx_optional_args); /* proto*/ -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__process_header(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self); /* proto*/ -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_header_field(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self, char *__pyx_v_at, size_t __pyx_v_length); /* proto*/ -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_header_value(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self, char *__pyx_v_at, size_t __pyx_v_length); /* proto*/ -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_headers_complete(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self); /* proto*/ -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_message_complete(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self); /* proto*/ -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_chunk_header(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self); /* proto*/ -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_chunk_complete(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self); /* proto*/ -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_status_complete(CYTHON_UNUSED struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self); /* proto*/ -static CYTHON_INLINE PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser_http_version(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self); /* proto*/ -static PyObject *__pyx_f_7aiohttp_12_http_parser_17HttpRequestParser__on_status_complete(struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParser *__pyx_v_self); /* proto*/ -static PyObject *__pyx_f_7aiohttp_12_http_parser_18HttpResponseParser__on_status_complete(struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParser *__pyx_v_self); /* proto*/ - -/* Module declarations from 'cpython.version' */ - -/* Module declarations from '__builtin__' */ - -/* Module declarations from 'cpython.type' */ -static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; - -/* Module declarations from 'libc.string' */ - -/* Module declarations from 'libc.stdio' */ - -/* Module declarations from 'cpython.object' */ - -/* Module declarations from 'cpython.ref' */ - -/* Module declarations from 'cpython.exc' */ - -/* Module declarations from 'cpython.module' */ - -/* Module declarations from 'cpython.mem' */ - -/* Module declarations from 'cpython.tuple' */ - -/* Module declarations from 'cpython.list' */ - -/* Module declarations from 'cpython.sequence' */ - -/* Module declarations from 'cpython.mapping' */ - -/* Module declarations from 'cpython.iterator' */ - -/* Module declarations from 'cpython.number' */ - -/* Module declarations from 'cpython.int' */ - -/* Module declarations from '__builtin__' */ - -/* Module declarations from 'cpython.bool' */ -static PyTypeObject *__pyx_ptype_7cpython_4bool_bool = 0; - -/* Module declarations from 'cpython.long' */ - -/* Module declarations from 'cpython.float' */ - -/* Module declarations from '__builtin__' */ - -/* Module declarations from 'cpython.complex' */ -static PyTypeObject *__pyx_ptype_7cpython_7complex_complex = 0; - -/* Module declarations from 'cpython.string' */ - -/* Module declarations from 'cpython.unicode' */ - -/* Module declarations from 'cpython.dict' */ - -/* Module declarations from 'cpython.instance' */ - -/* Module declarations from 'cpython.function' */ - -/* Module declarations from 'cpython.method' */ - -/* Module declarations from 'cpython.weakref' */ - -/* Module declarations from 'cpython.getargs' */ - -/* Module declarations from 'cpython.pythread' */ - -/* Module declarations from 'cpython.pystate' */ - -/* Module declarations from 'cpython.cobject' */ - -/* Module declarations from 'cpython.oldbuffer' */ - -/* Module declarations from 'cpython.set' */ - -/* Module declarations from 'cpython.buffer' */ - -/* Module declarations from 'cpython.bytes' */ - -/* Module declarations from 'cpython.pycapsule' */ - -/* Module declarations from 'cpython' */ - -/* Module declarations from 'libc.limits' */ - -/* Module declarations from 'cython' */ - -/* Module declarations from 'aiohttp' */ - -/* Module declarations from 'libc.stdint' */ - -/* Module declarations from 'aiohttp._cparser' */ - -/* Module declarations from 'aiohttp._find_header' */ - -/* Module declarations from 'aiohttp._http_parser' */ -static PyTypeObject *__pyx_ptype_7aiohttp_12_http_parser_RawRequestMessage = 0; -static PyTypeObject *__pyx_ptype_7aiohttp_12_http_parser_RawResponseMessage = 0; -static PyTypeObject *__pyx_ptype_7aiohttp_12_http_parser_HttpParser = 0; -static PyTypeObject *__pyx_ptype_7aiohttp_12_http_parser_HttpRequestParser = 0; -static PyTypeObject *__pyx_ptype_7aiohttp_12_http_parser_HttpResponseParser = 0; -static PyTypeObject *__pyx_ptype_7aiohttp_12_http_parser___pyx_scope_struct____repr__ = 0; -static PyTypeObject *__pyx_ptype_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr = 0; -static PyTypeObject *__pyx_ptype_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__ = 0; -static PyTypeObject *__pyx_ptype_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr = 0; -static PyObject *__pyx_v_7aiohttp_12_http_parser_headers = 0; -static PyObject *__pyx_v_7aiohttp_12_http_parser_URL = 0; -static PyObject *__pyx_v_7aiohttp_12_http_parser_URL_build = 0; -static PyObject *__pyx_v_7aiohttp_12_http_parser_CIMultiDict = 0; -static PyObject *__pyx_v_7aiohttp_12_http_parser_CIMultiDictProxy = 0; -static PyObject *__pyx_v_7aiohttp_12_http_parser_HttpVersion = 0; -static PyObject *__pyx_v_7aiohttp_12_http_parser_HttpVersion10 = 0; -static PyObject *__pyx_v_7aiohttp_12_http_parser_HttpVersion11 = 0; -static PyObject *__pyx_v_7aiohttp_12_http_parser_SEC_WEBSOCKET_KEY1 = 0; -static PyObject *__pyx_v_7aiohttp_12_http_parser_CONTENT_ENCODING = 0; -static PyObject *__pyx_v_7aiohttp_12_http_parser_EMPTY_PAYLOAD = 0; -static PyObject *__pyx_v_7aiohttp_12_http_parser_StreamReader = 0; -static PyObject *__pyx_v_7aiohttp_12_http_parser_DeflateBuffer = 0; -static PyObject *__pyx_v_7aiohttp_12_http_parser__http_method = 0; -static CYTHON_INLINE PyObject *__pyx_f_7aiohttp_12_http_parser_extend(PyObject *, char const *, size_t); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_7aiohttp_12_http_parser_http_method_str(int); /*proto*/ -static CYTHON_INLINE PyObject *__pyx_f_7aiohttp_12_http_parser_find_header(PyObject *); /*proto*/ -static PyObject *__pyx_f_7aiohttp_12_http_parser__new_request_message(PyObject *, PyObject *, PyObject *, PyObject *, PyObject *, int, PyObject *, int, int, PyObject *); /*proto*/ -static PyObject *__pyx_f_7aiohttp_12_http_parser__new_response_message(PyObject *, int, PyObject *, PyObject *, PyObject *, int, PyObject *, int, int); /*proto*/ -static int __pyx_f_7aiohttp_12_http_parser_cb_on_message_begin(llhttp_t *); /*proto*/ -static int __pyx_f_7aiohttp_12_http_parser_cb_on_url(llhttp_t *, char const *, size_t); /*proto*/ -static int __pyx_f_7aiohttp_12_http_parser_cb_on_status(llhttp_t *, char const *, size_t); /*proto*/ -static int __pyx_f_7aiohttp_12_http_parser_cb_on_header_field(llhttp_t *, char const *, size_t); /*proto*/ -static int __pyx_f_7aiohttp_12_http_parser_cb_on_header_value(llhttp_t *, char const *, size_t); /*proto*/ -static int __pyx_f_7aiohttp_12_http_parser_cb_on_headers_complete(llhttp_t *); /*proto*/ -static int __pyx_f_7aiohttp_12_http_parser_cb_on_body(llhttp_t *, char const *, size_t); /*proto*/ -static int __pyx_f_7aiohttp_12_http_parser_cb_on_message_complete(llhttp_t *); /*proto*/ -static int __pyx_f_7aiohttp_12_http_parser_cb_on_chunk_header(llhttp_t *); /*proto*/ -static int __pyx_f_7aiohttp_12_http_parser_cb_on_chunk_complete(llhttp_t *); /*proto*/ -static PyObject *__pyx_f_7aiohttp_12_http_parser_parser_error_from_errno(llhttp_t *); /*proto*/ -static PyObject *__pyx_f_7aiohttp_12_http_parser___pyx_unpickle_RawRequestMessage__set_state(struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *, PyObject *); /*proto*/ -static PyObject *__pyx_f_7aiohttp_12_http_parser___pyx_unpickle_RawResponseMessage__set_state(struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *, PyObject *); /*proto*/ -#define __Pyx_MODULE_NAME "aiohttp._http_parser" -extern int __pyx_module_is_main_aiohttp___http_parser; -int __pyx_module_is_main_aiohttp___http_parser = 0; - -/* Implementation of 'aiohttp._http_parser' */ -static PyObject *__pyx_builtin_range; -static PyObject *__pyx_builtin_MemoryError; -static PyObject *__pyx_builtin_TypeError; -static PyObject *__pyx_builtin_BaseException; -static const char __pyx_k_[] = "="; -static const char __pyx_k_i[] = "i"; -static const char __pyx_k_TE[] = "TE"; -static const char __pyx_k__2[] = ", "; -static const char __pyx_k__3[] = ")>"; -static const char __pyx_k__4[] = ""; -static const char __pyx_k__7[] = "?"; -static const char __pyx_k__8[] = "#"; -static const char __pyx_k_br[] = "br"; -static const char __pyx_k_AGE[] = "AGE"; -static const char __pyx_k_URI[] = "URI"; -static const char __pyx_k_URL[] = "URL"; -static const char __pyx_k_VIA[] = "VIA"; -static const char __pyx_k_add[] = "add"; -static const char __pyx_k_all[] = "__all__"; -static const char __pyx_k_new[] = "__new__"; -static const char __pyx_k_url[] = "url"; -static const char __pyx_k_DATE[] = "DATE"; -static const char __pyx_k_ETAG[] = "ETAG"; -static const char __pyx_k_FROM[] = "FROM"; -static const char __pyx_k_HOST[] = "HOST"; -static const char __pyx_k_LINK[] = "LINK"; -static const char __pyx_k_VARY[] = "VARY"; -static const char __pyx_k_args[] = "args"; -static const char __pyx_k_code[] = "code"; -static const char __pyx_k_dict[] = "__dict__"; -static const char __pyx_k_gzip[] = "gzip"; -static const char __pyx_k_hdrs[] = "hdrs"; -static const char __pyx_k_loop[] = "loop"; -static const char __pyx_k_main[] = "__main__"; -static const char __pyx_k_name[] = "__name__"; -static const char __pyx_k_path[] = "path"; -static const char __pyx_k_send[] = "send"; -static const char __pyx_k_test[] = "__test__"; -static const char __pyx_k_yarl[] = "yarl"; -static const char __pyx_k_ALLOW[] = "ALLOW"; -static const char __pyx_k_RANGE[] = "RANGE"; -static const char __pyx_k_URL_2[] = "_URL"; -static const char __pyx_k_build[] = "build"; -static const char __pyx_k_close[] = "close"; -static const char __pyx_k_limit[] = "limit"; -static const char __pyx_k_lower[] = "lower"; -static const char __pyx_k_range[] = "range"; -static const char __pyx_k_throw[] = "throw"; -static const char __pyx_k_timer[] = "timer"; -static const char __pyx_k_ACCEPT[] = "ACCEPT"; -static const char __pyx_k_COOKIE[] = "COOKIE"; -static const char __pyx_k_DIGEST[] = "DIGEST"; -static const char __pyx_k_EXPECT[] = "EXPECT"; -static const char __pyx_k_ORIGIN[] = "ORIGIN"; -static const char __pyx_k_PRAGMA[] = "PRAGMA"; -static const char __pyx_k_SERVER[] = "SERVER"; -static const char __pyx_k_import[] = "__import__"; -static const char __pyx_k_method[] = "method"; -static const char __pyx_k_pickle[] = "pickle"; -static const char __pyx_k_reason[] = "reason"; -static const char __pyx_k_reduce[] = "__reduce__"; -static const char __pyx_k_update[] = "update"; -static const char __pyx_k_EXPIRES[] = "EXPIRES"; -static const char __pyx_k_REFERER[] = "REFERER"; -static const char __pyx_k_TRAILER[] = "TRAILER"; -static const char __pyx_k_UPGRADE[] = "UPGRADE"; -static const char __pyx_k_WARNING[] = "WARNING"; -static const char __pyx_k_aiohttp[] = "aiohttp"; -static const char __pyx_k_chunked[] = "chunked"; -static const char __pyx_k_deflate[] = "deflate"; -static const char __pyx_k_encoded[] = "encoded"; -static const char __pyx_k_genexpr[] = "genexpr"; -static const char __pyx_k_headers[] = "headers"; -static const char __pyx_k_streams[] = "streams"; -static const char __pyx_k_unknown[] = ""; -static const char __pyx_k_upgrade[] = "upgrade"; -static const char __pyx_k_version[] = "version"; -static const char __pyx_k_IF_MATCH[] = "IF_MATCH"; -static const char __pyx_k_IF_RANGE[] = "IF_RANGE"; -static const char __pyx_k_LOCATION[] = "LOCATION"; -static const char __pyx_k_feed_eof[] = "feed_eof"; -static const char __pyx_k_fragment[] = "fragment"; -static const char __pyx_k_getstate[] = "__getstate__"; -static const char __pyx_k_protocol[] = "protocol"; -static const char __pyx_k_pyx_type[] = "__pyx_type"; -static const char __pyx_k_setstate[] = "__setstate__"; -static const char __pyx_k_FORWARDED[] = "FORWARDED"; -static const char __pyx_k_TypeError[] = "TypeError"; -static const char __pyx_k_feed_data[] = "feed_data"; -static const char __pyx_k_multidict[] = "multidict"; -static const char __pyx_k_pyx_state[] = "__pyx_state"; -static const char __pyx_k_reduce_ex[] = "__reduce_ex__"; -static const char __pyx_k_CONNECTION[] = "CONNECTION"; -static const char __pyx_k_KEEP_ALIVE[] = "KEEP_ALIVE"; -static const char __pyx_k_SET_COOKIE[] = "SET_COOKIE"; -static const char __pyx_k_USER_AGENT[] = "USER_AGENT"; -static const char __pyx_k_pyx_result[] = "__pyx_result"; -static const char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; -static const char __pyx_k_CIMultiDict[] = "CIMultiDict"; -static const char __pyx_k_CONTENT_MD5[] = "CONTENT_MD5"; -static const char __pyx_k_DESTINATION[] = "DESTINATION"; -static const char __pyx_k_HttpVersion[] = "HttpVersion"; -static const char __pyx_k_LineTooLong[] = "LineTooLong"; -static const char __pyx_k_MemoryError[] = "MemoryError"; -static const char __pyx_k_PickleError[] = "PickleError"; -static const char __pyx_k_RETRY_AFTER[] = "RETRY_AFTER"; -static const char __pyx_k_WANT_DIGEST[] = "WANT_DIGEST"; -static const char __pyx_k_compression[] = "compression"; -static const char __pyx_k_http_parser[] = "http_parser"; -static const char __pyx_k_http_writer[] = "http_writer"; -static const char __pyx_k_max_headers[] = "max_headers"; -static const char __pyx_k_raw_headers[] = "raw_headers"; -static const char __pyx_k_CONTENT_TYPE[] = "CONTENT_TYPE"; -static const char __pyx_k_MAX_FORWARDS[] = "MAX_FORWARDS"; -static const char __pyx_k_StreamReader[] = "StreamReader"; -static const char __pyx_k_pyx_checksum[] = "__pyx_checksum"; -static const char __pyx_k_query_string[] = "query_string"; -static const char __pyx_k_should_close[] = "should_close"; -static const char __pyx_k_stringsource[] = "stringsource"; -static const char __pyx_k_ACCEPT_RANGES[] = "ACCEPT_RANGES"; -static const char __pyx_k_AUTHORIZATION[] = "AUTHORIZATION"; -static const char __pyx_k_BadStatusLine[] = "BadStatusLine"; -static const char __pyx_k_BaseException[] = "BaseException"; -static const char __pyx_k_CACHE_CONTROL[] = "CACHE_CONTROL"; -static const char __pyx_k_CIMultiDict_2[] = "_CIMultiDict"; -static const char __pyx_k_CONTENT_RANGE[] = "CONTENT_RANGE"; -static const char __pyx_k_DeflateBuffer[] = "DeflateBuffer"; -static const char __pyx_k_EMPTY_PAYLOAD[] = "EMPTY_PAYLOAD"; -static const char __pyx_k_HttpVersion10[] = "HttpVersion10"; -static const char __pyx_k_HttpVersion11[] = "HttpVersion11"; -static const char __pyx_k_HttpVersion_2[] = "_HttpVersion"; -static const char __pyx_k_IF_NONE_MATCH[] = "IF_NONE_MATCH"; -static const char __pyx_k_InvalidHeader[] = "InvalidHeader"; -static const char __pyx_k_LAST_EVENT_ID[] = "LAST_EVENT_ID"; -static const char __pyx_k_LAST_MODIFIED[] = "LAST_MODIFIED"; -static const char __pyx_k_max_line_size[] = "max_line_size"; -static const char __pyx_k_reduce_cython[] = "__reduce_cython__"; -static const char __pyx_k_set_exception[] = "set_exception"; -static const char __pyx_k_ACCEPT_CHARSET[] = "ACCEPT_CHARSET"; -static const char __pyx_k_BadHttpMessage[] = "BadHttpMessage"; -static const char __pyx_k_CONTENT_LENGTH[] = "CONTENT_LENGTH"; -static const char __pyx_k_StreamReader_2[] = "_StreamReader"; -static const char __pyx_k_max_field_size[] = "max_field_size"; -static const char __pyx_k_read_until_eof[] = "read_until_eof"; -static const char __pyx_k_ACCEPT_ENCODING[] = "ACCEPT_ENCODING"; -static const char __pyx_k_ACCEPT_LANGUAGE[] = "ACCEPT_LANGUAGE"; -static const char __pyx_k_DeflateBuffer_2[] = "_DeflateBuffer"; -static const char __pyx_k_EMPTY_PAYLOAD_2[] = "_EMPTY_PAYLOAD"; -static const char __pyx_k_HttpVersion10_2[] = "_HttpVersion10"; -static const char __pyx_k_HttpVersion11_2[] = "_HttpVersion11"; -static const char __pyx_k_InvalidURLError[] = "InvalidURLError"; -static const char __pyx_k_X_FORWARDED_FOR[] = "X_FORWARDED_FOR"; -static const char __pyx_k_auto_decompress[] = "auto_decompress"; -static const char __pyx_k_http_exceptions[] = "http_exceptions"; -static const char __pyx_k_pyx_PickleError[] = "__pyx_PickleError"; -static const char __pyx_k_setstate_cython[] = "__setstate_cython__"; -static const char __pyx_k_CIMultiDictProxy[] = "CIMultiDictProxy"; -static const char __pyx_k_CONTENT_ENCODING[] = "CONTENT_ENCODING"; -static const char __pyx_k_CONTENT_LANGUAGE[] = "CONTENT_LANGUAGE"; -static const char __pyx_k_CONTENT_LOCATION[] = "CONTENT_LOCATION"; -static const char __pyx_k_WWW_AUTHENTICATE[] = "WWW_AUTHENTICATE"; -static const char __pyx_k_X_FORWARDED_HOST[] = "X_FORWARDED_HOST"; -static const char __pyx_k_HttpRequestParser[] = "HttpRequestParser"; -static const char __pyx_k_IF_MODIFIED_SINCE[] = "IF_MODIFIED_SINCE"; -static const char __pyx_k_RawRequestMessage[] = "_http_method[i] - */ - -static CYTHON_INLINE PyObject *__pyx_f_7aiohttp_12_http_parser_http_method_str(int __pyx_v_i) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("http_method_str", 0); - - /* "aiohttp/_http_parser.pyx":93 - * - * cdef inline str http_method_str(int i): - * if i < METHODS_COUNT: # <<<<<<<<<<<<<< - * return _http_method[i] - * else: - */ - __pyx_t_1 = ((__pyx_v_i < 46) != 0); - if (__pyx_t_1) { - - /* "aiohttp/_http_parser.pyx":94 - * cdef inline str http_method_str(int i): - * if i < METHODS_COUNT: - * return _http_method[i] # <<<<<<<<<<<<<< - * else: - * return "" - */ - __Pyx_XDECREF(__pyx_r); - if (unlikely(__pyx_v_7aiohttp_12_http_parser__http_method == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(0, 94, __pyx_L1_error) - } - __pyx_t_2 = __Pyx_GetItemInt_List(__pyx_v_7aiohttp_12_http_parser__http_method, __pyx_v_i, int, 1, __Pyx_PyInt_From_int, 1, 1, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 94, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(((PyObject*)__pyx_t_2)); - __pyx_r = ((PyObject*)__pyx_t_2); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - goto __pyx_L0; - - /* "aiohttp/_http_parser.pyx":93 - * - * cdef inline str http_method_str(int i): - * if i < METHODS_COUNT: # <<<<<<<<<<<<<< - * return _http_method[i] - * else: - */ - } - - /* "aiohttp/_http_parser.pyx":96 - * return _http_method[i] - * else: - * return "" # <<<<<<<<<<<<<< - * - * cdef inline object find_header(bytes raw_header): - */ - /*else*/ { - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_kp_u_unknown); - __pyx_r = __pyx_kp_u_unknown; - goto __pyx_L0; - } - - /* "aiohttp/_http_parser.pyx":92 - * - * - * cdef inline str http_method_str(int i): # <<<<<<<<<<<<<< - * if i < METHODS_COUNT: - * return _http_method[i] - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("aiohttp._http_parser.http_method_str", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":98 - * return "" - * - * cdef inline object find_header(bytes raw_header): # <<<<<<<<<<<<<< - * cdef Py_ssize_t size - * cdef char *buf - */ - -static CYTHON_INLINE PyObject *__pyx_f_7aiohttp_12_http_parser_find_header(PyObject *__pyx_v_raw_header) { - Py_ssize_t __pyx_v_size; - char *__pyx_v_buf; - int __pyx_v_idx; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("find_header", 0); - - /* "aiohttp/_http_parser.pyx":102 - * cdef char *buf - * cdef int idx - * PyBytes_AsStringAndSize(raw_header, &buf, &size) # <<<<<<<<<<<<<< - * idx = _find_header.find_header(buf, size) - * if idx == -1: - */ - __pyx_t_1 = PyBytes_AsStringAndSize(__pyx_v_raw_header, (&__pyx_v_buf), (&__pyx_v_size)); if (unlikely(__pyx_t_1 == ((int)-1))) __PYX_ERR(0, 102, __pyx_L1_error) - - /* "aiohttp/_http_parser.pyx":103 - * cdef int idx - * PyBytes_AsStringAndSize(raw_header, &buf, &size) - * idx = _find_header.find_header(buf, size) # <<<<<<<<<<<<<< - * if idx == -1: - * return raw_header.decode('utf-8', 'surrogateescape') - */ - __pyx_v_idx = find_header(__pyx_v_buf, __pyx_v_size); - - /* "aiohttp/_http_parser.pyx":104 - * PyBytes_AsStringAndSize(raw_header, &buf, &size) - * idx = _find_header.find_header(buf, size) - * if idx == -1: # <<<<<<<<<<<<<< - * return raw_header.decode('utf-8', 'surrogateescape') - * return headers[idx] - */ - __pyx_t_2 = ((__pyx_v_idx == -1L) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_http_parser.pyx":105 - * idx = _find_header.find_header(buf, size) - * if idx == -1: - * return raw_header.decode('utf-8', 'surrogateescape') # <<<<<<<<<<<<<< - * return headers[idx] - * - */ - __Pyx_XDECREF(__pyx_r); - if (unlikely(__pyx_v_raw_header == Py_None)) { - PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "decode"); - __PYX_ERR(0, 105, __pyx_L1_error) - } - __pyx_t_3 = __Pyx_decode_bytes(__pyx_v_raw_header, 0, PY_SSIZE_T_MAX, NULL, ((char const *)"surrogateescape"), PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 105, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "aiohttp/_http_parser.pyx":104 - * PyBytes_AsStringAndSize(raw_header, &buf, &size) - * idx = _find_header.find_header(buf, size) - * if idx == -1: # <<<<<<<<<<<<<< - * return raw_header.decode('utf-8', 'surrogateescape') - * return headers[idx] - */ - } - - /* "aiohttp/_http_parser.pyx":106 - * if idx == -1: - * return raw_header.decode('utf-8', 'surrogateescape') - * return headers[idx] # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - if (unlikely(__pyx_v_7aiohttp_12_http_parser_headers == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(0, 106, __pyx_L1_error) - } - __pyx_t_3 = __Pyx_GetItemInt_Tuple(__pyx_v_7aiohttp_12_http_parser_headers, __pyx_v_idx, int, 1, __Pyx_PyInt_From_int, 0, 1, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 106, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "aiohttp/_http_parser.pyx":98 - * return "" - * - * cdef inline object find_header(bytes raw_header): # <<<<<<<<<<<<<< - * cdef Py_ssize_t size - * cdef char *buf - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("aiohttp._http_parser.find_header", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":122 - * cdef readonly object url # yarl.URL - * - * def __init__(self, method, path, version, headers, raw_headers, # <<<<<<<<<<<<<< - * should_close, compression, upgrade, chunked, url): - * self.method = method - */ - -/* Python wrapper */ -static int __pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_method = 0; - PyObject *__pyx_v_path = 0; - PyObject *__pyx_v_version = 0; - PyObject *__pyx_v_headers = 0; - PyObject *__pyx_v_raw_headers = 0; - PyObject *__pyx_v_should_close = 0; - PyObject *__pyx_v_compression = 0; - PyObject *__pyx_v_upgrade = 0; - PyObject *__pyx_v_chunked = 0; - PyObject *__pyx_v_url = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_method,&__pyx_n_s_path,&__pyx_n_s_version,&__pyx_n_s_headers,&__pyx_n_s_raw_headers,&__pyx_n_s_should_close,&__pyx_n_s_compression,&__pyx_n_s_upgrade,&__pyx_n_s_chunked,&__pyx_n_s_url,0}; - PyObject* values[10] = {0,0,0,0,0,0,0,0,0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); - CYTHON_FALLTHROUGH; - case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); - CYTHON_FALLTHROUGH; - case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); - CYTHON_FALLTHROUGH; - case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); - CYTHON_FALLTHROUGH; - case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); - CYTHON_FALLTHROUGH; - case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - CYTHON_FALLTHROUGH; - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - CYTHON_FALLTHROUGH; - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_method)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_path)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__init__", 1, 10, 10, 1); __PYX_ERR(0, 122, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_version)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__init__", 1, 10, 10, 2); __PYX_ERR(0, 122, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_headers)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__init__", 1, 10, 10, 3); __PYX_ERR(0, 122, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 4: - if (likely((values[4] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_raw_headers)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__init__", 1, 10, 10, 4); __PYX_ERR(0, 122, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 5: - if (likely((values[5] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_should_close)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__init__", 1, 10, 10, 5); __PYX_ERR(0, 122, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 6: - if (likely((values[6] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_compression)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__init__", 1, 10, 10, 6); __PYX_ERR(0, 122, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 7: - if (likely((values[7] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_upgrade)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__init__", 1, 10, 10, 7); __PYX_ERR(0, 122, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 8: - if (likely((values[8] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_chunked)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__init__", 1, 10, 10, 8); __PYX_ERR(0, 122, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 9: - if (likely((values[9] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_url)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__init__", 1, 10, 10, 9); __PYX_ERR(0, 122, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) __PYX_ERR(0, 122, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 10) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - values[5] = PyTuple_GET_ITEM(__pyx_args, 5); - values[6] = PyTuple_GET_ITEM(__pyx_args, 6); - values[7] = PyTuple_GET_ITEM(__pyx_args, 7); - values[8] = PyTuple_GET_ITEM(__pyx_args, 8); - values[9] = PyTuple_GET_ITEM(__pyx_args, 9); - } - __pyx_v_method = values[0]; - __pyx_v_path = values[1]; - __pyx_v_version = values[2]; - __pyx_v_headers = values[3]; - __pyx_v_raw_headers = values[4]; - __pyx_v_should_close = values[5]; - __pyx_v_compression = values[6]; - __pyx_v_upgrade = values[7]; - __pyx_v_chunked = values[8]; - __pyx_v_url = values[9]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__init__", 1, 10, 10, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 122, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._http_parser.RawRequestMessage.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage___init__(((struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *)__pyx_v_self), __pyx_v_method, __pyx_v_path, __pyx_v_version, __pyx_v_headers, __pyx_v_raw_headers, __pyx_v_should_close, __pyx_v_compression, __pyx_v_upgrade, __pyx_v_chunked, __pyx_v_url); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage___init__(struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *__pyx_v_self, PyObject *__pyx_v_method, PyObject *__pyx_v_path, PyObject *__pyx_v_version, PyObject *__pyx_v_headers, PyObject *__pyx_v_raw_headers, PyObject *__pyx_v_should_close, PyObject *__pyx_v_compression, PyObject *__pyx_v_upgrade, PyObject *__pyx_v_chunked, PyObject *__pyx_v_url) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__init__", 0); - - /* "aiohttp/_http_parser.pyx":124 - * def __init__(self, method, path, version, headers, raw_headers, - * should_close, compression, upgrade, chunked, url): - * self.method = method # <<<<<<<<<<<<<< - * self.path = path - * self.version = version - */ - if (!(likely(PyUnicode_CheckExact(__pyx_v_method))||((__pyx_v_method) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "unicode", Py_TYPE(__pyx_v_method)->tp_name), 0))) __PYX_ERR(0, 124, __pyx_L1_error) - __pyx_t_1 = __pyx_v_method; - __Pyx_INCREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v_self->method); - __Pyx_DECREF(__pyx_v_self->method); - __pyx_v_self->method = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":125 - * should_close, compression, upgrade, chunked, url): - * self.method = method - * self.path = path # <<<<<<<<<<<<<< - * self.version = version - * self.headers = headers - */ - if (!(likely(PyUnicode_CheckExact(__pyx_v_path))||((__pyx_v_path) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "unicode", Py_TYPE(__pyx_v_path)->tp_name), 0))) __PYX_ERR(0, 125, __pyx_L1_error) - __pyx_t_1 = __pyx_v_path; - __Pyx_INCREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v_self->path); - __Pyx_DECREF(__pyx_v_self->path); - __pyx_v_self->path = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":126 - * self.method = method - * self.path = path - * self.version = version # <<<<<<<<<<<<<< - * self.headers = headers - * self.raw_headers = raw_headers - */ - __Pyx_INCREF(__pyx_v_version); - __Pyx_GIVEREF(__pyx_v_version); - __Pyx_GOTREF(__pyx_v_self->version); - __Pyx_DECREF(__pyx_v_self->version); - __pyx_v_self->version = __pyx_v_version; - - /* "aiohttp/_http_parser.pyx":127 - * self.path = path - * self.version = version - * self.headers = headers # <<<<<<<<<<<<<< - * self.raw_headers = raw_headers - * self.should_close = should_close - */ - __Pyx_INCREF(__pyx_v_headers); - __Pyx_GIVEREF(__pyx_v_headers); - __Pyx_GOTREF(__pyx_v_self->headers); - __Pyx_DECREF(__pyx_v_self->headers); - __pyx_v_self->headers = __pyx_v_headers; - - /* "aiohttp/_http_parser.pyx":128 - * self.version = version - * self.headers = headers - * self.raw_headers = raw_headers # <<<<<<<<<<<<<< - * self.should_close = should_close - * self.compression = compression - */ - __Pyx_INCREF(__pyx_v_raw_headers); - __Pyx_GIVEREF(__pyx_v_raw_headers); - __Pyx_GOTREF(__pyx_v_self->raw_headers); - __Pyx_DECREF(__pyx_v_self->raw_headers); - __pyx_v_self->raw_headers = __pyx_v_raw_headers; - - /* "aiohttp/_http_parser.pyx":129 - * self.headers = headers - * self.raw_headers = raw_headers - * self.should_close = should_close # <<<<<<<<<<<<<< - * self.compression = compression - * self.upgrade = upgrade - */ - __Pyx_INCREF(__pyx_v_should_close); - __Pyx_GIVEREF(__pyx_v_should_close); - __Pyx_GOTREF(__pyx_v_self->should_close); - __Pyx_DECREF(__pyx_v_self->should_close); - __pyx_v_self->should_close = __pyx_v_should_close; - - /* "aiohttp/_http_parser.pyx":130 - * self.raw_headers = raw_headers - * self.should_close = should_close - * self.compression = compression # <<<<<<<<<<<<<< - * self.upgrade = upgrade - * self.chunked = chunked - */ - __Pyx_INCREF(__pyx_v_compression); - __Pyx_GIVEREF(__pyx_v_compression); - __Pyx_GOTREF(__pyx_v_self->compression); - __Pyx_DECREF(__pyx_v_self->compression); - __pyx_v_self->compression = __pyx_v_compression; - - /* "aiohttp/_http_parser.pyx":131 - * self.should_close = should_close - * self.compression = compression - * self.upgrade = upgrade # <<<<<<<<<<<<<< - * self.chunked = chunked - * self.url = url - */ - __Pyx_INCREF(__pyx_v_upgrade); - __Pyx_GIVEREF(__pyx_v_upgrade); - __Pyx_GOTREF(__pyx_v_self->upgrade); - __Pyx_DECREF(__pyx_v_self->upgrade); - __pyx_v_self->upgrade = __pyx_v_upgrade; - - /* "aiohttp/_http_parser.pyx":132 - * self.compression = compression - * self.upgrade = upgrade - * self.chunked = chunked # <<<<<<<<<<<<<< - * self.url = url - * - */ - __Pyx_INCREF(__pyx_v_chunked); - __Pyx_GIVEREF(__pyx_v_chunked); - __Pyx_GOTREF(__pyx_v_self->chunked); - __Pyx_DECREF(__pyx_v_self->chunked); - __pyx_v_self->chunked = __pyx_v_chunked; - - /* "aiohttp/_http_parser.pyx":133 - * self.upgrade = upgrade - * self.chunked = chunked - * self.url = url # <<<<<<<<<<<<<< - * - * def __repr__(self): - */ - __Pyx_INCREF(__pyx_v_url); - __Pyx_GIVEREF(__pyx_v_url); - __Pyx_GOTREF(__pyx_v_self->url); - __Pyx_DECREF(__pyx_v_self->url); - __pyx_v_self->url = __pyx_v_url; - - /* "aiohttp/_http_parser.pyx":122 - * cdef readonly object url # yarl.URL - * - * def __init__(self, method, path, version, headers, raw_headers, # <<<<<<<<<<<<<< - * should_close, compression, upgrade, chunked, url): - * self.method = method - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._http_parser.RawRequestMessage.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":135 - * self.url = url - * - * def __repr__(self): # <<<<<<<<<<<<<< - * info = [] - * info.append(("method", self.method)) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_3__repr__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_3__repr__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_2__repr__(((struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} -static PyObject *__pyx_gb_7aiohttp_12_http_parser_17RawRequestMessage_8__repr___2generator(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value); /* proto */ - -/* "aiohttp/_http_parser.pyx":147 - * info.append(("chunked", self.chunked)) - * info.append(("url", self.url)) - * sinfo = ', '.join(name + '=' + repr(val) for name, val in info) # <<<<<<<<<<<<<< - * return '' - * - */ - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_8__repr___genexpr(PyObject *__pyx_self) { - struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr *__pyx_cur_scope; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("genexpr", 0); - __pyx_cur_scope = (struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr *)__pyx_tp_new_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr(__pyx_ptype_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr, __pyx_empty_tuple, NULL); - if (unlikely(!__pyx_cur_scope)) { - __pyx_cur_scope = ((struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr *)Py_None); - __Pyx_INCREF(Py_None); - __PYX_ERR(0, 147, __pyx_L1_error) - } else { - __Pyx_GOTREF(__pyx_cur_scope); - } - __pyx_cur_scope->__pyx_outer_scope = (struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct____repr__ *) __pyx_self; - __Pyx_INCREF(((PyObject *)__pyx_cur_scope->__pyx_outer_scope)); - __Pyx_GIVEREF(__pyx_cur_scope->__pyx_outer_scope); - { - __pyx_CoroutineObject *gen = __Pyx_Generator_New((__pyx_coroutine_body_t) __pyx_gb_7aiohttp_12_http_parser_17RawRequestMessage_8__repr___2generator, NULL, (PyObject *) __pyx_cur_scope, __pyx_n_s_genexpr, __pyx_n_s_repr___locals_genexpr, __pyx_n_s_aiohttp__http_parser); if (unlikely(!gen)) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_DECREF(__pyx_cur_scope); - __Pyx_RefNannyFinishContext(); - return (PyObject *) gen; - } - - /* function exit code */ - __pyx_L1_error:; - __Pyx_AddTraceback("aiohttp._http_parser.RawRequestMessage.__repr__.genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_DECREF(((PyObject *)__pyx_cur_scope)); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_gb_7aiohttp_12_http_parser_17RawRequestMessage_8__repr___2generator(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value) /* generator body */ -{ - struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr *__pyx_cur_scope = ((struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr *)__pyx_generator->closure); - PyObject *__pyx_r = NULL; - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *(*__pyx_t_7)(PyObject *); - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("genexpr", 0); - switch (__pyx_generator->resume_label) { - case 0: goto __pyx_L3_first_run; - default: /* CPython raises the right error here */ - __Pyx_RefNannyFinishContext(); - return NULL; - } - __pyx_L3_first_run:; - if (unlikely(!__pyx_sent_value)) __PYX_ERR(0, 147, __pyx_L1_error) - __pyx_r = PyList_New(0); if (unlikely(!__pyx_r)) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_GOTREF(__pyx_r); - if (unlikely(!__pyx_cur_scope->__pyx_outer_scope->__pyx_v_info)) { __Pyx_RaiseClosureNameError("info"); __PYX_ERR(0, 147, __pyx_L1_error) } - if (unlikely(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_info == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - __PYX_ERR(0, 147, __pyx_L1_error) - } - __pyx_t_1 = __pyx_cur_scope->__pyx_outer_scope->__pyx_v_info; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; - for (;;) { - if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_3 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(0, 147, __pyx_L1_error) - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - #endif - if ((likely(PyTuple_CheckExact(__pyx_t_3))) || (PyList_CheckExact(__pyx_t_3))) { - PyObject* sequence = __pyx_t_3; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 2)) { - if (size > 2) __Pyx_RaiseTooManyValuesError(2); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 147, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_4 = PyList_GET_ITEM(sequence, 0); - __pyx_t_5 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(__pyx_t_5); - #else - __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - #endif - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_6 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = Py_TYPE(__pyx_t_6)->tp_iternext; - index = 0; __pyx_t_4 = __pyx_t_7(__pyx_t_6); if (unlikely(!__pyx_t_4)) goto __pyx_L6_unpacking_failed; - __Pyx_GOTREF(__pyx_t_4); - index = 1; __pyx_t_5 = __pyx_t_7(__pyx_t_6); if (unlikely(!__pyx_t_5)) goto __pyx_L6_unpacking_failed; - __Pyx_GOTREF(__pyx_t_5); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_7(__pyx_t_6), 2) < 0) __PYX_ERR(0, 147, __pyx_L1_error) - __pyx_t_7 = NULL; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - goto __pyx_L7_unpacking_done; - __pyx_L6_unpacking_failed:; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_7 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 147, __pyx_L1_error) - __pyx_L7_unpacking_done:; - } - __Pyx_XGOTREF(__pyx_cur_scope->__pyx_v_name); - __Pyx_XDECREF_SET(__pyx_cur_scope->__pyx_v_name, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __Pyx_XGOTREF(__pyx_cur_scope->__pyx_v_val); - __Pyx_XDECREF_SET(__pyx_cur_scope->__pyx_v_val, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - __pyx_t_5 = 0; - __pyx_t_3 = PyNumber_Add(__pyx_cur_scope->__pyx_v_name, __pyx_kp_u_); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_Repr(__pyx_cur_scope->__pyx_v_val); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_4 = PyNumber_Add(__pyx_t_3, __pyx_t_5); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (unlikely(__Pyx_ListComp_Append(__pyx_r, (PyObject*)__pyx_t_4))) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - CYTHON_MAYBE_UNUSED_VAR(__pyx_cur_scope); - - /* function exit code */ - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_r); __pyx_r = 0; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - #if !CYTHON_USE_EXC_INFO_STACK - __Pyx_Coroutine_ResetAndClearException(__pyx_generator); - #endif - __pyx_generator->resume_label = -1; - __Pyx_Coroutine_clear((PyObject*)__pyx_generator); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":135 - * self.url = url - * - * def __repr__(self): # <<<<<<<<<<<<<< - * info = [] - * info.append(("method", self.method)) - */ - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_2__repr__(struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *__pyx_v_self) { - struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct____repr__ *__pyx_cur_scope; - PyObject *__pyx_v_sinfo = NULL; - PyObject *__pyx_gb_7aiohttp_12_http_parser_17RawRequestMessage_8__repr___2generator = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__repr__", 0); - __pyx_cur_scope = (struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct____repr__ *)__pyx_tp_new_7aiohttp_12_http_parser___pyx_scope_struct____repr__(__pyx_ptype_7aiohttp_12_http_parser___pyx_scope_struct____repr__, __pyx_empty_tuple, NULL); - if (unlikely(!__pyx_cur_scope)) { - __pyx_cur_scope = ((struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct____repr__ *)Py_None); - __Pyx_INCREF(Py_None); - __PYX_ERR(0, 135, __pyx_L1_error) - } else { - __Pyx_GOTREF(__pyx_cur_scope); - } - - /* "aiohttp/_http_parser.pyx":136 - * - * def __repr__(self): - * info = [] # <<<<<<<<<<<<<< - * info.append(("method", self.method)) - * info.append(("path", self.path)) - */ - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 136, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_cur_scope->__pyx_v_info = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":137 - * def __repr__(self): - * info = [] - * info.append(("method", self.method)) # <<<<<<<<<<<<<< - * info.append(("path", self.path)) - * info.append(("version", self.version)) - */ - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 137, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_u_method); - __Pyx_GIVEREF(__pyx_n_u_method); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_n_u_method); - __Pyx_INCREF(__pyx_v_self->method); - __Pyx_GIVEREF(__pyx_v_self->method); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_self->method); - __pyx_t_2 = __Pyx_PyList_Append(__pyx_cur_scope->__pyx_v_info, __pyx_t_1); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(0, 137, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":138 - * info = [] - * info.append(("method", self.method)) - * info.append(("path", self.path)) # <<<<<<<<<<<<<< - * info.append(("version", self.version)) - * info.append(("headers", self.headers)) - */ - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 138, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_u_path); - __Pyx_GIVEREF(__pyx_n_u_path); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_n_u_path); - __Pyx_INCREF(__pyx_v_self->path); - __Pyx_GIVEREF(__pyx_v_self->path); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_self->path); - __pyx_t_2 = __Pyx_PyList_Append(__pyx_cur_scope->__pyx_v_info, __pyx_t_1); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(0, 138, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":139 - * info.append(("method", self.method)) - * info.append(("path", self.path)) - * info.append(("version", self.version)) # <<<<<<<<<<<<<< - * info.append(("headers", self.headers)) - * info.append(("raw_headers", self.raw_headers)) - */ - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 139, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_u_version); - __Pyx_GIVEREF(__pyx_n_u_version); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_n_u_version); - __Pyx_INCREF(__pyx_v_self->version); - __Pyx_GIVEREF(__pyx_v_self->version); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_self->version); - __pyx_t_2 = __Pyx_PyList_Append(__pyx_cur_scope->__pyx_v_info, __pyx_t_1); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(0, 139, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":140 - * info.append(("path", self.path)) - * info.append(("version", self.version)) - * info.append(("headers", self.headers)) # <<<<<<<<<<<<<< - * info.append(("raw_headers", self.raw_headers)) - * info.append(("should_close", self.should_close)) - */ - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 140, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_u_headers); - __Pyx_GIVEREF(__pyx_n_u_headers); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_n_u_headers); - __Pyx_INCREF(__pyx_v_self->headers); - __Pyx_GIVEREF(__pyx_v_self->headers); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_self->headers); - __pyx_t_2 = __Pyx_PyList_Append(__pyx_cur_scope->__pyx_v_info, __pyx_t_1); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(0, 140, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":141 - * info.append(("version", self.version)) - * info.append(("headers", self.headers)) - * info.append(("raw_headers", self.raw_headers)) # <<<<<<<<<<<<<< - * info.append(("should_close", self.should_close)) - * info.append(("compression", self.compression)) - */ - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 141, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_u_raw_headers); - __Pyx_GIVEREF(__pyx_n_u_raw_headers); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_n_u_raw_headers); - __Pyx_INCREF(__pyx_v_self->raw_headers); - __Pyx_GIVEREF(__pyx_v_self->raw_headers); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_self->raw_headers); - __pyx_t_2 = __Pyx_PyList_Append(__pyx_cur_scope->__pyx_v_info, __pyx_t_1); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(0, 141, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":142 - * info.append(("headers", self.headers)) - * info.append(("raw_headers", self.raw_headers)) - * info.append(("should_close", self.should_close)) # <<<<<<<<<<<<<< - * info.append(("compression", self.compression)) - * info.append(("upgrade", self.upgrade)) - */ - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 142, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_u_should_close); - __Pyx_GIVEREF(__pyx_n_u_should_close); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_n_u_should_close); - __Pyx_INCREF(__pyx_v_self->should_close); - __Pyx_GIVEREF(__pyx_v_self->should_close); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_self->should_close); - __pyx_t_2 = __Pyx_PyList_Append(__pyx_cur_scope->__pyx_v_info, __pyx_t_1); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(0, 142, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":143 - * info.append(("raw_headers", self.raw_headers)) - * info.append(("should_close", self.should_close)) - * info.append(("compression", self.compression)) # <<<<<<<<<<<<<< - * info.append(("upgrade", self.upgrade)) - * info.append(("chunked", self.chunked)) - */ - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 143, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_u_compression); - __Pyx_GIVEREF(__pyx_n_u_compression); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_n_u_compression); - __Pyx_INCREF(__pyx_v_self->compression); - __Pyx_GIVEREF(__pyx_v_self->compression); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_self->compression); - __pyx_t_2 = __Pyx_PyList_Append(__pyx_cur_scope->__pyx_v_info, __pyx_t_1); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(0, 143, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":144 - * info.append(("should_close", self.should_close)) - * info.append(("compression", self.compression)) - * info.append(("upgrade", self.upgrade)) # <<<<<<<<<<<<<< - * info.append(("chunked", self.chunked)) - * info.append(("url", self.url)) - */ - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 144, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_u_upgrade); - __Pyx_GIVEREF(__pyx_n_u_upgrade); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_n_u_upgrade); - __Pyx_INCREF(__pyx_v_self->upgrade); - __Pyx_GIVEREF(__pyx_v_self->upgrade); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_self->upgrade); - __pyx_t_2 = __Pyx_PyList_Append(__pyx_cur_scope->__pyx_v_info, __pyx_t_1); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(0, 144, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":145 - * info.append(("compression", self.compression)) - * info.append(("upgrade", self.upgrade)) - * info.append(("chunked", self.chunked)) # <<<<<<<<<<<<<< - * info.append(("url", self.url)) - * sinfo = ', '.join(name + '=' + repr(val) for name, val in info) - */ - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 145, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_u_chunked); - __Pyx_GIVEREF(__pyx_n_u_chunked); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_n_u_chunked); - __Pyx_INCREF(__pyx_v_self->chunked); - __Pyx_GIVEREF(__pyx_v_self->chunked); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_self->chunked); - __pyx_t_2 = __Pyx_PyList_Append(__pyx_cur_scope->__pyx_v_info, __pyx_t_1); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(0, 145, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":146 - * info.append(("upgrade", self.upgrade)) - * info.append(("chunked", self.chunked)) - * info.append(("url", self.url)) # <<<<<<<<<<<<<< - * sinfo = ', '.join(name + '=' + repr(val) for name, val in info) - * return '' - */ - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 146, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_u_url); - __Pyx_GIVEREF(__pyx_n_u_url); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_n_u_url); - __Pyx_INCREF(__pyx_v_self->url); - __Pyx_GIVEREF(__pyx_v_self->url); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_self->url); - __pyx_t_2 = __Pyx_PyList_Append(__pyx_cur_scope->__pyx_v_info, __pyx_t_1); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(0, 146, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":147 - * info.append(("chunked", self.chunked)) - * info.append(("url", self.url)) - * sinfo = ', '.join(name + '=' + repr(val) for name, val in info) # <<<<<<<<<<<<<< - * return '' - * - */ - __pyx_t_1 = __pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_8__repr___genexpr(((PyObject*)__pyx_cur_scope)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_Generator_Next(__pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyUnicode_Join(__pyx_kp_u__2, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 147, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_sinfo = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":148 - * info.append(("url", self.url)) - * sinfo = ', '.join(name + '=' + repr(val) for name, val in info) - * return '' # <<<<<<<<<<<<<< - * - * def _replace(self, **dct): - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyUnicode_ConcatSafe(__pyx_kp_u_RawRequestMessage, __pyx_v_sinfo); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyUnicode_Concat(__pyx_t_1, __pyx_kp_u__3); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 148, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "aiohttp/_http_parser.pyx":135 - * self.url = url - * - * def __repr__(self): # <<<<<<<<<<<<<< - * info = [] - * info.append(("method", self.method)) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("aiohttp._http_parser.RawRequestMessage.__repr__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_sinfo); - __Pyx_XDECREF(__pyx_gb_7aiohttp_12_http_parser_17RawRequestMessage_8__repr___2generator); - __Pyx_DECREF(((PyObject *)__pyx_cur_scope)); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":150 - * return '' - * - * def _replace(self, **dct): # <<<<<<<<<<<<<< - * cdef RawRequestMessage ret - * ret = _new_request_message(self.method, - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_5_replace(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_5_replace(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_dct = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_replace (wrapper)", 0); - if (unlikely(PyTuple_GET_SIZE(__pyx_args) > 0)) { - __Pyx_RaiseArgtupleInvalid("_replace", 1, 0, 0, PyTuple_GET_SIZE(__pyx_args)); return NULL;} - if (__pyx_kwds && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "_replace", 1))) return NULL; - __pyx_v_dct = (__pyx_kwds) ? PyDict_Copy(__pyx_kwds) : PyDict_New(); if (unlikely(!__pyx_v_dct)) return NULL; - __Pyx_GOTREF(__pyx_v_dct); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_4_replace(((struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *)__pyx_v_self), __pyx_v_dct); - - /* function exit code */ - __Pyx_XDECREF(__pyx_v_dct); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_4_replace(struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *__pyx_v_self, PyObject *__pyx_v_dct) { - struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *__pyx_v_ret = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_t_6; - PyObject *__pyx_t_7 = NULL; - int __pyx_t_8; - int __pyx_t_9; - PyObject *__pyx_t_10 = NULL; - PyObject *__pyx_t_11 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_replace", 0); - - /* "aiohttp/_http_parser.pyx":152 - * def _replace(self, **dct): - * cdef RawRequestMessage ret - * ret = _new_request_message(self.method, # <<<<<<<<<<<<<< - * self.path, - * self.version, - */ - __pyx_t_1 = __pyx_v_self->method; - __Pyx_INCREF(__pyx_t_1); - - /* "aiohttp/_http_parser.pyx":153 - * cdef RawRequestMessage ret - * ret = _new_request_message(self.method, - * self.path, # <<<<<<<<<<<<<< - * self.version, - * self.headers, - */ - __pyx_t_2 = __pyx_v_self->path; - __Pyx_INCREF(__pyx_t_2); - - /* "aiohttp/_http_parser.pyx":154 - * ret = _new_request_message(self.method, - * self.path, - * self.version, # <<<<<<<<<<<<<< - * self.headers, - * self.raw_headers, - */ - __pyx_t_3 = __pyx_v_self->version; - __Pyx_INCREF(__pyx_t_3); - - /* "aiohttp/_http_parser.pyx":155 - * self.path, - * self.version, - * self.headers, # <<<<<<<<<<<<<< - * self.raw_headers, - * self.should_close, - */ - __pyx_t_4 = __pyx_v_self->headers; - __Pyx_INCREF(__pyx_t_4); - - /* "aiohttp/_http_parser.pyx":156 - * self.version, - * self.headers, - * self.raw_headers, # <<<<<<<<<<<<<< - * self.should_close, - * self.compression, - */ - __pyx_t_5 = __pyx_v_self->raw_headers; - __Pyx_INCREF(__pyx_t_5); - - /* "aiohttp/_http_parser.pyx":157 - * self.headers, - * self.raw_headers, - * self.should_close, # <<<<<<<<<<<<<< - * self.compression, - * self.upgrade, - */ - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_self->should_close); if (unlikely((__pyx_t_6 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 157, __pyx_L1_error) - - /* "aiohttp/_http_parser.pyx":158 - * self.raw_headers, - * self.should_close, - * self.compression, # <<<<<<<<<<<<<< - * self.upgrade, - * self.chunked, - */ - __pyx_t_7 = __pyx_v_self->compression; - __Pyx_INCREF(__pyx_t_7); - - /* "aiohttp/_http_parser.pyx":159 - * self.should_close, - * self.compression, - * self.upgrade, # <<<<<<<<<<<<<< - * self.chunked, - * self.url) - */ - __pyx_t_8 = __Pyx_PyObject_IsTrue(__pyx_v_self->upgrade); if (unlikely((__pyx_t_8 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 159, __pyx_L1_error) - - /* "aiohttp/_http_parser.pyx":160 - * self.compression, - * self.upgrade, - * self.chunked, # <<<<<<<<<<<<<< - * self.url) - * if "method" in dct: - */ - __pyx_t_9 = __Pyx_PyObject_IsTrue(__pyx_v_self->chunked); if (unlikely((__pyx_t_9 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 160, __pyx_L1_error) - - /* "aiohttp/_http_parser.pyx":161 - * self.upgrade, - * self.chunked, - * self.url) # <<<<<<<<<<<<<< - * if "method" in dct: - * ret.method = dct["method"] - */ - __pyx_t_10 = __pyx_v_self->url; - __Pyx_INCREF(__pyx_t_10); - - /* "aiohttp/_http_parser.pyx":152 - * def _replace(self, **dct): - * cdef RawRequestMessage ret - * ret = _new_request_message(self.method, # <<<<<<<<<<<<<< - * self.path, - * self.version, - */ - __pyx_t_11 = __pyx_f_7aiohttp_12_http_parser__new_request_message(((PyObject*)__pyx_t_1), ((PyObject*)__pyx_t_2), __pyx_t_3, __pyx_t_4, __pyx_t_5, __pyx_t_6, __pyx_t_7, __pyx_t_8, __pyx_t_9, __pyx_t_10); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 152, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - if (!(likely(((__pyx_t_11) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_11, __pyx_ptype_7aiohttp_12_http_parser_RawRequestMessage))))) __PYX_ERR(0, 152, __pyx_L1_error) - __pyx_v_ret = ((struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *)__pyx_t_11); - __pyx_t_11 = 0; - - /* "aiohttp/_http_parser.pyx":162 - * self.chunked, - * self.url) - * if "method" in dct: # <<<<<<<<<<<<<< - * ret.method = dct["method"] - * if "path" in dct: - */ - __pyx_t_9 = (__Pyx_PyDict_ContainsTF(__pyx_n_u_method, __pyx_v_dct, Py_EQ)); if (unlikely(__pyx_t_9 < 0)) __PYX_ERR(0, 162, __pyx_L1_error) - __pyx_t_8 = (__pyx_t_9 != 0); - if (__pyx_t_8) { - - /* "aiohttp/_http_parser.pyx":163 - * self.url) - * if "method" in dct: - * ret.method = dct["method"] # <<<<<<<<<<<<<< - * if "path" in dct: - * ret.path = dct["path"] - */ - __pyx_t_11 = __Pyx_PyDict_GetItem(__pyx_v_dct, __pyx_n_u_method); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 163, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - if (!(likely(PyUnicode_CheckExact(__pyx_t_11))||((__pyx_t_11) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "unicode", Py_TYPE(__pyx_t_11)->tp_name), 0))) __PYX_ERR(0, 163, __pyx_L1_error) - __Pyx_GIVEREF(__pyx_t_11); - __Pyx_GOTREF(__pyx_v_ret->method); - __Pyx_DECREF(__pyx_v_ret->method); - __pyx_v_ret->method = ((PyObject*)__pyx_t_11); - __pyx_t_11 = 0; - - /* "aiohttp/_http_parser.pyx":162 - * self.chunked, - * self.url) - * if "method" in dct: # <<<<<<<<<<<<<< - * ret.method = dct["method"] - * if "path" in dct: - */ - } - - /* "aiohttp/_http_parser.pyx":164 - * if "method" in dct: - * ret.method = dct["method"] - * if "path" in dct: # <<<<<<<<<<<<<< - * ret.path = dct["path"] - * if "version" in dct: - */ - __pyx_t_8 = (__Pyx_PyDict_ContainsTF(__pyx_n_u_path, __pyx_v_dct, Py_EQ)); if (unlikely(__pyx_t_8 < 0)) __PYX_ERR(0, 164, __pyx_L1_error) - __pyx_t_9 = (__pyx_t_8 != 0); - if (__pyx_t_9) { - - /* "aiohttp/_http_parser.pyx":165 - * ret.method = dct["method"] - * if "path" in dct: - * ret.path = dct["path"] # <<<<<<<<<<<<<< - * if "version" in dct: - * ret.version = dct["version"] - */ - __pyx_t_11 = __Pyx_PyDict_GetItem(__pyx_v_dct, __pyx_n_u_path); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 165, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - if (!(likely(PyUnicode_CheckExact(__pyx_t_11))||((__pyx_t_11) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "unicode", Py_TYPE(__pyx_t_11)->tp_name), 0))) __PYX_ERR(0, 165, __pyx_L1_error) - __Pyx_GIVEREF(__pyx_t_11); - __Pyx_GOTREF(__pyx_v_ret->path); - __Pyx_DECREF(__pyx_v_ret->path); - __pyx_v_ret->path = ((PyObject*)__pyx_t_11); - __pyx_t_11 = 0; - - /* "aiohttp/_http_parser.pyx":164 - * if "method" in dct: - * ret.method = dct["method"] - * if "path" in dct: # <<<<<<<<<<<<<< - * ret.path = dct["path"] - * if "version" in dct: - */ - } - - /* "aiohttp/_http_parser.pyx":166 - * if "path" in dct: - * ret.path = dct["path"] - * if "version" in dct: # <<<<<<<<<<<<<< - * ret.version = dct["version"] - * if "headers" in dct: - */ - __pyx_t_9 = (__Pyx_PyDict_ContainsTF(__pyx_n_u_version, __pyx_v_dct, Py_EQ)); if (unlikely(__pyx_t_9 < 0)) __PYX_ERR(0, 166, __pyx_L1_error) - __pyx_t_8 = (__pyx_t_9 != 0); - if (__pyx_t_8) { - - /* "aiohttp/_http_parser.pyx":167 - * ret.path = dct["path"] - * if "version" in dct: - * ret.version = dct["version"] # <<<<<<<<<<<<<< - * if "headers" in dct: - * ret.headers = dct["headers"] - */ - __pyx_t_11 = __Pyx_PyDict_GetItem(__pyx_v_dct, __pyx_n_u_version); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 167, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_GIVEREF(__pyx_t_11); - __Pyx_GOTREF(__pyx_v_ret->version); - __Pyx_DECREF(__pyx_v_ret->version); - __pyx_v_ret->version = __pyx_t_11; - __pyx_t_11 = 0; - - /* "aiohttp/_http_parser.pyx":166 - * if "path" in dct: - * ret.path = dct["path"] - * if "version" in dct: # <<<<<<<<<<<<<< - * ret.version = dct["version"] - * if "headers" in dct: - */ - } - - /* "aiohttp/_http_parser.pyx":168 - * if "version" in dct: - * ret.version = dct["version"] - * if "headers" in dct: # <<<<<<<<<<<<<< - * ret.headers = dct["headers"] - * if "raw_headers" in dct: - */ - __pyx_t_8 = (__Pyx_PyDict_ContainsTF(__pyx_n_u_headers, __pyx_v_dct, Py_EQ)); if (unlikely(__pyx_t_8 < 0)) __PYX_ERR(0, 168, __pyx_L1_error) - __pyx_t_9 = (__pyx_t_8 != 0); - if (__pyx_t_9) { - - /* "aiohttp/_http_parser.pyx":169 - * ret.version = dct["version"] - * if "headers" in dct: - * ret.headers = dct["headers"] # <<<<<<<<<<<<<< - * if "raw_headers" in dct: - * ret.raw_headers = dct["raw_headers"] - */ - __pyx_t_11 = __Pyx_PyDict_GetItem(__pyx_v_dct, __pyx_n_u_headers); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 169, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_GIVEREF(__pyx_t_11); - __Pyx_GOTREF(__pyx_v_ret->headers); - __Pyx_DECREF(__pyx_v_ret->headers); - __pyx_v_ret->headers = __pyx_t_11; - __pyx_t_11 = 0; - - /* "aiohttp/_http_parser.pyx":168 - * if "version" in dct: - * ret.version = dct["version"] - * if "headers" in dct: # <<<<<<<<<<<<<< - * ret.headers = dct["headers"] - * if "raw_headers" in dct: - */ - } - - /* "aiohttp/_http_parser.pyx":170 - * if "headers" in dct: - * ret.headers = dct["headers"] - * if "raw_headers" in dct: # <<<<<<<<<<<<<< - * ret.raw_headers = dct["raw_headers"] - * if "should_close" in dct: - */ - __pyx_t_9 = (__Pyx_PyDict_ContainsTF(__pyx_n_u_raw_headers, __pyx_v_dct, Py_EQ)); if (unlikely(__pyx_t_9 < 0)) __PYX_ERR(0, 170, __pyx_L1_error) - __pyx_t_8 = (__pyx_t_9 != 0); - if (__pyx_t_8) { - - /* "aiohttp/_http_parser.pyx":171 - * ret.headers = dct["headers"] - * if "raw_headers" in dct: - * ret.raw_headers = dct["raw_headers"] # <<<<<<<<<<<<<< - * if "should_close" in dct: - * ret.should_close = dct["should_close"] - */ - __pyx_t_11 = __Pyx_PyDict_GetItem(__pyx_v_dct, __pyx_n_u_raw_headers); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 171, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_GIVEREF(__pyx_t_11); - __Pyx_GOTREF(__pyx_v_ret->raw_headers); - __Pyx_DECREF(__pyx_v_ret->raw_headers); - __pyx_v_ret->raw_headers = __pyx_t_11; - __pyx_t_11 = 0; - - /* "aiohttp/_http_parser.pyx":170 - * if "headers" in dct: - * ret.headers = dct["headers"] - * if "raw_headers" in dct: # <<<<<<<<<<<<<< - * ret.raw_headers = dct["raw_headers"] - * if "should_close" in dct: - */ - } - - /* "aiohttp/_http_parser.pyx":172 - * if "raw_headers" in dct: - * ret.raw_headers = dct["raw_headers"] - * if "should_close" in dct: # <<<<<<<<<<<<<< - * ret.should_close = dct["should_close"] - * if "compression" in dct: - */ - __pyx_t_8 = (__Pyx_PyDict_ContainsTF(__pyx_n_u_should_close, __pyx_v_dct, Py_EQ)); if (unlikely(__pyx_t_8 < 0)) __PYX_ERR(0, 172, __pyx_L1_error) - __pyx_t_9 = (__pyx_t_8 != 0); - if (__pyx_t_9) { - - /* "aiohttp/_http_parser.pyx":173 - * ret.raw_headers = dct["raw_headers"] - * if "should_close" in dct: - * ret.should_close = dct["should_close"] # <<<<<<<<<<<<<< - * if "compression" in dct: - * ret.compression = dct["compression"] - */ - __pyx_t_11 = __Pyx_PyDict_GetItem(__pyx_v_dct, __pyx_n_u_should_close); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 173, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_GIVEREF(__pyx_t_11); - __Pyx_GOTREF(__pyx_v_ret->should_close); - __Pyx_DECREF(__pyx_v_ret->should_close); - __pyx_v_ret->should_close = __pyx_t_11; - __pyx_t_11 = 0; - - /* "aiohttp/_http_parser.pyx":172 - * if "raw_headers" in dct: - * ret.raw_headers = dct["raw_headers"] - * if "should_close" in dct: # <<<<<<<<<<<<<< - * ret.should_close = dct["should_close"] - * if "compression" in dct: - */ - } - - /* "aiohttp/_http_parser.pyx":174 - * if "should_close" in dct: - * ret.should_close = dct["should_close"] - * if "compression" in dct: # <<<<<<<<<<<<<< - * ret.compression = dct["compression"] - * if "upgrade" in dct: - */ - __pyx_t_9 = (__Pyx_PyDict_ContainsTF(__pyx_n_u_compression, __pyx_v_dct, Py_EQ)); if (unlikely(__pyx_t_9 < 0)) __PYX_ERR(0, 174, __pyx_L1_error) - __pyx_t_8 = (__pyx_t_9 != 0); - if (__pyx_t_8) { - - /* "aiohttp/_http_parser.pyx":175 - * ret.should_close = dct["should_close"] - * if "compression" in dct: - * ret.compression = dct["compression"] # <<<<<<<<<<<<<< - * if "upgrade" in dct: - * ret.upgrade = dct["upgrade"] - */ - __pyx_t_11 = __Pyx_PyDict_GetItem(__pyx_v_dct, __pyx_n_u_compression); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 175, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_GIVEREF(__pyx_t_11); - __Pyx_GOTREF(__pyx_v_ret->compression); - __Pyx_DECREF(__pyx_v_ret->compression); - __pyx_v_ret->compression = __pyx_t_11; - __pyx_t_11 = 0; - - /* "aiohttp/_http_parser.pyx":174 - * if "should_close" in dct: - * ret.should_close = dct["should_close"] - * if "compression" in dct: # <<<<<<<<<<<<<< - * ret.compression = dct["compression"] - * if "upgrade" in dct: - */ - } - - /* "aiohttp/_http_parser.pyx":176 - * if "compression" in dct: - * ret.compression = dct["compression"] - * if "upgrade" in dct: # <<<<<<<<<<<<<< - * ret.upgrade = dct["upgrade"] - * if "chunked" in dct: - */ - __pyx_t_8 = (__Pyx_PyDict_ContainsTF(__pyx_n_u_upgrade, __pyx_v_dct, Py_EQ)); if (unlikely(__pyx_t_8 < 0)) __PYX_ERR(0, 176, __pyx_L1_error) - __pyx_t_9 = (__pyx_t_8 != 0); - if (__pyx_t_9) { - - /* "aiohttp/_http_parser.pyx":177 - * ret.compression = dct["compression"] - * if "upgrade" in dct: - * ret.upgrade = dct["upgrade"] # <<<<<<<<<<<<<< - * if "chunked" in dct: - * ret.chunked = dct["chunked"] - */ - __pyx_t_11 = __Pyx_PyDict_GetItem(__pyx_v_dct, __pyx_n_u_upgrade); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 177, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_GIVEREF(__pyx_t_11); - __Pyx_GOTREF(__pyx_v_ret->upgrade); - __Pyx_DECREF(__pyx_v_ret->upgrade); - __pyx_v_ret->upgrade = __pyx_t_11; - __pyx_t_11 = 0; - - /* "aiohttp/_http_parser.pyx":176 - * if "compression" in dct: - * ret.compression = dct["compression"] - * if "upgrade" in dct: # <<<<<<<<<<<<<< - * ret.upgrade = dct["upgrade"] - * if "chunked" in dct: - */ - } - - /* "aiohttp/_http_parser.pyx":178 - * if "upgrade" in dct: - * ret.upgrade = dct["upgrade"] - * if "chunked" in dct: # <<<<<<<<<<<<<< - * ret.chunked = dct["chunked"] - * if "url" in dct: - */ - __pyx_t_9 = (__Pyx_PyDict_ContainsTF(__pyx_n_u_chunked, __pyx_v_dct, Py_EQ)); if (unlikely(__pyx_t_9 < 0)) __PYX_ERR(0, 178, __pyx_L1_error) - __pyx_t_8 = (__pyx_t_9 != 0); - if (__pyx_t_8) { - - /* "aiohttp/_http_parser.pyx":179 - * ret.upgrade = dct["upgrade"] - * if "chunked" in dct: - * ret.chunked = dct["chunked"] # <<<<<<<<<<<<<< - * if "url" in dct: - * ret.url = dct["url"] - */ - __pyx_t_11 = __Pyx_PyDict_GetItem(__pyx_v_dct, __pyx_n_u_chunked); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 179, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_GIVEREF(__pyx_t_11); - __Pyx_GOTREF(__pyx_v_ret->chunked); - __Pyx_DECREF(__pyx_v_ret->chunked); - __pyx_v_ret->chunked = __pyx_t_11; - __pyx_t_11 = 0; - - /* "aiohttp/_http_parser.pyx":178 - * if "upgrade" in dct: - * ret.upgrade = dct["upgrade"] - * if "chunked" in dct: # <<<<<<<<<<<<<< - * ret.chunked = dct["chunked"] - * if "url" in dct: - */ - } - - /* "aiohttp/_http_parser.pyx":180 - * if "chunked" in dct: - * ret.chunked = dct["chunked"] - * if "url" in dct: # <<<<<<<<<<<<<< - * ret.url = dct["url"] - * return ret - */ - __pyx_t_8 = (__Pyx_PyDict_ContainsTF(__pyx_n_u_url, __pyx_v_dct, Py_EQ)); if (unlikely(__pyx_t_8 < 0)) __PYX_ERR(0, 180, __pyx_L1_error) - __pyx_t_9 = (__pyx_t_8 != 0); - if (__pyx_t_9) { - - /* "aiohttp/_http_parser.pyx":181 - * ret.chunked = dct["chunked"] - * if "url" in dct: - * ret.url = dct["url"] # <<<<<<<<<<<<<< - * return ret - * - */ - __pyx_t_11 = __Pyx_PyDict_GetItem(__pyx_v_dct, __pyx_n_u_url); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 181, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_GIVEREF(__pyx_t_11); - __Pyx_GOTREF(__pyx_v_ret->url); - __Pyx_DECREF(__pyx_v_ret->url); - __pyx_v_ret->url = __pyx_t_11; - __pyx_t_11 = 0; - - /* "aiohttp/_http_parser.pyx":180 - * if "chunked" in dct: - * ret.chunked = dct["chunked"] - * if "url" in dct: # <<<<<<<<<<<<<< - * ret.url = dct["url"] - * return ret - */ - } - - /* "aiohttp/_http_parser.pyx":182 - * if "url" in dct: - * ret.url = dct["url"] - * return ret # <<<<<<<<<<<<<< - * - * cdef _new_request_message(str method, - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_ret)); - __pyx_r = ((PyObject *)__pyx_v_ret); - goto __pyx_L0; - - /* "aiohttp/_http_parser.pyx":150 - * return '' - * - * def _replace(self, **dct): # <<<<<<<<<<<<<< - * cdef RawRequestMessage ret - * ret = _new_request_message(self.method, - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_XDECREF(__pyx_t_11); - __Pyx_AddTraceback("aiohttp._http_parser.RawRequestMessage._replace", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_ret); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":111 - * @cython.freelist(DEFAULT_FREELIST_SIZE) - * cdef class RawRequestMessage: - * cdef readonly str method # <<<<<<<<<<<<<< - * cdef readonly str path - * cdef readonly object version # HttpVersion - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_6method_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_6method_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_6method___get__(((struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_6method___get__(struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->method); - __pyx_r = __pyx_v_self->method; - goto __pyx_L0; - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":112 - * cdef class RawRequestMessage: - * cdef readonly str method - * cdef readonly str path # <<<<<<<<<<<<<< - * cdef readonly object version # HttpVersion - * cdef readonly object headers # CIMultiDict - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_4path_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_4path_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_4path___get__(((struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_4path___get__(struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->path); - __pyx_r = __pyx_v_self->path; - goto __pyx_L0; - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":113 - * cdef readonly str method - * cdef readonly str path - * cdef readonly object version # HttpVersion # <<<<<<<<<<<<<< - * cdef readonly object headers # CIMultiDict - * cdef readonly object raw_headers # tuple - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_7version_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_7version_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_7version___get__(((struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_7version___get__(struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->version); - __pyx_r = __pyx_v_self->version; - goto __pyx_L0; - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":114 - * cdef readonly str path - * cdef readonly object version # HttpVersion - * cdef readonly object headers # CIMultiDict # <<<<<<<<<<<<<< - * cdef readonly object raw_headers # tuple - * cdef readonly object should_close - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_7headers_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_7headers_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_7headers___get__(((struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_7headers___get__(struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->headers); - __pyx_r = __pyx_v_self->headers; - goto __pyx_L0; - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":115 - * cdef readonly object version # HttpVersion - * cdef readonly object headers # CIMultiDict - * cdef readonly object raw_headers # tuple # <<<<<<<<<<<<<< - * cdef readonly object should_close - * cdef readonly object compression - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_11raw_headers_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_11raw_headers_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_11raw_headers___get__(((struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_11raw_headers___get__(struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->raw_headers); - __pyx_r = __pyx_v_self->raw_headers; - goto __pyx_L0; - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":116 - * cdef readonly object headers # CIMultiDict - * cdef readonly object raw_headers # tuple - * cdef readonly object should_close # <<<<<<<<<<<<<< - * cdef readonly object compression - * cdef readonly object upgrade - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_12should_close_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_12should_close_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_12should_close___get__(((struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_12should_close___get__(struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->should_close); - __pyx_r = __pyx_v_self->should_close; - goto __pyx_L0; - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":117 - * cdef readonly object raw_headers # tuple - * cdef readonly object should_close - * cdef readonly object compression # <<<<<<<<<<<<<< - * cdef readonly object upgrade - * cdef readonly object chunked - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_11compression_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_11compression_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_11compression___get__(((struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_11compression___get__(struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->compression); - __pyx_r = __pyx_v_self->compression; - goto __pyx_L0; - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":118 - * cdef readonly object should_close - * cdef readonly object compression - * cdef readonly object upgrade # <<<<<<<<<<<<<< - * cdef readonly object chunked - * cdef readonly object url # yarl.URL - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_7upgrade_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_7upgrade_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_7upgrade___get__(((struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_7upgrade___get__(struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->upgrade); - __pyx_r = __pyx_v_self->upgrade; - goto __pyx_L0; - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":119 - * cdef readonly object compression - * cdef readonly object upgrade - * cdef readonly object chunked # <<<<<<<<<<<<<< - * cdef readonly object url # yarl.URL - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_7chunked_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_7chunked_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_7chunked___get__(((struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_7chunked___get__(struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->chunked); - __pyx_r = __pyx_v_self->chunked; - goto __pyx_L0; - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":120 - * cdef readonly object upgrade - * cdef readonly object chunked - * cdef readonly object url # yarl.URL # <<<<<<<<<<<<<< - * - * def __init__(self, method, path, version, headers, raw_headers, - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_3url_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_3url_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_3url___get__(((struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_3url___get__(struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->url); - __pyx_r = __pyx_v_self->url; - goto __pyx_L0; - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * cdef tuple state - * cdef object _dict - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_7__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_7__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_6__reduce_cython__(((struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_6__reduce_cython__(struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *__pyx_v_self) { - PyObject *__pyx_v_state = 0; - PyObject *__pyx_v__dict = 0; - int __pyx_v_use_setstate; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - PyObject *__pyx_t_6 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce_cython__", 0); - - /* "(tree fragment)":5 - * cdef object _dict - * cdef bint use_setstate - * state = (self.chunked, self.compression, self.headers, self.method, self.path, self.raw_headers, self.should_close, self.upgrade, self.url, self.version) # <<<<<<<<<<<<<< - * _dict = getattr(self, '__dict__', None) - * if _dict is not None: - */ - __pyx_t_1 = PyTuple_New(10); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_self->chunked); - __Pyx_GIVEREF(__pyx_v_self->chunked); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_self->chunked); - __Pyx_INCREF(__pyx_v_self->compression); - __Pyx_GIVEREF(__pyx_v_self->compression); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_self->compression); - __Pyx_INCREF(__pyx_v_self->headers); - __Pyx_GIVEREF(__pyx_v_self->headers); - PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_self->headers); - __Pyx_INCREF(__pyx_v_self->method); - __Pyx_GIVEREF(__pyx_v_self->method); - PyTuple_SET_ITEM(__pyx_t_1, 3, __pyx_v_self->method); - __Pyx_INCREF(__pyx_v_self->path); - __Pyx_GIVEREF(__pyx_v_self->path); - PyTuple_SET_ITEM(__pyx_t_1, 4, __pyx_v_self->path); - __Pyx_INCREF(__pyx_v_self->raw_headers); - __Pyx_GIVEREF(__pyx_v_self->raw_headers); - PyTuple_SET_ITEM(__pyx_t_1, 5, __pyx_v_self->raw_headers); - __Pyx_INCREF(__pyx_v_self->should_close); - __Pyx_GIVEREF(__pyx_v_self->should_close); - PyTuple_SET_ITEM(__pyx_t_1, 6, __pyx_v_self->should_close); - __Pyx_INCREF(__pyx_v_self->upgrade); - __Pyx_GIVEREF(__pyx_v_self->upgrade); - PyTuple_SET_ITEM(__pyx_t_1, 7, __pyx_v_self->upgrade); - __Pyx_INCREF(__pyx_v_self->url); - __Pyx_GIVEREF(__pyx_v_self->url); - PyTuple_SET_ITEM(__pyx_t_1, 8, __pyx_v_self->url); - __Pyx_INCREF(__pyx_v_self->version); - __Pyx_GIVEREF(__pyx_v_self->version); - PyTuple_SET_ITEM(__pyx_t_1, 9, __pyx_v_self->version); - __pyx_v_state = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "(tree fragment)":6 - * cdef bint use_setstate - * state = (self.chunked, self.compression, self.headers, self.method, self.path, self.raw_headers, self.should_close, self.upgrade, self.url, self.version) - * _dict = getattr(self, '__dict__', None) # <<<<<<<<<<<<<< - * if _dict is not None: - * state += (_dict,) - */ - __pyx_t_1 = __Pyx_GetAttr3(((PyObject *)__pyx_v_self), __pyx_n_s_dict, Py_None); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v__dict = __pyx_t_1; - __pyx_t_1 = 0; - - /* "(tree fragment)":7 - * state = (self.chunked, self.compression, self.headers, self.method, self.path, self.raw_headers, self.should_close, self.upgrade, self.url, self.version) - * _dict = getattr(self, '__dict__', None) - * if _dict is not None: # <<<<<<<<<<<<<< - * state += (_dict,) - * use_setstate = True - */ - __pyx_t_2 = (__pyx_v__dict != Py_None); - __pyx_t_3 = (__pyx_t_2 != 0); - if (__pyx_t_3) { - - /* "(tree fragment)":8 - * _dict = getattr(self, '__dict__', None) - * if _dict is not None: - * state += (_dict,) # <<<<<<<<<<<<<< - * use_setstate = True - * else: - */ - __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 8, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v__dict); - __Pyx_GIVEREF(__pyx_v__dict); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v__dict); - __pyx_t_4 = PyNumber_InPlaceAdd(__pyx_v_state, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 8, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF_SET(__pyx_v_state, ((PyObject*)__pyx_t_4)); - __pyx_t_4 = 0; - - /* "(tree fragment)":9 - * if _dict is not None: - * state += (_dict,) - * use_setstate = True # <<<<<<<<<<<<<< - * else: - * use_setstate = self.chunked is not None or self.compression is not None or self.headers is not None or self.method is not None or self.path is not None or self.raw_headers is not None or self.should_close is not None or self.upgrade is not None or self.url is not None or self.version is not None - */ - __pyx_v_use_setstate = 1; - - /* "(tree fragment)":7 - * state = (self.chunked, self.compression, self.headers, self.method, self.path, self.raw_headers, self.should_close, self.upgrade, self.url, self.version) - * _dict = getattr(self, '__dict__', None) - * if _dict is not None: # <<<<<<<<<<<<<< - * state += (_dict,) - * use_setstate = True - */ - goto __pyx_L3; - } - - /* "(tree fragment)":11 - * use_setstate = True - * else: - * use_setstate = self.chunked is not None or self.compression is not None or self.headers is not None or self.method is not None or self.path is not None or self.raw_headers is not None or self.should_close is not None or self.upgrade is not None or self.url is not None or self.version is not None # <<<<<<<<<<<<<< - * if use_setstate: - * return __pyx_unpickle_RawRequestMessage, (type(self), 0x1408252, None), state - */ - /*else*/ { - __pyx_t_2 = (__pyx_v_self->chunked != Py_None); - __pyx_t_5 = (__pyx_t_2 != 0); - if (!__pyx_t_5) { - } else { - __pyx_t_3 = __pyx_t_5; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_5 = (__pyx_v_self->compression != Py_None); - __pyx_t_2 = (__pyx_t_5 != 0); - if (!__pyx_t_2) { - } else { - __pyx_t_3 = __pyx_t_2; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_2 = (__pyx_v_self->headers != Py_None); - __pyx_t_5 = (__pyx_t_2 != 0); - if (!__pyx_t_5) { - } else { - __pyx_t_3 = __pyx_t_5; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_5 = (__pyx_v_self->method != ((PyObject*)Py_None)); - __pyx_t_2 = (__pyx_t_5 != 0); - if (!__pyx_t_2) { - } else { - __pyx_t_3 = __pyx_t_2; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_2 = (__pyx_v_self->path != ((PyObject*)Py_None)); - __pyx_t_5 = (__pyx_t_2 != 0); - if (!__pyx_t_5) { - } else { - __pyx_t_3 = __pyx_t_5; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_5 = (__pyx_v_self->raw_headers != Py_None); - __pyx_t_2 = (__pyx_t_5 != 0); - if (!__pyx_t_2) { - } else { - __pyx_t_3 = __pyx_t_2; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_2 = (__pyx_v_self->should_close != Py_None); - __pyx_t_5 = (__pyx_t_2 != 0); - if (!__pyx_t_5) { - } else { - __pyx_t_3 = __pyx_t_5; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_5 = (__pyx_v_self->upgrade != Py_None); - __pyx_t_2 = (__pyx_t_5 != 0); - if (!__pyx_t_2) { - } else { - __pyx_t_3 = __pyx_t_2; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_2 = (__pyx_v_self->url != Py_None); - __pyx_t_5 = (__pyx_t_2 != 0); - if (!__pyx_t_5) { - } else { - __pyx_t_3 = __pyx_t_5; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_5 = (__pyx_v_self->version != Py_None); - __pyx_t_2 = (__pyx_t_5 != 0); - __pyx_t_3 = __pyx_t_2; - __pyx_L4_bool_binop_done:; - __pyx_v_use_setstate = __pyx_t_3; - } - __pyx_L3:; - - /* "(tree fragment)":12 - * else: - * use_setstate = self.chunked is not None or self.compression is not None or self.headers is not None or self.method is not None or self.path is not None or self.raw_headers is not None or self.should_close is not None or self.upgrade is not None or self.url is not None or self.version is not None - * if use_setstate: # <<<<<<<<<<<<<< - * return __pyx_unpickle_RawRequestMessage, (type(self), 0x1408252, None), state - * else: - */ - __pyx_t_3 = (__pyx_v_use_setstate != 0); - if (__pyx_t_3) { - - /* "(tree fragment)":13 - * use_setstate = self.chunked is not None or self.compression is not None or self.headers is not None or self.method is not None or self.path is not None or self.raw_headers is not None or self.should_close is not None or self.upgrade is not None or self.url is not None or self.version is not None - * if use_setstate: - * return __pyx_unpickle_RawRequestMessage, (type(self), 0x1408252, None), state # <<<<<<<<<<<<<< - * else: - * return __pyx_unpickle_RawRequestMessage, (type(self), 0x1408252, state) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_pyx_unpickle_RawRequestMessage); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - __Pyx_INCREF(__pyx_int_21004882); - __Pyx_GIVEREF(__pyx_int_21004882); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_21004882); - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - PyTuple_SET_ITEM(__pyx_t_1, 2, Py_None); - __pyx_t_6 = PyTuple_New(3); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_1); - __Pyx_INCREF(__pyx_v_state); - __Pyx_GIVEREF(__pyx_v_state); - PyTuple_SET_ITEM(__pyx_t_6, 2, __pyx_v_state); - __pyx_t_4 = 0; - __pyx_t_1 = 0; - __pyx_r = __pyx_t_6; - __pyx_t_6 = 0; - goto __pyx_L0; - - /* "(tree fragment)":12 - * else: - * use_setstate = self.chunked is not None or self.compression is not None or self.headers is not None or self.method is not None or self.path is not None or self.raw_headers is not None or self.should_close is not None or self.upgrade is not None or self.url is not None or self.version is not None - * if use_setstate: # <<<<<<<<<<<<<< - * return __pyx_unpickle_RawRequestMessage, (type(self), 0x1408252, None), state - * else: - */ - } - - /* "(tree fragment)":15 - * return __pyx_unpickle_RawRequestMessage, (type(self), 0x1408252, None), state - * else: - * return __pyx_unpickle_RawRequestMessage, (type(self), 0x1408252, state) # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * __pyx_unpickle_RawRequestMessage__set_state(self, __pyx_state) - */ - /*else*/ { - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_n_s_pyx_unpickle_RawRequestMessage); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 15, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 15, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - __Pyx_INCREF(__pyx_int_21004882); - __Pyx_GIVEREF(__pyx_int_21004882); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_21004882); - __Pyx_INCREF(__pyx_v_state); - __Pyx_GIVEREF(__pyx_v_state); - PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_state); - __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 15, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_6); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_1); - __pyx_t_6 = 0; - __pyx_t_1 = 0; - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - } - - /* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * cdef tuple state - * cdef object _dict - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("aiohttp._http_parser.RawRequestMessage.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_state); - __Pyx_XDECREF(__pyx_v__dict); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":16 - * else: - * return __pyx_unpickle_RawRequestMessage, (type(self), 0x1408252, state) - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * __pyx_unpickle_RawRequestMessage__set_state(self, __pyx_state) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_9__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_9__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_8__setstate_cython__(((struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_17RawRequestMessage_8__setstate_cython__(struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *__pyx_v_self, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setstate_cython__", 0); - - /* "(tree fragment)":17 - * return __pyx_unpickle_RawRequestMessage, (type(self), 0x1408252, state) - * def __setstate_cython__(self, __pyx_state): - * __pyx_unpickle_RawRequestMessage__set_state(self, __pyx_state) # <<<<<<<<<<<<<< - */ - if (!(likely(PyTuple_CheckExact(__pyx_v___pyx_state))||((__pyx_v___pyx_state) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(1, 17, __pyx_L1_error) - __pyx_t_1 = __pyx_f_7aiohttp_12_http_parser___pyx_unpickle_RawRequestMessage__set_state(__pyx_v_self, ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 17, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "(tree fragment)":16 - * else: - * return __pyx_unpickle_RawRequestMessage, (type(self), 0x1408252, state) - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * __pyx_unpickle_RawRequestMessage__set_state(self, __pyx_state) - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._http_parser.RawRequestMessage.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":184 - * return ret - * - * cdef _new_request_message(str method, # <<<<<<<<<<<<<< - * str path, - * object version, - */ - -static PyObject *__pyx_f_7aiohttp_12_http_parser__new_request_message(PyObject *__pyx_v_method, PyObject *__pyx_v_path, PyObject *__pyx_v_version, PyObject *__pyx_v_headers, PyObject *__pyx_v_raw_headers, int __pyx_v_should_close, PyObject *__pyx_v_compression, int __pyx_v_upgrade, int __pyx_v_chunked, PyObject *__pyx_v_url) { - struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *__pyx_v_ret = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_new_request_message", 0); - - /* "aiohttp/_http_parser.pyx":195 - * object url): - * cdef RawRequestMessage ret - * ret = RawRequestMessage.__new__(RawRequestMessage) # <<<<<<<<<<<<<< - * ret.method = method - * ret.path = path - */ - __pyx_t_1 = ((PyObject *)__pyx_tp_new_7aiohttp_12_http_parser_RawRequestMessage(((PyTypeObject *)__pyx_ptype_7aiohttp_12_http_parser_RawRequestMessage), __pyx_empty_tuple, NULL)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 195, __pyx_L1_error) - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __pyx_v_ret = ((struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":196 - * cdef RawRequestMessage ret - * ret = RawRequestMessage.__new__(RawRequestMessage) - * ret.method = method # <<<<<<<<<<<<<< - * ret.path = path - * ret.version = version - */ - __Pyx_INCREF(__pyx_v_method); - __Pyx_GIVEREF(__pyx_v_method); - __Pyx_GOTREF(__pyx_v_ret->method); - __Pyx_DECREF(__pyx_v_ret->method); - __pyx_v_ret->method = __pyx_v_method; - - /* "aiohttp/_http_parser.pyx":197 - * ret = RawRequestMessage.__new__(RawRequestMessage) - * ret.method = method - * ret.path = path # <<<<<<<<<<<<<< - * ret.version = version - * ret.headers = headers - */ - __Pyx_INCREF(__pyx_v_path); - __Pyx_GIVEREF(__pyx_v_path); - __Pyx_GOTREF(__pyx_v_ret->path); - __Pyx_DECREF(__pyx_v_ret->path); - __pyx_v_ret->path = __pyx_v_path; - - /* "aiohttp/_http_parser.pyx":198 - * ret.method = method - * ret.path = path - * ret.version = version # <<<<<<<<<<<<<< - * ret.headers = headers - * ret.raw_headers = raw_headers - */ - __Pyx_INCREF(__pyx_v_version); - __Pyx_GIVEREF(__pyx_v_version); - __Pyx_GOTREF(__pyx_v_ret->version); - __Pyx_DECREF(__pyx_v_ret->version); - __pyx_v_ret->version = __pyx_v_version; - - /* "aiohttp/_http_parser.pyx":199 - * ret.path = path - * ret.version = version - * ret.headers = headers # <<<<<<<<<<<<<< - * ret.raw_headers = raw_headers - * ret.should_close = should_close - */ - __Pyx_INCREF(__pyx_v_headers); - __Pyx_GIVEREF(__pyx_v_headers); - __Pyx_GOTREF(__pyx_v_ret->headers); - __Pyx_DECREF(__pyx_v_ret->headers); - __pyx_v_ret->headers = __pyx_v_headers; - - /* "aiohttp/_http_parser.pyx":200 - * ret.version = version - * ret.headers = headers - * ret.raw_headers = raw_headers # <<<<<<<<<<<<<< - * ret.should_close = should_close - * ret.compression = compression - */ - __Pyx_INCREF(__pyx_v_raw_headers); - __Pyx_GIVEREF(__pyx_v_raw_headers); - __Pyx_GOTREF(__pyx_v_ret->raw_headers); - __Pyx_DECREF(__pyx_v_ret->raw_headers); - __pyx_v_ret->raw_headers = __pyx_v_raw_headers; - - /* "aiohttp/_http_parser.pyx":201 - * ret.headers = headers - * ret.raw_headers = raw_headers - * ret.should_close = should_close # <<<<<<<<<<<<<< - * ret.compression = compression - * ret.upgrade = upgrade - */ - __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_v_should_close); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 201, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v_ret->should_close); - __Pyx_DECREF(__pyx_v_ret->should_close); - __pyx_v_ret->should_close = __pyx_t_1; - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":202 - * ret.raw_headers = raw_headers - * ret.should_close = should_close - * ret.compression = compression # <<<<<<<<<<<<<< - * ret.upgrade = upgrade - * ret.chunked = chunked - */ - __Pyx_INCREF(__pyx_v_compression); - __Pyx_GIVEREF(__pyx_v_compression); - __Pyx_GOTREF(__pyx_v_ret->compression); - __Pyx_DECREF(__pyx_v_ret->compression); - __pyx_v_ret->compression = __pyx_v_compression; - - /* "aiohttp/_http_parser.pyx":203 - * ret.should_close = should_close - * ret.compression = compression - * ret.upgrade = upgrade # <<<<<<<<<<<<<< - * ret.chunked = chunked - * ret.url = url - */ - __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_v_upgrade); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 203, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v_ret->upgrade); - __Pyx_DECREF(__pyx_v_ret->upgrade); - __pyx_v_ret->upgrade = __pyx_t_1; - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":204 - * ret.compression = compression - * ret.upgrade = upgrade - * ret.chunked = chunked # <<<<<<<<<<<<<< - * ret.url = url - * return ret - */ - __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_v_chunked); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 204, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v_ret->chunked); - __Pyx_DECREF(__pyx_v_ret->chunked); - __pyx_v_ret->chunked = __pyx_t_1; - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":205 - * ret.upgrade = upgrade - * ret.chunked = chunked - * ret.url = url # <<<<<<<<<<<<<< - * return ret - * - */ - __Pyx_INCREF(__pyx_v_url); - __Pyx_GIVEREF(__pyx_v_url); - __Pyx_GOTREF(__pyx_v_ret->url); - __Pyx_DECREF(__pyx_v_ret->url); - __pyx_v_ret->url = __pyx_v_url; - - /* "aiohttp/_http_parser.pyx":206 - * ret.chunked = chunked - * ret.url = url - * return ret # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_ret)); - __pyx_r = ((PyObject *)__pyx_v_ret); - goto __pyx_L0; - - /* "aiohttp/_http_parser.pyx":184 - * return ret - * - * cdef _new_request_message(str method, # <<<<<<<<<<<<<< - * str path, - * object version, - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._http_parser._new_request_message", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_ret); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":221 - * cdef readonly object chunked - * - * def __init__(self, version, code, reason, headers, raw_headers, # <<<<<<<<<<<<<< - * should_close, compression, upgrade, chunked): - * self.version = version - */ - -/* Python wrapper */ -static int __pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_version = 0; - PyObject *__pyx_v_code = 0; - PyObject *__pyx_v_reason = 0; - PyObject *__pyx_v_headers = 0; - PyObject *__pyx_v_raw_headers = 0; - PyObject *__pyx_v_should_close = 0; - PyObject *__pyx_v_compression = 0; - PyObject *__pyx_v_upgrade = 0; - PyObject *__pyx_v_chunked = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_version,&__pyx_n_s_code,&__pyx_n_s_reason,&__pyx_n_s_headers,&__pyx_n_s_raw_headers,&__pyx_n_s_should_close,&__pyx_n_s_compression,&__pyx_n_s_upgrade,&__pyx_n_s_chunked,0}; - PyObject* values[9] = {0,0,0,0,0,0,0,0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); - CYTHON_FALLTHROUGH; - case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); - CYTHON_FALLTHROUGH; - case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); - CYTHON_FALLTHROUGH; - case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); - CYTHON_FALLTHROUGH; - case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - CYTHON_FALLTHROUGH; - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - CYTHON_FALLTHROUGH; - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_version)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_code)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__init__", 1, 9, 9, 1); __PYX_ERR(0, 221, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_reason)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__init__", 1, 9, 9, 2); __PYX_ERR(0, 221, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (likely((values[3] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_headers)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__init__", 1, 9, 9, 3); __PYX_ERR(0, 221, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 4: - if (likely((values[4] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_raw_headers)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__init__", 1, 9, 9, 4); __PYX_ERR(0, 221, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 5: - if (likely((values[5] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_should_close)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__init__", 1, 9, 9, 5); __PYX_ERR(0, 221, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 6: - if (likely((values[6] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_compression)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__init__", 1, 9, 9, 6); __PYX_ERR(0, 221, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 7: - if (likely((values[7] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_upgrade)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__init__", 1, 9, 9, 7); __PYX_ERR(0, 221, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 8: - if (likely((values[8] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_chunked)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__init__", 1, 9, 9, 8); __PYX_ERR(0, 221, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) __PYX_ERR(0, 221, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 9) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - values[5] = PyTuple_GET_ITEM(__pyx_args, 5); - values[6] = PyTuple_GET_ITEM(__pyx_args, 6); - values[7] = PyTuple_GET_ITEM(__pyx_args, 7); - values[8] = PyTuple_GET_ITEM(__pyx_args, 8); - } - __pyx_v_version = values[0]; - __pyx_v_code = values[1]; - __pyx_v_reason = values[2]; - __pyx_v_headers = values[3]; - __pyx_v_raw_headers = values[4]; - __pyx_v_should_close = values[5]; - __pyx_v_compression = values[6]; - __pyx_v_upgrade = values[7]; - __pyx_v_chunked = values[8]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__init__", 1, 9, 9, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 221, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._http_parser.RawResponseMessage.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage___init__(((struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *)__pyx_v_self), __pyx_v_version, __pyx_v_code, __pyx_v_reason, __pyx_v_headers, __pyx_v_raw_headers, __pyx_v_should_close, __pyx_v_compression, __pyx_v_upgrade, __pyx_v_chunked); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage___init__(struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *__pyx_v_self, PyObject *__pyx_v_version, PyObject *__pyx_v_code, PyObject *__pyx_v_reason, PyObject *__pyx_v_headers, PyObject *__pyx_v_raw_headers, PyObject *__pyx_v_should_close, PyObject *__pyx_v_compression, PyObject *__pyx_v_upgrade, PyObject *__pyx_v_chunked) { - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__init__", 0); - - /* "aiohttp/_http_parser.pyx":223 - * def __init__(self, version, code, reason, headers, raw_headers, - * should_close, compression, upgrade, chunked): - * self.version = version # <<<<<<<<<<<<<< - * self.code = code - * self.reason = reason - */ - __Pyx_INCREF(__pyx_v_version); - __Pyx_GIVEREF(__pyx_v_version); - __Pyx_GOTREF(__pyx_v_self->version); - __Pyx_DECREF(__pyx_v_self->version); - __pyx_v_self->version = __pyx_v_version; - - /* "aiohttp/_http_parser.pyx":224 - * should_close, compression, upgrade, chunked): - * self.version = version - * self.code = code # <<<<<<<<<<<<<< - * self.reason = reason - * self.headers = headers - */ - __pyx_t_1 = __Pyx_PyInt_As_int(__pyx_v_code); if (unlikely((__pyx_t_1 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 224, __pyx_L1_error) - __pyx_v_self->code = __pyx_t_1; - - /* "aiohttp/_http_parser.pyx":225 - * self.version = version - * self.code = code - * self.reason = reason # <<<<<<<<<<<<<< - * self.headers = headers - * self.raw_headers = raw_headers - */ - if (!(likely(PyUnicode_CheckExact(__pyx_v_reason))||((__pyx_v_reason) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "unicode", Py_TYPE(__pyx_v_reason)->tp_name), 0))) __PYX_ERR(0, 225, __pyx_L1_error) - __pyx_t_2 = __pyx_v_reason; - __Pyx_INCREF(__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __Pyx_GOTREF(__pyx_v_self->reason); - __Pyx_DECREF(__pyx_v_self->reason); - __pyx_v_self->reason = ((PyObject*)__pyx_t_2); - __pyx_t_2 = 0; - - /* "aiohttp/_http_parser.pyx":226 - * self.code = code - * self.reason = reason - * self.headers = headers # <<<<<<<<<<<<<< - * self.raw_headers = raw_headers - * self.should_close = should_close - */ - __Pyx_INCREF(__pyx_v_headers); - __Pyx_GIVEREF(__pyx_v_headers); - __Pyx_GOTREF(__pyx_v_self->headers); - __Pyx_DECREF(__pyx_v_self->headers); - __pyx_v_self->headers = __pyx_v_headers; - - /* "aiohttp/_http_parser.pyx":227 - * self.reason = reason - * self.headers = headers - * self.raw_headers = raw_headers # <<<<<<<<<<<<<< - * self.should_close = should_close - * self.compression = compression - */ - __Pyx_INCREF(__pyx_v_raw_headers); - __Pyx_GIVEREF(__pyx_v_raw_headers); - __Pyx_GOTREF(__pyx_v_self->raw_headers); - __Pyx_DECREF(__pyx_v_self->raw_headers); - __pyx_v_self->raw_headers = __pyx_v_raw_headers; - - /* "aiohttp/_http_parser.pyx":228 - * self.headers = headers - * self.raw_headers = raw_headers - * self.should_close = should_close # <<<<<<<<<<<<<< - * self.compression = compression - * self.upgrade = upgrade - */ - __Pyx_INCREF(__pyx_v_should_close); - __Pyx_GIVEREF(__pyx_v_should_close); - __Pyx_GOTREF(__pyx_v_self->should_close); - __Pyx_DECREF(__pyx_v_self->should_close); - __pyx_v_self->should_close = __pyx_v_should_close; - - /* "aiohttp/_http_parser.pyx":229 - * self.raw_headers = raw_headers - * self.should_close = should_close - * self.compression = compression # <<<<<<<<<<<<<< - * self.upgrade = upgrade - * self.chunked = chunked - */ - __Pyx_INCREF(__pyx_v_compression); - __Pyx_GIVEREF(__pyx_v_compression); - __Pyx_GOTREF(__pyx_v_self->compression); - __Pyx_DECREF(__pyx_v_self->compression); - __pyx_v_self->compression = __pyx_v_compression; - - /* "aiohttp/_http_parser.pyx":230 - * self.should_close = should_close - * self.compression = compression - * self.upgrade = upgrade # <<<<<<<<<<<<<< - * self.chunked = chunked - * - */ - __Pyx_INCREF(__pyx_v_upgrade); - __Pyx_GIVEREF(__pyx_v_upgrade); - __Pyx_GOTREF(__pyx_v_self->upgrade); - __Pyx_DECREF(__pyx_v_self->upgrade); - __pyx_v_self->upgrade = __pyx_v_upgrade; - - /* "aiohttp/_http_parser.pyx":231 - * self.compression = compression - * self.upgrade = upgrade - * self.chunked = chunked # <<<<<<<<<<<<<< - * - * def __repr__(self): - */ - __Pyx_INCREF(__pyx_v_chunked); - __Pyx_GIVEREF(__pyx_v_chunked); - __Pyx_GOTREF(__pyx_v_self->chunked); - __Pyx_DECREF(__pyx_v_self->chunked); - __pyx_v_self->chunked = __pyx_v_chunked; - - /* "aiohttp/_http_parser.pyx":221 - * cdef readonly object chunked - * - * def __init__(self, version, code, reason, headers, raw_headers, # <<<<<<<<<<<<<< - * should_close, compression, upgrade, chunked): - * self.version = version - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("aiohttp._http_parser.RawResponseMessage.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":233 - * self.chunked = chunked - * - * def __repr__(self): # <<<<<<<<<<<<<< - * info = [] - * info.append(("version", self.version)) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_3__repr__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_3__repr__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_2__repr__(((struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} -static PyObject *__pyx_gb_7aiohttp_12_http_parser_18RawResponseMessage_8__repr___2generator1(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value); /* proto */ - -/* "aiohttp/_http_parser.pyx":244 - * info.append(("upgrade", self.upgrade)) - * info.append(("chunked", self.chunked)) - * sinfo = ', '.join(name + '=' + repr(val) for name, val in info) # <<<<<<<<<<<<<< - * return '' - * - */ - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_8__repr___genexpr(PyObject *__pyx_self) { - struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr *__pyx_cur_scope; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("genexpr", 0); - __pyx_cur_scope = (struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr *)__pyx_tp_new_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr(__pyx_ptype_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr, __pyx_empty_tuple, NULL); - if (unlikely(!__pyx_cur_scope)) { - __pyx_cur_scope = ((struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr *)Py_None); - __Pyx_INCREF(Py_None); - __PYX_ERR(0, 244, __pyx_L1_error) - } else { - __Pyx_GOTREF(__pyx_cur_scope); - } - __pyx_cur_scope->__pyx_outer_scope = (struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__ *) __pyx_self; - __Pyx_INCREF(((PyObject *)__pyx_cur_scope->__pyx_outer_scope)); - __Pyx_GIVEREF(__pyx_cur_scope->__pyx_outer_scope); - { - __pyx_CoroutineObject *gen = __Pyx_Generator_New((__pyx_coroutine_body_t) __pyx_gb_7aiohttp_12_http_parser_18RawResponseMessage_8__repr___2generator1, NULL, (PyObject *) __pyx_cur_scope, __pyx_n_s_genexpr, __pyx_n_s_repr___locals_genexpr, __pyx_n_s_aiohttp__http_parser); if (unlikely(!gen)) __PYX_ERR(0, 244, __pyx_L1_error) - __Pyx_DECREF(__pyx_cur_scope); - __Pyx_RefNannyFinishContext(); - return (PyObject *) gen; - } - - /* function exit code */ - __pyx_L1_error:; - __Pyx_AddTraceback("aiohttp._http_parser.RawResponseMessage.__repr__.genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_DECREF(((PyObject *)__pyx_cur_scope)); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_gb_7aiohttp_12_http_parser_18RawResponseMessage_8__repr___2generator1(__pyx_CoroutineObject *__pyx_generator, CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject *__pyx_sent_value) /* generator body */ -{ - struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr *__pyx_cur_scope = ((struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr *)__pyx_generator->closure); - PyObject *__pyx_r = NULL; - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *(*__pyx_t_7)(PyObject *); - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("genexpr", 0); - switch (__pyx_generator->resume_label) { - case 0: goto __pyx_L3_first_run; - default: /* CPython raises the right error here */ - __Pyx_RefNannyFinishContext(); - return NULL; - } - __pyx_L3_first_run:; - if (unlikely(!__pyx_sent_value)) __PYX_ERR(0, 244, __pyx_L1_error) - __pyx_r = PyList_New(0); if (unlikely(!__pyx_r)) __PYX_ERR(0, 244, __pyx_L1_error) - __Pyx_GOTREF(__pyx_r); - if (unlikely(!__pyx_cur_scope->__pyx_outer_scope->__pyx_v_info)) { __Pyx_RaiseClosureNameError("info"); __PYX_ERR(0, 244, __pyx_L1_error) } - if (unlikely(__pyx_cur_scope->__pyx_outer_scope->__pyx_v_info == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - __PYX_ERR(0, 244, __pyx_L1_error) - } - __pyx_t_1 = __pyx_cur_scope->__pyx_outer_scope->__pyx_v_info; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; - for (;;) { - if (__pyx_t_2 >= PyList_GET_SIZE(__pyx_t_1)) break; - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - __pyx_t_3 = PyList_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(0, 244, __pyx_L1_error) - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 244, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - #endif - if ((likely(PyTuple_CheckExact(__pyx_t_3))) || (PyList_CheckExact(__pyx_t_3))) { - PyObject* sequence = __pyx_t_3; - Py_ssize_t size = __Pyx_PySequence_SIZE(sequence); - if (unlikely(size != 2)) { - if (size > 2) __Pyx_RaiseTooManyValuesError(2); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 244, __pyx_L1_error) - } - #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_4 = PyList_GET_ITEM(sequence, 0); - __pyx_t_5 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(__pyx_t_5); - #else - __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 244, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 244, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - #endif - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_6 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 244, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_7 = Py_TYPE(__pyx_t_6)->tp_iternext; - index = 0; __pyx_t_4 = __pyx_t_7(__pyx_t_6); if (unlikely(!__pyx_t_4)) goto __pyx_L6_unpacking_failed; - __Pyx_GOTREF(__pyx_t_4); - index = 1; __pyx_t_5 = __pyx_t_7(__pyx_t_6); if (unlikely(!__pyx_t_5)) goto __pyx_L6_unpacking_failed; - __Pyx_GOTREF(__pyx_t_5); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_7(__pyx_t_6), 2) < 0) __PYX_ERR(0, 244, __pyx_L1_error) - __pyx_t_7 = NULL; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - goto __pyx_L7_unpacking_done; - __pyx_L6_unpacking_failed:; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_t_7 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 244, __pyx_L1_error) - __pyx_L7_unpacking_done:; - } - __Pyx_XGOTREF(__pyx_cur_scope->__pyx_v_name); - __Pyx_XDECREF_SET(__pyx_cur_scope->__pyx_v_name, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __Pyx_XGOTREF(__pyx_cur_scope->__pyx_v_val); - __Pyx_XDECREF_SET(__pyx_cur_scope->__pyx_v_val, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_5); - __pyx_t_5 = 0; - __pyx_t_3 = PyNumber_Add(__pyx_cur_scope->__pyx_v_name, __pyx_kp_u_); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 244, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = PyObject_Repr(__pyx_cur_scope->__pyx_v_val); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 244, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_4 = PyNumber_Add(__pyx_t_3, __pyx_t_5); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 244, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (unlikely(__Pyx_ListComp_Append(__pyx_r, (PyObject*)__pyx_t_4))) __PYX_ERR(0, 244, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - CYTHON_MAYBE_UNUSED_VAR(__pyx_cur_scope); - - /* function exit code */ - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_r); __pyx_r = 0; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - #if !CYTHON_USE_EXC_INFO_STACK - __Pyx_Coroutine_ResetAndClearException(__pyx_generator); - #endif - __pyx_generator->resume_label = -1; - __Pyx_Coroutine_clear((PyObject*)__pyx_generator); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":233 - * self.chunked = chunked - * - * def __repr__(self): # <<<<<<<<<<<<<< - * info = [] - * info.append(("version", self.version)) - */ - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_2__repr__(struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *__pyx_v_self) { - struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__ *__pyx_cur_scope; - PyObject *__pyx_v_sinfo = NULL; - PyObject *__pyx_gb_7aiohttp_12_http_parser_18RawResponseMessage_8__repr___2generator1 = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__repr__", 0); - __pyx_cur_scope = (struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__ *)__pyx_tp_new_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__(__pyx_ptype_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__, __pyx_empty_tuple, NULL); - if (unlikely(!__pyx_cur_scope)) { - __pyx_cur_scope = ((struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__ *)Py_None); - __Pyx_INCREF(Py_None); - __PYX_ERR(0, 233, __pyx_L1_error) - } else { - __Pyx_GOTREF(__pyx_cur_scope); - } - - /* "aiohttp/_http_parser.pyx":234 - * - * def __repr__(self): - * info = [] # <<<<<<<<<<<<<< - * info.append(("version", self.version)) - * info.append(("code", self.code)) - */ - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 234, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_cur_scope->__pyx_v_info = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":235 - * def __repr__(self): - * info = [] - * info.append(("version", self.version)) # <<<<<<<<<<<<<< - * info.append(("code", self.code)) - * info.append(("reason", self.reason)) - */ - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 235, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_u_version); - __Pyx_GIVEREF(__pyx_n_u_version); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_n_u_version); - __Pyx_INCREF(__pyx_v_self->version); - __Pyx_GIVEREF(__pyx_v_self->version); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_self->version); - __pyx_t_2 = __Pyx_PyList_Append(__pyx_cur_scope->__pyx_v_info, __pyx_t_1); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(0, 235, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":236 - * info = [] - * info.append(("version", self.version)) - * info.append(("code", self.code)) # <<<<<<<<<<<<<< - * info.append(("reason", self.reason)) - * info.append(("headers", self.headers)) - */ - __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->code); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 236, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 236, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_n_u_code); - __Pyx_GIVEREF(__pyx_n_u_code); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_n_u_code); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); - __pyx_t_1 = 0; - __pyx_t_2 = __Pyx_PyList_Append(__pyx_cur_scope->__pyx_v_info, __pyx_t_3); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(0, 236, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "aiohttp/_http_parser.pyx":237 - * info.append(("version", self.version)) - * info.append(("code", self.code)) - * info.append(("reason", self.reason)) # <<<<<<<<<<<<<< - * info.append(("headers", self.headers)) - * info.append(("raw_headers", self.raw_headers)) - */ - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 237, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_n_u_reason); - __Pyx_GIVEREF(__pyx_n_u_reason); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_n_u_reason); - __Pyx_INCREF(__pyx_v_self->reason); - __Pyx_GIVEREF(__pyx_v_self->reason); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_self->reason); - __pyx_t_2 = __Pyx_PyList_Append(__pyx_cur_scope->__pyx_v_info, __pyx_t_3); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(0, 237, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "aiohttp/_http_parser.pyx":238 - * info.append(("code", self.code)) - * info.append(("reason", self.reason)) - * info.append(("headers", self.headers)) # <<<<<<<<<<<<<< - * info.append(("raw_headers", self.raw_headers)) - * info.append(("should_close", self.should_close)) - */ - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 238, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_n_u_headers); - __Pyx_GIVEREF(__pyx_n_u_headers); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_n_u_headers); - __Pyx_INCREF(__pyx_v_self->headers); - __Pyx_GIVEREF(__pyx_v_self->headers); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_self->headers); - __pyx_t_2 = __Pyx_PyList_Append(__pyx_cur_scope->__pyx_v_info, __pyx_t_3); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(0, 238, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "aiohttp/_http_parser.pyx":239 - * info.append(("reason", self.reason)) - * info.append(("headers", self.headers)) - * info.append(("raw_headers", self.raw_headers)) # <<<<<<<<<<<<<< - * info.append(("should_close", self.should_close)) - * info.append(("compression", self.compression)) - */ - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 239, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_n_u_raw_headers); - __Pyx_GIVEREF(__pyx_n_u_raw_headers); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_n_u_raw_headers); - __Pyx_INCREF(__pyx_v_self->raw_headers); - __Pyx_GIVEREF(__pyx_v_self->raw_headers); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_self->raw_headers); - __pyx_t_2 = __Pyx_PyList_Append(__pyx_cur_scope->__pyx_v_info, __pyx_t_3); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(0, 239, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "aiohttp/_http_parser.pyx":240 - * info.append(("headers", self.headers)) - * info.append(("raw_headers", self.raw_headers)) - * info.append(("should_close", self.should_close)) # <<<<<<<<<<<<<< - * info.append(("compression", self.compression)) - * info.append(("upgrade", self.upgrade)) - */ - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 240, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_n_u_should_close); - __Pyx_GIVEREF(__pyx_n_u_should_close); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_n_u_should_close); - __Pyx_INCREF(__pyx_v_self->should_close); - __Pyx_GIVEREF(__pyx_v_self->should_close); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_self->should_close); - __pyx_t_2 = __Pyx_PyList_Append(__pyx_cur_scope->__pyx_v_info, __pyx_t_3); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(0, 240, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "aiohttp/_http_parser.pyx":241 - * info.append(("raw_headers", self.raw_headers)) - * info.append(("should_close", self.should_close)) - * info.append(("compression", self.compression)) # <<<<<<<<<<<<<< - * info.append(("upgrade", self.upgrade)) - * info.append(("chunked", self.chunked)) - */ - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 241, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_n_u_compression); - __Pyx_GIVEREF(__pyx_n_u_compression); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_n_u_compression); - __Pyx_INCREF(__pyx_v_self->compression); - __Pyx_GIVEREF(__pyx_v_self->compression); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_self->compression); - __pyx_t_2 = __Pyx_PyList_Append(__pyx_cur_scope->__pyx_v_info, __pyx_t_3); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(0, 241, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "aiohttp/_http_parser.pyx":242 - * info.append(("should_close", self.should_close)) - * info.append(("compression", self.compression)) - * info.append(("upgrade", self.upgrade)) # <<<<<<<<<<<<<< - * info.append(("chunked", self.chunked)) - * sinfo = ', '.join(name + '=' + repr(val) for name, val in info) - */ - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 242, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_n_u_upgrade); - __Pyx_GIVEREF(__pyx_n_u_upgrade); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_n_u_upgrade); - __Pyx_INCREF(__pyx_v_self->upgrade); - __Pyx_GIVEREF(__pyx_v_self->upgrade); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_self->upgrade); - __pyx_t_2 = __Pyx_PyList_Append(__pyx_cur_scope->__pyx_v_info, __pyx_t_3); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(0, 242, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "aiohttp/_http_parser.pyx":243 - * info.append(("compression", self.compression)) - * info.append(("upgrade", self.upgrade)) - * info.append(("chunked", self.chunked)) # <<<<<<<<<<<<<< - * sinfo = ', '.join(name + '=' + repr(val) for name, val in info) - * return '' - */ - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 243, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_n_u_chunked); - __Pyx_GIVEREF(__pyx_n_u_chunked); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_n_u_chunked); - __Pyx_INCREF(__pyx_v_self->chunked); - __Pyx_GIVEREF(__pyx_v_self->chunked); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_self->chunked); - __pyx_t_2 = __Pyx_PyList_Append(__pyx_cur_scope->__pyx_v_info, __pyx_t_3); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(0, 243, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "aiohttp/_http_parser.pyx":244 - * info.append(("upgrade", self.upgrade)) - * info.append(("chunked", self.chunked)) - * sinfo = ', '.join(name + '=' + repr(val) for name, val in info) # <<<<<<<<<<<<<< - * return '' - * - */ - __pyx_t_3 = __pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_8__repr___genexpr(((PyObject*)__pyx_cur_scope)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 244, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = __Pyx_Generator_Next(__pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 244, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyUnicode_Join(__pyx_kp_u__2, __pyx_t_1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 244, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_sinfo = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_http_parser.pyx":245 - * info.append(("chunked", self.chunked)) - * sinfo = ', '.join(name + '=' + repr(val) for name, val in info) - * return '' # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __Pyx_PyUnicode_ConcatSafe(__pyx_kp_u_RawResponseMessage, __pyx_v_sinfo); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 245, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_1 = __Pyx_PyUnicode_Concat(__pyx_t_3, __pyx_kp_u__3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 245, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "aiohttp/_http_parser.pyx":233 - * self.chunked = chunked - * - * def __repr__(self): # <<<<<<<<<<<<<< - * info = [] - * info.append(("version", self.version)) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("aiohttp._http_parser.RawResponseMessage.__repr__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_sinfo); - __Pyx_XDECREF(__pyx_gb_7aiohttp_12_http_parser_18RawResponseMessage_8__repr___2generator1); - __Pyx_DECREF(((PyObject *)__pyx_cur_scope)); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":211 - * @cython.freelist(DEFAULT_FREELIST_SIZE) - * cdef class RawResponseMessage: - * cdef readonly object version # HttpVersion # <<<<<<<<<<<<<< - * cdef readonly int code - * cdef readonly str reason - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_7version_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_7version_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_7version___get__(((struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_7version___get__(struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->version); - __pyx_r = __pyx_v_self->version; - goto __pyx_L0; - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":212 - * cdef class RawResponseMessage: - * cdef readonly object version # HttpVersion - * cdef readonly int code # <<<<<<<<<<<<<< - * cdef readonly str reason - * cdef readonly object headers # CIMultiDict - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_4code_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_4code_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_4code___get__(((struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_4code___get__(struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->code); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 212, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._http_parser.RawResponseMessage.code.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":213 - * cdef readonly object version # HttpVersion - * cdef readonly int code - * cdef readonly str reason # <<<<<<<<<<<<<< - * cdef readonly object headers # CIMultiDict - * cdef readonly object raw_headers # tuple - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_6reason_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_6reason_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_6reason___get__(((struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_6reason___get__(struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->reason); - __pyx_r = __pyx_v_self->reason; - goto __pyx_L0; - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":214 - * cdef readonly int code - * cdef readonly str reason - * cdef readonly object headers # CIMultiDict # <<<<<<<<<<<<<< - * cdef readonly object raw_headers # tuple - * cdef readonly object should_close - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_7headers_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_7headers_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_7headers___get__(((struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_7headers___get__(struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->headers); - __pyx_r = __pyx_v_self->headers; - goto __pyx_L0; - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":215 - * cdef readonly str reason - * cdef readonly object headers # CIMultiDict - * cdef readonly object raw_headers # tuple # <<<<<<<<<<<<<< - * cdef readonly object should_close - * cdef readonly object compression - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_11raw_headers_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_11raw_headers_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_11raw_headers___get__(((struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_11raw_headers___get__(struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->raw_headers); - __pyx_r = __pyx_v_self->raw_headers; - goto __pyx_L0; - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":216 - * cdef readonly object headers # CIMultiDict - * cdef readonly object raw_headers # tuple - * cdef readonly object should_close # <<<<<<<<<<<<<< - * cdef readonly object compression - * cdef readonly object upgrade - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_12should_close_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_12should_close_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_12should_close___get__(((struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_12should_close___get__(struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->should_close); - __pyx_r = __pyx_v_self->should_close; - goto __pyx_L0; - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":217 - * cdef readonly object raw_headers # tuple - * cdef readonly object should_close - * cdef readonly object compression # <<<<<<<<<<<<<< - * cdef readonly object upgrade - * cdef readonly object chunked - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_11compression_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_11compression_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_11compression___get__(((struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_11compression___get__(struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->compression); - __pyx_r = __pyx_v_self->compression; - goto __pyx_L0; - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":218 - * cdef readonly object should_close - * cdef readonly object compression - * cdef readonly object upgrade # <<<<<<<<<<<<<< - * cdef readonly object chunked - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_7upgrade_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_7upgrade_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_7upgrade___get__(((struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_7upgrade___get__(struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->upgrade); - __pyx_r = __pyx_v_self->upgrade; - goto __pyx_L0; - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":219 - * cdef readonly object compression - * cdef readonly object upgrade - * cdef readonly object chunked # <<<<<<<<<<<<<< - * - * def __init__(self, version, code, reason, headers, raw_headers, - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_7chunked_1__get__(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_7chunked_1__get__(PyObject *__pyx_v_self) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_7chunked___get__(((struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_7chunked___get__(struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__get__", 0); - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_self->chunked); - __pyx_r = __pyx_v_self->chunked; - goto __pyx_L0; - - /* function exit code */ - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * cdef tuple state - * cdef object _dict - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_5__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_5__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_4__reduce_cython__(((struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_4__reduce_cython__(struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *__pyx_v_self) { - PyObject *__pyx_v_state = 0; - PyObject *__pyx_v__dict = 0; - int __pyx_v_use_setstate; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_t_3; - int __pyx_t_4; - int __pyx_t_5; - PyObject *__pyx_t_6 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce_cython__", 0); - - /* "(tree fragment)":5 - * cdef object _dict - * cdef bint use_setstate - * state = (self.chunked, self.code, self.compression, self.headers, self.raw_headers, self.reason, self.should_close, self.upgrade, self.version) # <<<<<<<<<<<<<< - * _dict = getattr(self, '__dict__', None) - * if _dict is not None: - */ - __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->code); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyTuple_New(9); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_self->chunked); - __Pyx_GIVEREF(__pyx_v_self->chunked); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_self->chunked); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_1); - __Pyx_INCREF(__pyx_v_self->compression); - __Pyx_GIVEREF(__pyx_v_self->compression); - PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_v_self->compression); - __Pyx_INCREF(__pyx_v_self->headers); - __Pyx_GIVEREF(__pyx_v_self->headers); - PyTuple_SET_ITEM(__pyx_t_2, 3, __pyx_v_self->headers); - __Pyx_INCREF(__pyx_v_self->raw_headers); - __Pyx_GIVEREF(__pyx_v_self->raw_headers); - PyTuple_SET_ITEM(__pyx_t_2, 4, __pyx_v_self->raw_headers); - __Pyx_INCREF(__pyx_v_self->reason); - __Pyx_GIVEREF(__pyx_v_self->reason); - PyTuple_SET_ITEM(__pyx_t_2, 5, __pyx_v_self->reason); - __Pyx_INCREF(__pyx_v_self->should_close); - __Pyx_GIVEREF(__pyx_v_self->should_close); - PyTuple_SET_ITEM(__pyx_t_2, 6, __pyx_v_self->should_close); - __Pyx_INCREF(__pyx_v_self->upgrade); - __Pyx_GIVEREF(__pyx_v_self->upgrade); - PyTuple_SET_ITEM(__pyx_t_2, 7, __pyx_v_self->upgrade); - __Pyx_INCREF(__pyx_v_self->version); - __Pyx_GIVEREF(__pyx_v_self->version); - PyTuple_SET_ITEM(__pyx_t_2, 8, __pyx_v_self->version); - __pyx_t_1 = 0; - __pyx_v_state = ((PyObject*)__pyx_t_2); - __pyx_t_2 = 0; - - /* "(tree fragment)":6 - * cdef bint use_setstate - * state = (self.chunked, self.code, self.compression, self.headers, self.raw_headers, self.reason, self.should_close, self.upgrade, self.version) - * _dict = getattr(self, '__dict__', None) # <<<<<<<<<<<<<< - * if _dict is not None: - * state += (_dict,) - */ - __pyx_t_2 = __Pyx_GetAttr3(((PyObject *)__pyx_v_self), __pyx_n_s_dict, Py_None); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_v__dict = __pyx_t_2; - __pyx_t_2 = 0; - - /* "(tree fragment)":7 - * state = (self.chunked, self.code, self.compression, self.headers, self.raw_headers, self.reason, self.should_close, self.upgrade, self.version) - * _dict = getattr(self, '__dict__', None) - * if _dict is not None: # <<<<<<<<<<<<<< - * state += (_dict,) - * use_setstate = True - */ - __pyx_t_3 = (__pyx_v__dict != Py_None); - __pyx_t_4 = (__pyx_t_3 != 0); - if (__pyx_t_4) { - - /* "(tree fragment)":8 - * _dict = getattr(self, '__dict__', None) - * if _dict is not None: - * state += (_dict,) # <<<<<<<<<<<<<< - * use_setstate = True - * else: - */ - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 8, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v__dict); - __Pyx_GIVEREF(__pyx_v__dict); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v__dict); - __pyx_t_1 = PyNumber_InPlaceAdd(__pyx_v_state, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 8, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF_SET(__pyx_v_state, ((PyObject*)__pyx_t_1)); - __pyx_t_1 = 0; - - /* "(tree fragment)":9 - * if _dict is not None: - * state += (_dict,) - * use_setstate = True # <<<<<<<<<<<<<< - * else: - * use_setstate = self.chunked is not None or self.compression is not None or self.headers is not None or self.raw_headers is not None or self.reason is not None or self.should_close is not None or self.upgrade is not None or self.version is not None - */ - __pyx_v_use_setstate = 1; - - /* "(tree fragment)":7 - * state = (self.chunked, self.code, self.compression, self.headers, self.raw_headers, self.reason, self.should_close, self.upgrade, self.version) - * _dict = getattr(self, '__dict__', None) - * if _dict is not None: # <<<<<<<<<<<<<< - * state += (_dict,) - * use_setstate = True - */ - goto __pyx_L3; - } - - /* "(tree fragment)":11 - * use_setstate = True - * else: - * use_setstate = self.chunked is not None or self.compression is not None or self.headers is not None or self.raw_headers is not None or self.reason is not None or self.should_close is not None or self.upgrade is not None or self.version is not None # <<<<<<<<<<<<<< - * if use_setstate: - * return __pyx_unpickle_RawResponseMessage, (type(self), 0xc7706dc, None), state - */ - /*else*/ { - __pyx_t_3 = (__pyx_v_self->chunked != Py_None); - __pyx_t_5 = (__pyx_t_3 != 0); - if (!__pyx_t_5) { - } else { - __pyx_t_4 = __pyx_t_5; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_5 = (__pyx_v_self->compression != Py_None); - __pyx_t_3 = (__pyx_t_5 != 0); - if (!__pyx_t_3) { - } else { - __pyx_t_4 = __pyx_t_3; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_3 = (__pyx_v_self->headers != Py_None); - __pyx_t_5 = (__pyx_t_3 != 0); - if (!__pyx_t_5) { - } else { - __pyx_t_4 = __pyx_t_5; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_5 = (__pyx_v_self->raw_headers != Py_None); - __pyx_t_3 = (__pyx_t_5 != 0); - if (!__pyx_t_3) { - } else { - __pyx_t_4 = __pyx_t_3; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_3 = (__pyx_v_self->reason != ((PyObject*)Py_None)); - __pyx_t_5 = (__pyx_t_3 != 0); - if (!__pyx_t_5) { - } else { - __pyx_t_4 = __pyx_t_5; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_5 = (__pyx_v_self->should_close != Py_None); - __pyx_t_3 = (__pyx_t_5 != 0); - if (!__pyx_t_3) { - } else { - __pyx_t_4 = __pyx_t_3; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_3 = (__pyx_v_self->upgrade != Py_None); - __pyx_t_5 = (__pyx_t_3 != 0); - if (!__pyx_t_5) { - } else { - __pyx_t_4 = __pyx_t_5; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_5 = (__pyx_v_self->version != Py_None); - __pyx_t_3 = (__pyx_t_5 != 0); - __pyx_t_4 = __pyx_t_3; - __pyx_L4_bool_binop_done:; - __pyx_v_use_setstate = __pyx_t_4; - } - __pyx_L3:; - - /* "(tree fragment)":12 - * else: - * use_setstate = self.chunked is not None or self.compression is not None or self.headers is not None or self.raw_headers is not None or self.reason is not None or self.should_close is not None or self.upgrade is not None or self.version is not None - * if use_setstate: # <<<<<<<<<<<<<< - * return __pyx_unpickle_RawResponseMessage, (type(self), 0xc7706dc, None), state - * else: - */ - __pyx_t_4 = (__pyx_v_use_setstate != 0); - if (__pyx_t_4) { - - /* "(tree fragment)":13 - * use_setstate = self.chunked is not None or self.compression is not None or self.headers is not None or self.raw_headers is not None or self.reason is not None or self.should_close is not None or self.upgrade is not None or self.version is not None - * if use_setstate: - * return __pyx_unpickle_RawResponseMessage, (type(self), 0xc7706dc, None), state # <<<<<<<<<<<<<< - * else: - * return __pyx_unpickle_RawResponseMessage, (type(self), 0xc7706dc, state) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_pyx_unpickle_RawResponseMessag); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyTuple_New(3); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - __Pyx_INCREF(__pyx_int_209127132); - __Pyx_GIVEREF(__pyx_int_209127132); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_int_209127132); - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - PyTuple_SET_ITEM(__pyx_t_2, 2, Py_None); - __pyx_t_6 = PyTuple_New(3); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_t_2); - __Pyx_INCREF(__pyx_v_state); - __Pyx_GIVEREF(__pyx_v_state); - PyTuple_SET_ITEM(__pyx_t_6, 2, __pyx_v_state); - __pyx_t_1 = 0; - __pyx_t_2 = 0; - __pyx_r = __pyx_t_6; - __pyx_t_6 = 0; - goto __pyx_L0; - - /* "(tree fragment)":12 - * else: - * use_setstate = self.chunked is not None or self.compression is not None or self.headers is not None or self.raw_headers is not None or self.reason is not None or self.should_close is not None or self.upgrade is not None or self.version is not None - * if use_setstate: # <<<<<<<<<<<<<< - * return __pyx_unpickle_RawResponseMessage, (type(self), 0xc7706dc, None), state - * else: - */ - } - - /* "(tree fragment)":15 - * return __pyx_unpickle_RawResponseMessage, (type(self), 0xc7706dc, None), state - * else: - * return __pyx_unpickle_RawResponseMessage, (type(self), 0xc7706dc, state) # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * __pyx_unpickle_RawResponseMessage__set_state(self, __pyx_state) - */ - /*else*/ { - __Pyx_XDECREF(__pyx_r); - __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_n_s_pyx_unpickle_RawResponseMessag); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 15, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_2 = PyTuple_New(3); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 15, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); - __Pyx_INCREF(__pyx_int_209127132); - __Pyx_GIVEREF(__pyx_int_209127132); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_int_209127132); - __Pyx_INCREF(__pyx_v_state); - __Pyx_GIVEREF(__pyx_v_state); - PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_v_state); - __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 15, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_6); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_2); - __pyx_t_6 = 0; - __pyx_t_2 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - } - - /* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * cdef tuple state - * cdef object _dict - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("aiohttp._http_parser.RawResponseMessage.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_state); - __Pyx_XDECREF(__pyx_v__dict); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":16 - * else: - * return __pyx_unpickle_RawResponseMessage, (type(self), 0xc7706dc, state) - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * __pyx_unpickle_RawResponseMessage__set_state(self, __pyx_state) - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_7__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_7__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_6__setstate_cython__(((struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_18RawResponseMessage_6__setstate_cython__(struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *__pyx_v_self, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setstate_cython__", 0); - - /* "(tree fragment)":17 - * return __pyx_unpickle_RawResponseMessage, (type(self), 0xc7706dc, state) - * def __setstate_cython__(self, __pyx_state): - * __pyx_unpickle_RawResponseMessage__set_state(self, __pyx_state) # <<<<<<<<<<<<<< - */ - if (!(likely(PyTuple_CheckExact(__pyx_v___pyx_state))||((__pyx_v___pyx_state) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(1, 17, __pyx_L1_error) - __pyx_t_1 = __pyx_f_7aiohttp_12_http_parser___pyx_unpickle_RawResponseMessage__set_state(__pyx_v_self, ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 17, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "(tree fragment)":16 - * else: - * return __pyx_unpickle_RawResponseMessage, (type(self), 0xc7706dc, state) - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * __pyx_unpickle_RawResponseMessage__set_state(self, __pyx_state) - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._http_parser.RawResponseMessage.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":248 - * - * - * cdef _new_response_message(object version, # <<<<<<<<<<<<<< - * int code, - * str reason, - */ - -static PyObject *__pyx_f_7aiohttp_12_http_parser__new_response_message(PyObject *__pyx_v_version, int __pyx_v_code, PyObject *__pyx_v_reason, PyObject *__pyx_v_headers, PyObject *__pyx_v_raw_headers, int __pyx_v_should_close, PyObject *__pyx_v_compression, int __pyx_v_upgrade, int __pyx_v_chunked) { - struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *__pyx_v_ret = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_new_response_message", 0); - - /* "aiohttp/_http_parser.pyx":258 - * bint chunked): - * cdef RawResponseMessage ret - * ret = RawResponseMessage.__new__(RawResponseMessage) # <<<<<<<<<<<<<< - * ret.version = version - * ret.code = code - */ - __pyx_t_1 = ((PyObject *)__pyx_tp_new_7aiohttp_12_http_parser_RawResponseMessage(((PyTypeObject *)__pyx_ptype_7aiohttp_12_http_parser_RawResponseMessage), __pyx_empty_tuple, NULL)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 258, __pyx_L1_error) - __Pyx_GOTREF(((PyObject *)__pyx_t_1)); - __pyx_v_ret = ((struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":259 - * cdef RawResponseMessage ret - * ret = RawResponseMessage.__new__(RawResponseMessage) - * ret.version = version # <<<<<<<<<<<<<< - * ret.code = code - * ret.reason = reason - */ - __Pyx_INCREF(__pyx_v_version); - __Pyx_GIVEREF(__pyx_v_version); - __Pyx_GOTREF(__pyx_v_ret->version); - __Pyx_DECREF(__pyx_v_ret->version); - __pyx_v_ret->version = __pyx_v_version; - - /* "aiohttp/_http_parser.pyx":260 - * ret = RawResponseMessage.__new__(RawResponseMessage) - * ret.version = version - * ret.code = code # <<<<<<<<<<<<<< - * ret.reason = reason - * ret.headers = headers - */ - __pyx_v_ret->code = __pyx_v_code; - - /* "aiohttp/_http_parser.pyx":261 - * ret.version = version - * ret.code = code - * ret.reason = reason # <<<<<<<<<<<<<< - * ret.headers = headers - * ret.raw_headers = raw_headers - */ - __Pyx_INCREF(__pyx_v_reason); - __Pyx_GIVEREF(__pyx_v_reason); - __Pyx_GOTREF(__pyx_v_ret->reason); - __Pyx_DECREF(__pyx_v_ret->reason); - __pyx_v_ret->reason = __pyx_v_reason; - - /* "aiohttp/_http_parser.pyx":262 - * ret.code = code - * ret.reason = reason - * ret.headers = headers # <<<<<<<<<<<<<< - * ret.raw_headers = raw_headers - * ret.should_close = should_close - */ - __Pyx_INCREF(__pyx_v_headers); - __Pyx_GIVEREF(__pyx_v_headers); - __Pyx_GOTREF(__pyx_v_ret->headers); - __Pyx_DECREF(__pyx_v_ret->headers); - __pyx_v_ret->headers = __pyx_v_headers; - - /* "aiohttp/_http_parser.pyx":263 - * ret.reason = reason - * ret.headers = headers - * ret.raw_headers = raw_headers # <<<<<<<<<<<<<< - * ret.should_close = should_close - * ret.compression = compression - */ - __Pyx_INCREF(__pyx_v_raw_headers); - __Pyx_GIVEREF(__pyx_v_raw_headers); - __Pyx_GOTREF(__pyx_v_ret->raw_headers); - __Pyx_DECREF(__pyx_v_ret->raw_headers); - __pyx_v_ret->raw_headers = __pyx_v_raw_headers; - - /* "aiohttp/_http_parser.pyx":264 - * ret.headers = headers - * ret.raw_headers = raw_headers - * ret.should_close = should_close # <<<<<<<<<<<<<< - * ret.compression = compression - * ret.upgrade = upgrade - */ - __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_v_should_close); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 264, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v_ret->should_close); - __Pyx_DECREF(__pyx_v_ret->should_close); - __pyx_v_ret->should_close = __pyx_t_1; - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":265 - * ret.raw_headers = raw_headers - * ret.should_close = should_close - * ret.compression = compression # <<<<<<<<<<<<<< - * ret.upgrade = upgrade - * ret.chunked = chunked - */ - __Pyx_INCREF(__pyx_v_compression); - __Pyx_GIVEREF(__pyx_v_compression); - __Pyx_GOTREF(__pyx_v_ret->compression); - __Pyx_DECREF(__pyx_v_ret->compression); - __pyx_v_ret->compression = __pyx_v_compression; - - /* "aiohttp/_http_parser.pyx":266 - * ret.should_close = should_close - * ret.compression = compression - * ret.upgrade = upgrade # <<<<<<<<<<<<<< - * ret.chunked = chunked - * return ret - */ - __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_v_upgrade); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 266, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v_ret->upgrade); - __Pyx_DECREF(__pyx_v_ret->upgrade); - __pyx_v_ret->upgrade = __pyx_t_1; - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":267 - * ret.compression = compression - * ret.upgrade = upgrade - * ret.chunked = chunked # <<<<<<<<<<<<<< - * return ret - * - */ - __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_v_chunked); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 267, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v_ret->chunked); - __Pyx_DECREF(__pyx_v_ret->chunked); - __pyx_v_ret->chunked = __pyx_t_1; - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":268 - * ret.upgrade = upgrade - * ret.chunked = chunked - * return ret # <<<<<<<<<<<<<< - * - * - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject *)__pyx_v_ret)); - __pyx_r = ((PyObject *)__pyx_v_ret); - goto __pyx_L0; - - /* "aiohttp/_http_parser.pyx":248 - * - * - * cdef _new_response_message(object version, # <<<<<<<<<<<<<< - * int code, - * str reason, - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._http_parser._new_response_message", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_ret); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":312 - * Py_buffer py_buf - * - * def __cinit__(self): # <<<<<<<<<<<<<< - * self._cparser = \ - * PyMem_Malloc(sizeof(cparser.llhttp_t)) - */ - -/* Python wrapper */ -static int __pyx_pw_7aiohttp_12_http_parser_10HttpParser_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pw_7aiohttp_12_http_parser_10HttpParser_1__cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); - if (unlikely(PyTuple_GET_SIZE(__pyx_args) > 0)) { - __Pyx_RaiseArgtupleInvalid("__cinit__", 1, 0, 0, PyTuple_GET_SIZE(__pyx_args)); return -1;} - if (unlikely(__pyx_kwds) && unlikely(PyDict_Size(__pyx_kwds) > 0) && unlikely(!__Pyx_CheckKeywordStrings(__pyx_kwds, "__cinit__", 0))) return -1; - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_10HttpParser___cinit__(((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_7aiohttp_12_http_parser_10HttpParser___cinit__(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self) { - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__cinit__", 0); - - /* "aiohttp/_http_parser.pyx":313 - * - * def __cinit__(self): - * self._cparser = \ # <<<<<<<<<<<<<< - * PyMem_Malloc(sizeof(cparser.llhttp_t)) - * if self._cparser is NULL: - */ - __pyx_v_self->_cparser = ((llhttp_t *)PyMem_Malloc((sizeof(llhttp_t)))); - - /* "aiohttp/_http_parser.pyx":315 - * self._cparser = \ - * PyMem_Malloc(sizeof(cparser.llhttp_t)) - * if self._cparser is NULL: # <<<<<<<<<<<<<< - * raise MemoryError() - * - */ - __pyx_t_1 = ((__pyx_v_self->_cparser == NULL) != 0); - if (unlikely(__pyx_t_1)) { - - /* "aiohttp/_http_parser.pyx":316 - * PyMem_Malloc(sizeof(cparser.llhttp_t)) - * if self._cparser is NULL: - * raise MemoryError() # <<<<<<<<<<<<<< - * - * self._csettings = \ - */ - PyErr_NoMemory(); __PYX_ERR(0, 316, __pyx_L1_error) - - /* "aiohttp/_http_parser.pyx":315 - * self._cparser = \ - * PyMem_Malloc(sizeof(cparser.llhttp_t)) - * if self._cparser is NULL: # <<<<<<<<<<<<<< - * raise MemoryError() - * - */ - } - - /* "aiohttp/_http_parser.pyx":318 - * raise MemoryError() - * - * self._csettings = \ # <<<<<<<<<<<<<< - * PyMem_Malloc(sizeof(cparser.llhttp_settings_t)) - * if self._csettings is NULL: - */ - __pyx_v_self->_csettings = ((llhttp_settings_t *)PyMem_Malloc((sizeof(llhttp_settings_t)))); - - /* "aiohttp/_http_parser.pyx":320 - * self._csettings = \ - * PyMem_Malloc(sizeof(cparser.llhttp_settings_t)) - * if self._csettings is NULL: # <<<<<<<<<<<<<< - * raise MemoryError() - * - */ - __pyx_t_1 = ((__pyx_v_self->_csettings == NULL) != 0); - if (unlikely(__pyx_t_1)) { - - /* "aiohttp/_http_parser.pyx":321 - * PyMem_Malloc(sizeof(cparser.llhttp_settings_t)) - * if self._csettings is NULL: - * raise MemoryError() # <<<<<<<<<<<<<< - * - * def __dealloc__(self): - */ - PyErr_NoMemory(); __PYX_ERR(0, 321, __pyx_L1_error) - - /* "aiohttp/_http_parser.pyx":320 - * self._csettings = \ - * PyMem_Malloc(sizeof(cparser.llhttp_settings_t)) - * if self._csettings is NULL: # <<<<<<<<<<<<<< - * raise MemoryError() - * - */ - } - - /* "aiohttp/_http_parser.pyx":312 - * Py_buffer py_buf - * - * def __cinit__(self): # <<<<<<<<<<<<<< - * self._cparser = \ - * PyMem_Malloc(sizeof(cparser.llhttp_t)) - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_AddTraceback("aiohttp._http_parser.HttpParser.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":323 - * raise MemoryError() - * - * def __dealloc__(self): # <<<<<<<<<<<<<< - * PyMem_Free(self._cparser) - * PyMem_Free(self._csettings) - */ - -/* Python wrapper */ -static void __pyx_pw_7aiohttp_12_http_parser_10HttpParser_3__dealloc__(PyObject *__pyx_v_self); /*proto*/ -static void __pyx_pw_7aiohttp_12_http_parser_10HttpParser_3__dealloc__(PyObject *__pyx_v_self) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); - __pyx_pf_7aiohttp_12_http_parser_10HttpParser_2__dealloc__(((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -static void __pyx_pf_7aiohttp_12_http_parser_10HttpParser_2__dealloc__(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__dealloc__", 0); - - /* "aiohttp/_http_parser.pyx":324 - * - * def __dealloc__(self): - * PyMem_Free(self._cparser) # <<<<<<<<<<<<<< - * PyMem_Free(self._csettings) - * - */ - PyMem_Free(__pyx_v_self->_cparser); - - /* "aiohttp/_http_parser.pyx":325 - * def __dealloc__(self): - * PyMem_Free(self._cparser) - * PyMem_Free(self._csettings) # <<<<<<<<<<<<<< - * - * cdef _init( - */ - PyMem_Free(__pyx_v_self->_csettings); - - /* "aiohttp/_http_parser.pyx":323 - * raise MemoryError() - * - * def __dealloc__(self): # <<<<<<<<<<<<<< - * PyMem_Free(self._cparser) - * PyMem_Free(self._csettings) - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -/* "aiohttp/_http_parser.pyx":327 - * PyMem_Free(self._csettings) - * - * cdef _init( # <<<<<<<<<<<<<< - * self, cparser.llhttp_type mode, - * object protocol, object loop, int limit, - */ - -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__init(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self, enum llhttp_type __pyx_v_mode, PyObject *__pyx_v_protocol, PyObject *__pyx_v_loop, int __pyx_v_limit, struct __pyx_opt_args_7aiohttp_12_http_parser_10HttpParser__init *__pyx_optional_args) { - - /* "aiohttp/_http_parser.pyx":330 - * self, cparser.llhttp_type mode, - * object protocol, object loop, int limit, - * object timer=None, # <<<<<<<<<<<<<< - * size_t max_line_size=8190, size_t max_headers=32768, - * size_t max_field_size=8190, payload_exception=None, - */ - PyObject *__pyx_v_timer = ((PyObject *)Py_None); - size_t __pyx_v_max_line_size = ((size_t)0x1FFE); - size_t __pyx_v_max_headers = ((size_t)0x8000); - size_t __pyx_v_max_field_size = ((size_t)0x1FFE); - - /* "aiohttp/_http_parser.pyx":332 - * object timer=None, - * size_t max_line_size=8190, size_t max_headers=32768, - * size_t max_field_size=8190, payload_exception=None, # <<<<<<<<<<<<<< - * bint response_with_body=True, bint read_until_eof=False, - * bint auto_decompress=True, - */ - PyObject *__pyx_v_payload_exception = ((PyObject *)Py_None); - - /* "aiohttp/_http_parser.pyx":333 - * size_t max_line_size=8190, size_t max_headers=32768, - * size_t max_field_size=8190, payload_exception=None, - * bint response_with_body=True, bint read_until_eof=False, # <<<<<<<<<<<<<< - * bint auto_decompress=True, - * ): - */ - int __pyx_v_response_with_body = ((int)1); - int __pyx_v_read_until_eof = ((int)0); - - /* "aiohttp/_http_parser.pyx":334 - * size_t max_field_size=8190, payload_exception=None, - * bint response_with_body=True, bint read_until_eof=False, - * bint auto_decompress=True, # <<<<<<<<<<<<<< - * ): - * cparser.llhttp_settings_init(self._csettings) - */ - int __pyx_v_auto_decompress = ((int)1); - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_init", 0); - if (__pyx_optional_args) { - if (__pyx_optional_args->__pyx_n > 0) { - __pyx_v_timer = __pyx_optional_args->timer; - if (__pyx_optional_args->__pyx_n > 1) { - __pyx_v_max_line_size = __pyx_optional_args->max_line_size; - if (__pyx_optional_args->__pyx_n > 2) { - __pyx_v_max_headers = __pyx_optional_args->max_headers; - if (__pyx_optional_args->__pyx_n > 3) { - __pyx_v_max_field_size = __pyx_optional_args->max_field_size; - if (__pyx_optional_args->__pyx_n > 4) { - __pyx_v_payload_exception = __pyx_optional_args->payload_exception; - if (__pyx_optional_args->__pyx_n > 5) { - __pyx_v_response_with_body = __pyx_optional_args->response_with_body; - if (__pyx_optional_args->__pyx_n > 6) { - __pyx_v_read_until_eof = __pyx_optional_args->read_until_eof; - if (__pyx_optional_args->__pyx_n > 7) { - __pyx_v_auto_decompress = __pyx_optional_args->auto_decompress; - } - } - } - } - } - } - } - } - } - - /* "aiohttp/_http_parser.pyx":336 - * bint auto_decompress=True, - * ): - * cparser.llhttp_settings_init(self._csettings) # <<<<<<<<<<<<<< - * cparser.llhttp_init(self._cparser, mode, self._csettings) - * self._cparser.data = self - */ - llhttp_settings_init(__pyx_v_self->_csettings); - - /* "aiohttp/_http_parser.pyx":337 - * ): - * cparser.llhttp_settings_init(self._csettings) - * cparser.llhttp_init(self._cparser, mode, self._csettings) # <<<<<<<<<<<<<< - * self._cparser.data = self - * self._cparser.content_length = 0 - */ - llhttp_init(__pyx_v_self->_cparser, __pyx_v_mode, __pyx_v_self->_csettings); - - /* "aiohttp/_http_parser.pyx":338 - * cparser.llhttp_settings_init(self._csettings) - * cparser.llhttp_init(self._cparser, mode, self._csettings) - * self._cparser.data = self # <<<<<<<<<<<<<< - * self._cparser.content_length = 0 - * - */ - __pyx_v_self->_cparser->data = ((void *)__pyx_v_self); - - /* "aiohttp/_http_parser.pyx":339 - * cparser.llhttp_init(self._cparser, mode, self._csettings) - * self._cparser.data = self - * self._cparser.content_length = 0 # <<<<<<<<<<<<<< - * - * self._protocol = protocol - */ - __pyx_v_self->_cparser->content_length = 0; - - /* "aiohttp/_http_parser.pyx":341 - * self._cparser.content_length = 0 - * - * self._protocol = protocol # <<<<<<<<<<<<<< - * self._loop = loop - * self._timer = timer - */ - __Pyx_INCREF(__pyx_v_protocol); - __Pyx_GIVEREF(__pyx_v_protocol); - __Pyx_GOTREF(__pyx_v_self->_protocol); - __Pyx_DECREF(__pyx_v_self->_protocol); - __pyx_v_self->_protocol = __pyx_v_protocol; - - /* "aiohttp/_http_parser.pyx":342 - * - * self._protocol = protocol - * self._loop = loop # <<<<<<<<<<<<<< - * self._timer = timer - * - */ - __Pyx_INCREF(__pyx_v_loop); - __Pyx_GIVEREF(__pyx_v_loop); - __Pyx_GOTREF(__pyx_v_self->_loop); - __Pyx_DECREF(__pyx_v_self->_loop); - __pyx_v_self->_loop = __pyx_v_loop; - - /* "aiohttp/_http_parser.pyx":343 - * self._protocol = protocol - * self._loop = loop - * self._timer = timer # <<<<<<<<<<<<<< - * - * self._buf = bytearray() - */ - __Pyx_INCREF(__pyx_v_timer); - __Pyx_GIVEREF(__pyx_v_timer); - __Pyx_GOTREF(__pyx_v_self->_timer); - __Pyx_DECREF(__pyx_v_self->_timer); - __pyx_v_self->_timer = __pyx_v_timer; - - /* "aiohttp/_http_parser.pyx":345 - * self._timer = timer - * - * self._buf = bytearray() # <<<<<<<<<<<<<< - * self._payload = None - * self._payload_error = 0 - */ - __pyx_t_1 = __Pyx_PyObject_CallNoArg(((PyObject *)(&PyByteArray_Type))); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 345, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v_self->_buf); - __Pyx_DECREF(__pyx_v_self->_buf); - __pyx_v_self->_buf = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":346 - * - * self._buf = bytearray() - * self._payload = None # <<<<<<<<<<<<<< - * self._payload_error = 0 - * self._payload_exception = payload_exception - */ - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - __Pyx_GOTREF(__pyx_v_self->_payload); - __Pyx_DECREF(__pyx_v_self->_payload); - __pyx_v_self->_payload = Py_None; - - /* "aiohttp/_http_parser.pyx":347 - * self._buf = bytearray() - * self._payload = None - * self._payload_error = 0 # <<<<<<<<<<<<<< - * self._payload_exception = payload_exception - * self._messages = [] - */ - __pyx_v_self->_payload_error = 0; - - /* "aiohttp/_http_parser.pyx":348 - * self._payload = None - * self._payload_error = 0 - * self._payload_exception = payload_exception # <<<<<<<<<<<<<< - * self._messages = [] - * - */ - __Pyx_INCREF(__pyx_v_payload_exception); - __Pyx_GIVEREF(__pyx_v_payload_exception); - __Pyx_GOTREF(__pyx_v_self->_payload_exception); - __Pyx_DECREF(__pyx_v_self->_payload_exception); - __pyx_v_self->_payload_exception = __pyx_v_payload_exception; - - /* "aiohttp/_http_parser.pyx":349 - * self._payload_error = 0 - * self._payload_exception = payload_exception - * self._messages = [] # <<<<<<<<<<<<<< - * - * self._raw_name = bytearray() - */ - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 349, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v_self->_messages); - __Pyx_DECREF(__pyx_v_self->_messages); - __pyx_v_self->_messages = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":351 - * self._messages = [] - * - * self._raw_name = bytearray() # <<<<<<<<<<<<<< - * self._raw_value = bytearray() - * self._has_value = False - */ - __pyx_t_1 = __Pyx_PyObject_CallNoArg(((PyObject *)(&PyByteArray_Type))); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 351, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v_self->_raw_name); - __Pyx_DECREF(__pyx_v_self->_raw_name); - __pyx_v_self->_raw_name = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":352 - * - * self._raw_name = bytearray() - * self._raw_value = bytearray() # <<<<<<<<<<<<<< - * self._has_value = False - * - */ - __pyx_t_1 = __Pyx_PyObject_CallNoArg(((PyObject *)(&PyByteArray_Type))); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 352, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v_self->_raw_value); - __Pyx_DECREF(__pyx_v_self->_raw_value); - __pyx_v_self->_raw_value = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":353 - * self._raw_name = bytearray() - * self._raw_value = bytearray() - * self._has_value = False # <<<<<<<<<<<<<< - * - * self._max_line_size = max_line_size - */ - __pyx_v_self->_has_value = 0; - - /* "aiohttp/_http_parser.pyx":355 - * self._has_value = False - * - * self._max_line_size = max_line_size # <<<<<<<<<<<<<< - * self._max_headers = max_headers - * self._max_field_size = max_field_size - */ - __pyx_v_self->_max_line_size = __pyx_v_max_line_size; - - /* "aiohttp/_http_parser.pyx":356 - * - * self._max_line_size = max_line_size - * self._max_headers = max_headers # <<<<<<<<<<<<<< - * self._max_field_size = max_field_size - * self._response_with_body = response_with_body - */ - __pyx_v_self->_max_headers = __pyx_v_max_headers; - - /* "aiohttp/_http_parser.pyx":357 - * self._max_line_size = max_line_size - * self._max_headers = max_headers - * self._max_field_size = max_field_size # <<<<<<<<<<<<<< - * self._response_with_body = response_with_body - * self._read_until_eof = read_until_eof - */ - __pyx_v_self->_max_field_size = __pyx_v_max_field_size; - - /* "aiohttp/_http_parser.pyx":358 - * self._max_headers = max_headers - * self._max_field_size = max_field_size - * self._response_with_body = response_with_body # <<<<<<<<<<<<<< - * self._read_until_eof = read_until_eof - * self._upgraded = False - */ - __pyx_v_self->_response_with_body = __pyx_v_response_with_body; - - /* "aiohttp/_http_parser.pyx":359 - * self._max_field_size = max_field_size - * self._response_with_body = response_with_body - * self._read_until_eof = read_until_eof # <<<<<<<<<<<<<< - * self._upgraded = False - * self._auto_decompress = auto_decompress - */ - __pyx_v_self->_read_until_eof = __pyx_v_read_until_eof; - - /* "aiohttp/_http_parser.pyx":360 - * self._response_with_body = response_with_body - * self._read_until_eof = read_until_eof - * self._upgraded = False # <<<<<<<<<<<<<< - * self._auto_decompress = auto_decompress - * self._content_encoding = None - */ - __pyx_v_self->_upgraded = 0; - - /* "aiohttp/_http_parser.pyx":361 - * self._read_until_eof = read_until_eof - * self._upgraded = False - * self._auto_decompress = auto_decompress # <<<<<<<<<<<<<< - * self._content_encoding = None - * - */ - __pyx_v_self->_auto_decompress = __pyx_v_auto_decompress; - - /* "aiohttp/_http_parser.pyx":362 - * self._upgraded = False - * self._auto_decompress = auto_decompress - * self._content_encoding = None # <<<<<<<<<<<<<< - * - * self._csettings.on_url = cb_on_url - */ - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - __Pyx_GOTREF(__pyx_v_self->_content_encoding); - __Pyx_DECREF(__pyx_v_self->_content_encoding); - __pyx_v_self->_content_encoding = ((PyObject*)Py_None); - - /* "aiohttp/_http_parser.pyx":364 - * self._content_encoding = None - * - * self._csettings.on_url = cb_on_url # <<<<<<<<<<<<<< - * self._csettings.on_status = cb_on_status - * self._csettings.on_header_field = cb_on_header_field - */ - __pyx_v_self->_csettings->on_url = __pyx_f_7aiohttp_12_http_parser_cb_on_url; - - /* "aiohttp/_http_parser.pyx":365 - * - * self._csettings.on_url = cb_on_url - * self._csettings.on_status = cb_on_status # <<<<<<<<<<<<<< - * self._csettings.on_header_field = cb_on_header_field - * self._csettings.on_header_value = cb_on_header_value - */ - __pyx_v_self->_csettings->on_status = __pyx_f_7aiohttp_12_http_parser_cb_on_status; - - /* "aiohttp/_http_parser.pyx":366 - * self._csettings.on_url = cb_on_url - * self._csettings.on_status = cb_on_status - * self._csettings.on_header_field = cb_on_header_field # <<<<<<<<<<<<<< - * self._csettings.on_header_value = cb_on_header_value - * self._csettings.on_headers_complete = cb_on_headers_complete - */ - __pyx_v_self->_csettings->on_header_field = __pyx_f_7aiohttp_12_http_parser_cb_on_header_field; - - /* "aiohttp/_http_parser.pyx":367 - * self._csettings.on_status = cb_on_status - * self._csettings.on_header_field = cb_on_header_field - * self._csettings.on_header_value = cb_on_header_value # <<<<<<<<<<<<<< - * self._csettings.on_headers_complete = cb_on_headers_complete - * self._csettings.on_body = cb_on_body - */ - __pyx_v_self->_csettings->on_header_value = __pyx_f_7aiohttp_12_http_parser_cb_on_header_value; - - /* "aiohttp/_http_parser.pyx":368 - * self._csettings.on_header_field = cb_on_header_field - * self._csettings.on_header_value = cb_on_header_value - * self._csettings.on_headers_complete = cb_on_headers_complete # <<<<<<<<<<<<<< - * self._csettings.on_body = cb_on_body - * self._csettings.on_message_begin = cb_on_message_begin - */ - __pyx_v_self->_csettings->on_headers_complete = __pyx_f_7aiohttp_12_http_parser_cb_on_headers_complete; - - /* "aiohttp/_http_parser.pyx":369 - * self._csettings.on_header_value = cb_on_header_value - * self._csettings.on_headers_complete = cb_on_headers_complete - * self._csettings.on_body = cb_on_body # <<<<<<<<<<<<<< - * self._csettings.on_message_begin = cb_on_message_begin - * self._csettings.on_message_complete = cb_on_message_complete - */ - __pyx_v_self->_csettings->on_body = __pyx_f_7aiohttp_12_http_parser_cb_on_body; - - /* "aiohttp/_http_parser.pyx":370 - * self._csettings.on_headers_complete = cb_on_headers_complete - * self._csettings.on_body = cb_on_body - * self._csettings.on_message_begin = cb_on_message_begin # <<<<<<<<<<<<<< - * self._csettings.on_message_complete = cb_on_message_complete - * self._csettings.on_chunk_header = cb_on_chunk_header - */ - __pyx_v_self->_csettings->on_message_begin = __pyx_f_7aiohttp_12_http_parser_cb_on_message_begin; - - /* "aiohttp/_http_parser.pyx":371 - * self._csettings.on_body = cb_on_body - * self._csettings.on_message_begin = cb_on_message_begin - * self._csettings.on_message_complete = cb_on_message_complete # <<<<<<<<<<<<<< - * self._csettings.on_chunk_header = cb_on_chunk_header - * self._csettings.on_chunk_complete = cb_on_chunk_complete - */ - __pyx_v_self->_csettings->on_message_complete = __pyx_f_7aiohttp_12_http_parser_cb_on_message_complete; - - /* "aiohttp/_http_parser.pyx":372 - * self._csettings.on_message_begin = cb_on_message_begin - * self._csettings.on_message_complete = cb_on_message_complete - * self._csettings.on_chunk_header = cb_on_chunk_header # <<<<<<<<<<<<<< - * self._csettings.on_chunk_complete = cb_on_chunk_complete - * - */ - __pyx_v_self->_csettings->on_chunk_header = __pyx_f_7aiohttp_12_http_parser_cb_on_chunk_header; - - /* "aiohttp/_http_parser.pyx":373 - * self._csettings.on_message_complete = cb_on_message_complete - * self._csettings.on_chunk_header = cb_on_chunk_header - * self._csettings.on_chunk_complete = cb_on_chunk_complete # <<<<<<<<<<<<<< - * - * self._last_error = None - */ - __pyx_v_self->_csettings->on_chunk_complete = __pyx_f_7aiohttp_12_http_parser_cb_on_chunk_complete; - - /* "aiohttp/_http_parser.pyx":375 - * self._csettings.on_chunk_complete = cb_on_chunk_complete - * - * self._last_error = None # <<<<<<<<<<<<<< - * self._limit = limit - * - */ - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - __Pyx_GOTREF(__pyx_v_self->_last_error); - __Pyx_DECREF(__pyx_v_self->_last_error); - __pyx_v_self->_last_error = Py_None; - - /* "aiohttp/_http_parser.pyx":376 - * - * self._last_error = None - * self._limit = limit # <<<<<<<<<<<<<< - * - * cdef _process_header(self): - */ - __pyx_v_self->_limit = __pyx_v_limit; - - /* "aiohttp/_http_parser.pyx":327 - * PyMem_Free(self._csettings) - * - * cdef _init( # <<<<<<<<<<<<<< - * self, cparser.llhttp_type mode, - * object protocol, object loop, int limit, - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._http_parser.HttpParser._init", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":378 - * self._limit = limit - * - * cdef _process_header(self): # <<<<<<<<<<<<<< - * if self._raw_name: - * raw_name = bytes(self._raw_name) - */ - -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__process_header(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self) { - PyObject *__pyx_v_raw_name = NULL; - PyObject *__pyx_v_raw_value = NULL; - PyObject *__pyx_v_name = NULL; - PyObject *__pyx_v_value = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - PyObject *__pyx_t_6 = NULL; - int __pyx_t_7; - int __pyx_t_8; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_process_header", 0); - - /* "aiohttp/_http_parser.pyx":379 - * - * cdef _process_header(self): - * if self._raw_name: # <<<<<<<<<<<<<< - * raw_name = bytes(self._raw_name) - * raw_value = bytes(self._raw_value) - */ - __pyx_t_1 = (__pyx_v_self->_raw_name != Py_None)&&(PyByteArray_GET_SIZE(__pyx_v_self->_raw_name) != 0); - if (__pyx_t_1) { - - /* "aiohttp/_http_parser.pyx":380 - * cdef _process_header(self): - * if self._raw_name: - * raw_name = bytes(self._raw_name) # <<<<<<<<<<<<<< - * raw_value = bytes(self._raw_value) - * - */ - __pyx_t_2 = __Pyx_PyObject_CallOneArg(((PyObject *)(&PyBytes_Type)), __pyx_v_self->_raw_name); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 380, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_v_raw_name = ((PyObject*)__pyx_t_2); - __pyx_t_2 = 0; - - /* "aiohttp/_http_parser.pyx":381 - * if self._raw_name: - * raw_name = bytes(self._raw_name) - * raw_value = bytes(self._raw_value) # <<<<<<<<<<<<<< - * - * name = find_header(raw_name) - */ - __pyx_t_2 = __Pyx_PyObject_CallOneArg(((PyObject *)(&PyBytes_Type)), __pyx_v_self->_raw_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 381, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_v_raw_value = ((PyObject*)__pyx_t_2); - __pyx_t_2 = 0; - - /* "aiohttp/_http_parser.pyx":383 - * raw_value = bytes(self._raw_value) - * - * name = find_header(raw_name) # <<<<<<<<<<<<<< - * value = raw_value.decode('utf-8', 'surrogateescape') - * - */ - __pyx_t_2 = __pyx_f_7aiohttp_12_http_parser_find_header(__pyx_v_raw_name); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 383, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_v_name = __pyx_t_2; - __pyx_t_2 = 0; - - /* "aiohttp/_http_parser.pyx":384 - * - * name = find_header(raw_name) - * value = raw_value.decode('utf-8', 'surrogateescape') # <<<<<<<<<<<<<< - * - * self._headers.add(name, value) - */ - __pyx_t_2 = __Pyx_decode_bytes(__pyx_v_raw_value, 0, PY_SSIZE_T_MAX, NULL, ((char const *)"surrogateescape"), PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 384, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_v_value = __pyx_t_2; - __pyx_t_2 = 0; - - /* "aiohttp/_http_parser.pyx":386 - * value = raw_value.decode('utf-8', 'surrogateescape') - * - * self._headers.add(name, value) # <<<<<<<<<<<<<< - * - * if name is CONTENT_ENCODING: - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_self->_headers, __pyx_n_s_add); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 386, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = NULL; - __pyx_t_5 = 0; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - __pyx_t_5 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[3] = {__pyx_t_4, __pyx_v_name, __pyx_v_value}; - __pyx_t_2 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_5, 2+__pyx_t_5); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 386, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_GOTREF(__pyx_t_2); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[3] = {__pyx_t_4, __pyx_v_name, __pyx_v_value}; - __pyx_t_2 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_5, 2+__pyx_t_5); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 386, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_GOTREF(__pyx_t_2); - } else - #endif - { - __pyx_t_6 = PyTuple_New(2+__pyx_t_5); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 386, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - if (__pyx_t_4) { - __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_4); __pyx_t_4 = NULL; - } - __Pyx_INCREF(__pyx_v_name); - __Pyx_GIVEREF(__pyx_v_name); - PyTuple_SET_ITEM(__pyx_t_6, 0+__pyx_t_5, __pyx_v_name); - __Pyx_INCREF(__pyx_v_value); - __Pyx_GIVEREF(__pyx_v_value); - PyTuple_SET_ITEM(__pyx_t_6, 1+__pyx_t_5, __pyx_v_value); - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_6, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 386, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_http_parser.pyx":388 - * self._headers.add(name, value) - * - * if name is CONTENT_ENCODING: # <<<<<<<<<<<<<< - * self._content_encoding = value - * - */ - __pyx_t_1 = (__pyx_v_name == __pyx_v_7aiohttp_12_http_parser_CONTENT_ENCODING); - __pyx_t_7 = (__pyx_t_1 != 0); - if (__pyx_t_7) { - - /* "aiohttp/_http_parser.pyx":389 - * - * if name is CONTENT_ENCODING: - * self._content_encoding = value # <<<<<<<<<<<<<< - * - * PyByteArray_Resize(self._raw_name, 0) - */ - if (!(likely(PyUnicode_CheckExact(__pyx_v_value))||((__pyx_v_value) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "unicode", Py_TYPE(__pyx_v_value)->tp_name), 0))) __PYX_ERR(0, 389, __pyx_L1_error) - __pyx_t_2 = __pyx_v_value; - __Pyx_INCREF(__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __Pyx_GOTREF(__pyx_v_self->_content_encoding); - __Pyx_DECREF(__pyx_v_self->_content_encoding); - __pyx_v_self->_content_encoding = ((PyObject*)__pyx_t_2); - __pyx_t_2 = 0; - - /* "aiohttp/_http_parser.pyx":388 - * self._headers.add(name, value) - * - * if name is CONTENT_ENCODING: # <<<<<<<<<<<<<< - * self._content_encoding = value - * - */ - } - - /* "aiohttp/_http_parser.pyx":391 - * self._content_encoding = value - * - * PyByteArray_Resize(self._raw_name, 0) # <<<<<<<<<<<<<< - * PyByteArray_Resize(self._raw_value, 0) - * self._has_value = False - */ - __pyx_t_2 = __pyx_v_self->_raw_name; - __Pyx_INCREF(__pyx_t_2); - __pyx_t_5 = PyByteArray_Resize(__pyx_t_2, 0); if (unlikely(__pyx_t_5 == ((int)-1))) __PYX_ERR(0, 391, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_http_parser.pyx":392 - * - * PyByteArray_Resize(self._raw_name, 0) - * PyByteArray_Resize(self._raw_value, 0) # <<<<<<<<<<<<<< - * self._has_value = False - * self._raw_headers.append((raw_name, raw_value)) - */ - __pyx_t_2 = __pyx_v_self->_raw_value; - __Pyx_INCREF(__pyx_t_2); - __pyx_t_5 = PyByteArray_Resize(__pyx_t_2, 0); if (unlikely(__pyx_t_5 == ((int)-1))) __PYX_ERR(0, 392, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_http_parser.pyx":393 - * PyByteArray_Resize(self._raw_name, 0) - * PyByteArray_Resize(self._raw_value, 0) - * self._has_value = False # <<<<<<<<<<<<<< - * self._raw_headers.append((raw_name, raw_value)) - * - */ - __pyx_v_self->_has_value = 0; - - /* "aiohttp/_http_parser.pyx":394 - * PyByteArray_Resize(self._raw_value, 0) - * self._has_value = False - * self._raw_headers.append((raw_name, raw_value)) # <<<<<<<<<<<<<< - * - * cdef _on_header_field(self, char* at, size_t length): - */ - if (unlikely(__pyx_v_self->_raw_headers == Py_None)) { - PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "append"); - __PYX_ERR(0, 394, __pyx_L1_error) - } - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 394, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_raw_name); - __Pyx_GIVEREF(__pyx_v_raw_name); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_raw_name); - __Pyx_INCREF(__pyx_v_raw_value); - __Pyx_GIVEREF(__pyx_v_raw_value); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_v_raw_value); - __pyx_t_8 = __Pyx_PyList_Append(__pyx_v_self->_raw_headers, __pyx_t_2); if (unlikely(__pyx_t_8 == ((int)-1))) __PYX_ERR(0, 394, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_http_parser.pyx":379 - * - * cdef _process_header(self): - * if self._raw_name: # <<<<<<<<<<<<<< - * raw_name = bytes(self._raw_name) - * raw_value = bytes(self._raw_value) - */ - } - - /* "aiohttp/_http_parser.pyx":378 - * self._limit = limit - * - * cdef _process_header(self): # <<<<<<<<<<<<<< - * if self._raw_name: - * raw_name = bytes(self._raw_name) - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("aiohttp._http_parser.HttpParser._process_header", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_raw_name); - __Pyx_XDECREF(__pyx_v_raw_value); - __Pyx_XDECREF(__pyx_v_name); - __Pyx_XDECREF(__pyx_v_value); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":396 - * self._raw_headers.append((raw_name, raw_value)) - * - * cdef _on_header_field(self, char* at, size_t length): # <<<<<<<<<<<<<< - * cdef Py_ssize_t size - * cdef char *buf - */ - -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_header_field(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self, char *__pyx_v_at, size_t __pyx_v_length) { - Py_ssize_t __pyx_v_size; - char *__pyx_v_buf; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - Py_ssize_t __pyx_t_3; - int __pyx_t_4; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_on_header_field", 0); - - /* "aiohttp/_http_parser.pyx":399 - * cdef Py_ssize_t size - * cdef char *buf - * if self._has_value: # <<<<<<<<<<<<<< - * self._process_header() - * - */ - __pyx_t_1 = (__pyx_v_self->_has_value != 0); - if (__pyx_t_1) { - - /* "aiohttp/_http_parser.pyx":400 - * cdef char *buf - * if self._has_value: - * self._process_header() # <<<<<<<<<<<<<< - * - * size = PyByteArray_Size(self._raw_name) - */ - __pyx_t_2 = ((struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser *)__pyx_v_self->__pyx_vtab)->_process_header(__pyx_v_self); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 400, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_http_parser.pyx":399 - * cdef Py_ssize_t size - * cdef char *buf - * if self._has_value: # <<<<<<<<<<<<<< - * self._process_header() - * - */ - } - - /* "aiohttp/_http_parser.pyx":402 - * self._process_header() - * - * size = PyByteArray_Size(self._raw_name) # <<<<<<<<<<<<<< - * PyByteArray_Resize(self._raw_name, size + length) - * buf = PyByteArray_AsString(self._raw_name) - */ - __pyx_t_2 = __pyx_v_self->_raw_name; - __Pyx_INCREF(__pyx_t_2); - __pyx_t_3 = PyByteArray_Size(__pyx_t_2); if (unlikely(__pyx_t_3 == ((Py_ssize_t)-1L))) __PYX_ERR(0, 402, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v_size = __pyx_t_3; - - /* "aiohttp/_http_parser.pyx":403 - * - * size = PyByteArray_Size(self._raw_name) - * PyByteArray_Resize(self._raw_name, size + length) # <<<<<<<<<<<<<< - * buf = PyByteArray_AsString(self._raw_name) - * memcpy(buf + size, at, length) - */ - __pyx_t_2 = __pyx_v_self->_raw_name; - __Pyx_INCREF(__pyx_t_2); - __pyx_t_4 = PyByteArray_Resize(__pyx_t_2, (__pyx_v_size + __pyx_v_length)); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(0, 403, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_http_parser.pyx":404 - * size = PyByteArray_Size(self._raw_name) - * PyByteArray_Resize(self._raw_name, size + length) - * buf = PyByteArray_AsString(self._raw_name) # <<<<<<<<<<<<<< - * memcpy(buf + size, at, length) - * - */ - __pyx_t_2 = __pyx_v_self->_raw_name; - __Pyx_INCREF(__pyx_t_2); - __pyx_v_buf = PyByteArray_AsString(__pyx_t_2); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_http_parser.pyx":405 - * PyByteArray_Resize(self._raw_name, size + length) - * buf = PyByteArray_AsString(self._raw_name) - * memcpy(buf + size, at, length) # <<<<<<<<<<<<<< - * - * cdef _on_header_value(self, char* at, size_t length): - */ - (void)(memcpy((__pyx_v_buf + __pyx_v_size), __pyx_v_at, __pyx_v_length)); - - /* "aiohttp/_http_parser.pyx":396 - * self._raw_headers.append((raw_name, raw_value)) - * - * cdef _on_header_field(self, char* at, size_t length): # <<<<<<<<<<<<<< - * cdef Py_ssize_t size - * cdef char *buf - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("aiohttp._http_parser.HttpParser._on_header_field", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":407 - * memcpy(buf + size, at, length) - * - * cdef _on_header_value(self, char* at, size_t length): # <<<<<<<<<<<<<< - * cdef Py_ssize_t size - * cdef char *buf - */ - -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_header_value(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self, char *__pyx_v_at, size_t __pyx_v_length) { - Py_ssize_t __pyx_v_size; - char *__pyx_v_buf; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - int __pyx_t_3; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_on_header_value", 0); - - /* "aiohttp/_http_parser.pyx":411 - * cdef char *buf - * - * size = PyByteArray_Size(self._raw_value) # <<<<<<<<<<<<<< - * PyByteArray_Resize(self._raw_value, size + length) - * buf = PyByteArray_AsString(self._raw_value) - */ - __pyx_t_1 = __pyx_v_self->_raw_value; - __Pyx_INCREF(__pyx_t_1); - __pyx_t_2 = PyByteArray_Size(__pyx_t_1); if (unlikely(__pyx_t_2 == ((Py_ssize_t)-1L))) __PYX_ERR(0, 411, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_size = __pyx_t_2; - - /* "aiohttp/_http_parser.pyx":412 - * - * size = PyByteArray_Size(self._raw_value) - * PyByteArray_Resize(self._raw_value, size + length) # <<<<<<<<<<<<<< - * buf = PyByteArray_AsString(self._raw_value) - * memcpy(buf + size, at, length) - */ - __pyx_t_1 = __pyx_v_self->_raw_value; - __Pyx_INCREF(__pyx_t_1); - __pyx_t_3 = PyByteArray_Resize(__pyx_t_1, (__pyx_v_size + __pyx_v_length)); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(0, 412, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":413 - * size = PyByteArray_Size(self._raw_value) - * PyByteArray_Resize(self._raw_value, size + length) - * buf = PyByteArray_AsString(self._raw_value) # <<<<<<<<<<<<<< - * memcpy(buf + size, at, length) - * self._has_value = True - */ - __pyx_t_1 = __pyx_v_self->_raw_value; - __Pyx_INCREF(__pyx_t_1); - __pyx_v_buf = PyByteArray_AsString(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":414 - * PyByteArray_Resize(self._raw_value, size + length) - * buf = PyByteArray_AsString(self._raw_value) - * memcpy(buf + size, at, length) # <<<<<<<<<<<<<< - * self._has_value = True - * - */ - (void)(memcpy((__pyx_v_buf + __pyx_v_size), __pyx_v_at, __pyx_v_length)); - - /* "aiohttp/_http_parser.pyx":415 - * buf = PyByteArray_AsString(self._raw_value) - * memcpy(buf + size, at, length) - * self._has_value = True # <<<<<<<<<<<<<< - * - * cdef _on_headers_complete(self): - */ - __pyx_v_self->_has_value = 1; - - /* "aiohttp/_http_parser.pyx":407 - * memcpy(buf + size, at, length) - * - * cdef _on_header_value(self, char* at, size_t length): # <<<<<<<<<<<<<< - * cdef Py_ssize_t size - * cdef char *buf - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._http_parser.HttpParser._on_header_value", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":417 - * self._has_value = True - * - * cdef _on_headers_complete(self): # <<<<<<<<<<<<<< - * self._process_header() - * - */ - -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_headers_complete(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self) { - PyObject *__pyx_v_method = NULL; - int __pyx_v_should_close; - uint8_t __pyx_v_upgrade; - int __pyx_v_chunked; - PyObject *__pyx_v_raw_headers = NULL; - PyObject *__pyx_v_headers = NULL; - PyObject *__pyx_v_encoding = NULL; - PyObject *__pyx_v_enc = NULL; - PyObject *__pyx_v_msg = NULL; - PyObject *__pyx_v_payload = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - uint8_t __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - int __pyx_t_6; - PyObject *__pyx_t_7 = NULL; - int __pyx_t_8; - int __pyx_t_9; - int __pyx_t_10; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_on_headers_complete", 0); - - /* "aiohttp/_http_parser.pyx":418 - * - * cdef _on_headers_complete(self): - * self._process_header() # <<<<<<<<<<<<<< - * - * method = http_method_str(self._cparser.method) - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser *)__pyx_v_self->__pyx_vtab)->_process_header(__pyx_v_self); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 418, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":420 - * self._process_header() - * - * method = http_method_str(self._cparser.method) # <<<<<<<<<<<<<< - * should_close = not cparser.llhttp_should_keep_alive(self._cparser) - * upgrade = self._cparser.upgrade - */ - __pyx_t_1 = __pyx_f_7aiohttp_12_http_parser_http_method_str(__pyx_v_self->_cparser->method); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 420, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_method = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":421 - * - * method = http_method_str(self._cparser.method) - * should_close = not cparser.llhttp_should_keep_alive(self._cparser) # <<<<<<<<<<<<<< - * upgrade = self._cparser.upgrade - * chunked = self._cparser.flags & cparser.F_CHUNKED - */ - __pyx_v_should_close = (!(llhttp_should_keep_alive(__pyx_v_self->_cparser) != 0)); - - /* "aiohttp/_http_parser.pyx":422 - * method = http_method_str(self._cparser.method) - * should_close = not cparser.llhttp_should_keep_alive(self._cparser) - * upgrade = self._cparser.upgrade # <<<<<<<<<<<<<< - * chunked = self._cparser.flags & cparser.F_CHUNKED - * - */ - __pyx_t_2 = __pyx_v_self->_cparser->upgrade; - __pyx_v_upgrade = __pyx_t_2; - - /* "aiohttp/_http_parser.pyx":423 - * should_close = not cparser.llhttp_should_keep_alive(self._cparser) - * upgrade = self._cparser.upgrade - * chunked = self._cparser.flags & cparser.F_CHUNKED # <<<<<<<<<<<<<< - * - * raw_headers = tuple(self._raw_headers) - */ - __pyx_v_chunked = (__pyx_v_self->_cparser->flags & F_CHUNKED); - - /* "aiohttp/_http_parser.pyx":425 - * chunked = self._cparser.flags & cparser.F_CHUNKED - * - * raw_headers = tuple(self._raw_headers) # <<<<<<<<<<<<<< - * headers = CIMultiDictProxy(self._headers) - * - */ - if (unlikely(__pyx_v_self->_raw_headers == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - __PYX_ERR(0, 425, __pyx_L1_error) - } - __pyx_t_1 = PyList_AsTuple(__pyx_v_self->_raw_headers); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 425, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_raw_headers = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":426 - * - * raw_headers = tuple(self._raw_headers) - * headers = CIMultiDictProxy(self._headers) # <<<<<<<<<<<<<< - * - * if upgrade or self._cparser.method == 5: # cparser.CONNECT: - */ - __Pyx_INCREF(__pyx_v_7aiohttp_12_http_parser_CIMultiDictProxy); - __pyx_t_3 = __pyx_v_7aiohttp_12_http_parser_CIMultiDictProxy; __pyx_t_4 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - } - } - __pyx_t_1 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_4, __pyx_v_self->_headers) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_v_self->_headers); - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 426, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_headers = __pyx_t_1; - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":428 - * headers = CIMultiDictProxy(self._headers) - * - * if upgrade or self._cparser.method == 5: # cparser.CONNECT: # <<<<<<<<<<<<<< - * self._upgraded = True - * - */ - __pyx_t_6 = (__pyx_v_upgrade != 0); - if (!__pyx_t_6) { - } else { - __pyx_t_5 = __pyx_t_6; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_6 = ((__pyx_v_self->_cparser->method == 5) != 0); - __pyx_t_5 = __pyx_t_6; - __pyx_L4_bool_binop_done:; - if (__pyx_t_5) { - - /* "aiohttp/_http_parser.pyx":429 - * - * if upgrade or self._cparser.method == 5: # cparser.CONNECT: - * self._upgraded = True # <<<<<<<<<<<<<< - * - * # do not support old websocket spec - */ - __pyx_v_self->_upgraded = 1; - - /* "aiohttp/_http_parser.pyx":428 - * headers = CIMultiDictProxy(self._headers) - * - * if upgrade or self._cparser.method == 5: # cparser.CONNECT: # <<<<<<<<<<<<<< - * self._upgraded = True - * - */ - } - - /* "aiohttp/_http_parser.pyx":432 - * - * # do not support old websocket spec - * if SEC_WEBSOCKET_KEY1 in headers: # <<<<<<<<<<<<<< - * raise InvalidHeader(SEC_WEBSOCKET_KEY1) - * - */ - __pyx_t_5 = (__Pyx_PySequence_ContainsTF(__pyx_v_7aiohttp_12_http_parser_SEC_WEBSOCKET_KEY1, __pyx_v_headers, Py_EQ)); if (unlikely(__pyx_t_5 < 0)) __PYX_ERR(0, 432, __pyx_L1_error) - __pyx_t_6 = (__pyx_t_5 != 0); - if (unlikely(__pyx_t_6)) { - - /* "aiohttp/_http_parser.pyx":433 - * # do not support old websocket spec - * if SEC_WEBSOCKET_KEY1 in headers: - * raise InvalidHeader(SEC_WEBSOCKET_KEY1) # <<<<<<<<<<<<<< - * - * encoding = None - */ - __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_InvalidHeader); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 433, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - } - } - __pyx_t_1 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_4, __pyx_v_7aiohttp_12_http_parser_SEC_WEBSOCKET_KEY1) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_v_7aiohttp_12_http_parser_SEC_WEBSOCKET_KEY1); - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 433, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(0, 433, __pyx_L1_error) - - /* "aiohttp/_http_parser.pyx":432 - * - * # do not support old websocket spec - * if SEC_WEBSOCKET_KEY1 in headers: # <<<<<<<<<<<<<< - * raise InvalidHeader(SEC_WEBSOCKET_KEY1) - * - */ - } - - /* "aiohttp/_http_parser.pyx":435 - * raise InvalidHeader(SEC_WEBSOCKET_KEY1) - * - * encoding = None # <<<<<<<<<<<<<< - * enc = self._content_encoding - * if enc is not None: - */ - __Pyx_INCREF(Py_None); - __pyx_v_encoding = Py_None; - - /* "aiohttp/_http_parser.pyx":436 - * - * encoding = None - * enc = self._content_encoding # <<<<<<<<<<<<<< - * if enc is not None: - * self._content_encoding = None - */ - __pyx_t_1 = __pyx_v_self->_content_encoding; - __Pyx_INCREF(__pyx_t_1); - __pyx_v_enc = __pyx_t_1; - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":437 - * encoding = None - * enc = self._content_encoding - * if enc is not None: # <<<<<<<<<<<<<< - * self._content_encoding = None - * enc = enc.lower() - */ - __pyx_t_6 = (__pyx_v_enc != Py_None); - __pyx_t_5 = (__pyx_t_6 != 0); - if (__pyx_t_5) { - - /* "aiohttp/_http_parser.pyx":438 - * enc = self._content_encoding - * if enc is not None: - * self._content_encoding = None # <<<<<<<<<<<<<< - * enc = enc.lower() - * if enc in ('gzip', 'deflate', 'br'): - */ - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - __Pyx_GOTREF(__pyx_v_self->_content_encoding); - __Pyx_DECREF(__pyx_v_self->_content_encoding); - __pyx_v_self->_content_encoding = ((PyObject*)Py_None); - - /* "aiohttp/_http_parser.pyx":439 - * if enc is not None: - * self._content_encoding = None - * enc = enc.lower() # <<<<<<<<<<<<<< - * if enc in ('gzip', 'deflate', 'br'): - * encoding = enc - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_enc, __pyx_n_s_lower); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 439, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - } - } - __pyx_t_1 = (__pyx_t_4) ? __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4) : __Pyx_PyObject_CallNoArg(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 439, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF_SET(__pyx_v_enc, __pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":440 - * self._content_encoding = None - * enc = enc.lower() - * if enc in ('gzip', 'deflate', 'br'): # <<<<<<<<<<<<<< - * encoding = enc - * - */ - __Pyx_INCREF(__pyx_v_enc); - __pyx_t_1 = __pyx_v_enc; - __pyx_t_6 = (__Pyx_PyUnicode_Equals(__pyx_t_1, __pyx_n_u_gzip, Py_EQ)); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 440, __pyx_L1_error) - if (!__pyx_t_6) { - } else { - __pyx_t_5 = __pyx_t_6; - goto __pyx_L9_bool_binop_done; - } - __pyx_t_6 = (__Pyx_PyUnicode_Equals(__pyx_t_1, __pyx_n_u_deflate, Py_EQ)); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 440, __pyx_L1_error) - if (!__pyx_t_6) { - } else { - __pyx_t_5 = __pyx_t_6; - goto __pyx_L9_bool_binop_done; - } - __pyx_t_6 = (__Pyx_PyUnicode_Equals(__pyx_t_1, __pyx_n_u_br, Py_EQ)); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 440, __pyx_L1_error) - __pyx_t_5 = __pyx_t_6; - __pyx_L9_bool_binop_done:; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_6 = (__pyx_t_5 != 0); - if (__pyx_t_6) { - - /* "aiohttp/_http_parser.pyx":441 - * enc = enc.lower() - * if enc in ('gzip', 'deflate', 'br'): - * encoding = enc # <<<<<<<<<<<<<< - * - * if self._cparser.type == cparser.HTTP_REQUEST: - */ - __Pyx_INCREF(__pyx_v_enc); - __Pyx_DECREF_SET(__pyx_v_encoding, __pyx_v_enc); - - /* "aiohttp/_http_parser.pyx":440 - * self._content_encoding = None - * enc = enc.lower() - * if enc in ('gzip', 'deflate', 'br'): # <<<<<<<<<<<<<< - * encoding = enc - * - */ - } - - /* "aiohttp/_http_parser.pyx":437 - * encoding = None - * enc = self._content_encoding - * if enc is not None: # <<<<<<<<<<<<<< - * self._content_encoding = None - * enc = enc.lower() - */ - } - - /* "aiohttp/_http_parser.pyx":443 - * encoding = enc - * - * if self._cparser.type == cparser.HTTP_REQUEST: # <<<<<<<<<<<<<< - * msg = _new_request_message( - * method, self._path, - */ - __pyx_t_6 = ((__pyx_v_self->_cparser->type == HTTP_REQUEST) != 0); - if (__pyx_t_6) { - - /* "aiohttp/_http_parser.pyx":445 - * if self._cparser.type == cparser.HTTP_REQUEST: - * msg = _new_request_message( - * method, self._path, # <<<<<<<<<<<<<< - * self.http_version(), headers, raw_headers, - * should_close, encoding, upgrade, chunked, self._url) - */ - __pyx_t_1 = __pyx_v_self->_path; - __Pyx_INCREF(__pyx_t_1); - - /* "aiohttp/_http_parser.pyx":446 - * msg = _new_request_message( - * method, self._path, - * self.http_version(), headers, raw_headers, # <<<<<<<<<<<<<< - * should_close, encoding, upgrade, chunked, self._url) - * else: - */ - __pyx_t_3 = __pyx_f_7aiohttp_12_http_parser_10HttpParser_http_version(__pyx_v_self); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 446, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - - /* "aiohttp/_http_parser.pyx":447 - * method, self._path, - * self.http_version(), headers, raw_headers, - * should_close, encoding, upgrade, chunked, self._url) # <<<<<<<<<<<<<< - * else: - * msg = _new_response_message( - */ - __pyx_t_4 = __pyx_v_self->_url; - __Pyx_INCREF(__pyx_t_4); - - /* "aiohttp/_http_parser.pyx":444 - * - * if self._cparser.type == cparser.HTTP_REQUEST: - * msg = _new_request_message( # <<<<<<<<<<<<<< - * method, self._path, - * self.http_version(), headers, raw_headers, - */ - __pyx_t_7 = __pyx_f_7aiohttp_12_http_parser__new_request_message(__pyx_v_method, ((PyObject*)__pyx_t_1), __pyx_t_3, __pyx_v_headers, __pyx_v_raw_headers, __pyx_v_should_close, __pyx_v_encoding, __pyx_v_upgrade, __pyx_v_chunked, __pyx_t_4); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 444, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_v_msg = __pyx_t_7; - __pyx_t_7 = 0; - - /* "aiohttp/_http_parser.pyx":443 - * encoding = enc - * - * if self._cparser.type == cparser.HTTP_REQUEST: # <<<<<<<<<<<<<< - * msg = _new_request_message( - * method, self._path, - */ - goto __pyx_L12; - } - - /* "aiohttp/_http_parser.pyx":449 - * should_close, encoding, upgrade, chunked, self._url) - * else: - * msg = _new_response_message( # <<<<<<<<<<<<<< - * self.http_version(), self._cparser.status_code, self._reason, - * headers, raw_headers, should_close, encoding, - */ - /*else*/ { - - /* "aiohttp/_http_parser.pyx":450 - * else: - * msg = _new_response_message( - * self.http_version(), self._cparser.status_code, self._reason, # <<<<<<<<<<<<<< - * headers, raw_headers, should_close, encoding, - * upgrade, chunked) - */ - __pyx_t_7 = __pyx_f_7aiohttp_12_http_parser_10HttpParser_http_version(__pyx_v_self); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 450, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_4 = __pyx_v_self->_reason; - __Pyx_INCREF(__pyx_t_4); - - /* "aiohttp/_http_parser.pyx":449 - * should_close, encoding, upgrade, chunked, self._url) - * else: - * msg = _new_response_message( # <<<<<<<<<<<<<< - * self.http_version(), self._cparser.status_code, self._reason, - * headers, raw_headers, should_close, encoding, - */ - __pyx_t_3 = __pyx_f_7aiohttp_12_http_parser__new_response_message(__pyx_t_7, __pyx_v_self->_cparser->status_code, ((PyObject*)__pyx_t_4), __pyx_v_headers, __pyx_v_raw_headers, __pyx_v_should_close, __pyx_v_encoding, __pyx_v_upgrade, __pyx_v_chunked); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 449, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_v_msg = __pyx_t_3; - __pyx_t_3 = 0; - } - __pyx_L12:; - - /* "aiohttp/_http_parser.pyx":455 - * - * if ( - * ULLONG_MAX > self._cparser.content_length > 0 or chunked or # <<<<<<<<<<<<<< - * self._cparser.method == 5 or # CONNECT: 5 - * (self._cparser.status_code >= 199 and - */ - __pyx_t_5 = (ULLONG_MAX > __pyx_v_self->_cparser->content_length); - if (__pyx_t_5) { - __pyx_t_5 = (__pyx_v_self->_cparser->content_length > 0); - } - __pyx_t_8 = (__pyx_t_5 != 0); - if (!__pyx_t_8) { - } else { - __pyx_t_6 = __pyx_t_8; - goto __pyx_L14_bool_binop_done; - } - __pyx_t_8 = (__pyx_v_chunked != 0); - if (!__pyx_t_8) { - } else { - __pyx_t_6 = __pyx_t_8; - goto __pyx_L14_bool_binop_done; - } - - /* "aiohttp/_http_parser.pyx":456 - * if ( - * ULLONG_MAX > self._cparser.content_length > 0 or chunked or - * self._cparser.method == 5 or # CONNECT: 5 # <<<<<<<<<<<<<< - * (self._cparser.status_code >= 199 and - * self._cparser.content_length == 0 and - */ - __pyx_t_8 = ((__pyx_v_self->_cparser->method == 5) != 0); - if (!__pyx_t_8) { - } else { - __pyx_t_6 = __pyx_t_8; - goto __pyx_L14_bool_binop_done; - } - - /* "aiohttp/_http_parser.pyx":457 - * ULLONG_MAX > self._cparser.content_length > 0 or chunked or - * self._cparser.method == 5 or # CONNECT: 5 - * (self._cparser.status_code >= 199 and # <<<<<<<<<<<<<< - * self._cparser.content_length == 0 and - * self._read_until_eof) - */ - __pyx_t_8 = ((__pyx_v_self->_cparser->status_code >= 0xC7) != 0); - if (__pyx_t_8) { - } else { - __pyx_t_6 = __pyx_t_8; - goto __pyx_L14_bool_binop_done; - } - - /* "aiohttp/_http_parser.pyx":458 - * self._cparser.method == 5 or # CONNECT: 5 - * (self._cparser.status_code >= 199 and - * self._cparser.content_length == 0 and # <<<<<<<<<<<<<< - * self._read_until_eof) - * ): - */ - __pyx_t_8 = ((__pyx_v_self->_cparser->content_length == 0) != 0); - if (__pyx_t_8) { - } else { - __pyx_t_6 = __pyx_t_8; - goto __pyx_L14_bool_binop_done; - } - - /* "aiohttp/_http_parser.pyx":459 - * (self._cparser.status_code >= 199 and - * self._cparser.content_length == 0 and - * self._read_until_eof) # <<<<<<<<<<<<<< - * ): - * payload = StreamReader( - */ - __pyx_t_8 = (__pyx_v_self->_read_until_eof != 0); - __pyx_t_6 = __pyx_t_8; - __pyx_L14_bool_binop_done:; - - /* "aiohttp/_http_parser.pyx":454 - * upgrade, chunked) - * - * if ( # <<<<<<<<<<<<<< - * ULLONG_MAX > self._cparser.content_length > 0 or chunked or - * self._cparser.method == 5 or # CONNECT: 5 - */ - if (__pyx_t_6) { - - /* "aiohttp/_http_parser.pyx":461 - * self._read_until_eof) - * ): - * payload = StreamReader( # <<<<<<<<<<<<<< - * self._protocol, timer=self._timer, loop=self._loop, - * limit=self._limit) - */ - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 461, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_self->_protocol); - __Pyx_GIVEREF(__pyx_v_self->_protocol); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_self->_protocol); - - /* "aiohttp/_http_parser.pyx":462 - * ): - * payload = StreamReader( - * self._protocol, timer=self._timer, loop=self._loop, # <<<<<<<<<<<<<< - * limit=self._limit) - * else: - */ - __pyx_t_4 = __Pyx_PyDict_NewPresized(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 462, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_timer, __pyx_v_self->_timer) < 0) __PYX_ERR(0, 462, __pyx_L1_error) - if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_loop, __pyx_v_self->_loop) < 0) __PYX_ERR(0, 462, __pyx_L1_error) - - /* "aiohttp/_http_parser.pyx":463 - * payload = StreamReader( - * self._protocol, timer=self._timer, loop=self._loop, - * limit=self._limit) # <<<<<<<<<<<<<< - * else: - * payload = EMPTY_PAYLOAD - */ - __pyx_t_7 = __Pyx_PyInt_From_int(__pyx_v_self->_limit); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 463, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_limit, __pyx_t_7) < 0) __PYX_ERR(0, 462, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - - /* "aiohttp/_http_parser.pyx":461 - * self._read_until_eof) - * ): - * payload = StreamReader( # <<<<<<<<<<<<<< - * self._protocol, timer=self._timer, loop=self._loop, - * limit=self._limit) - */ - __pyx_t_7 = __Pyx_PyObject_Call(__pyx_v_7aiohttp_12_http_parser_StreamReader, __pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 461, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_v_payload = __pyx_t_7; - __pyx_t_7 = 0; - - /* "aiohttp/_http_parser.pyx":454 - * upgrade, chunked) - * - * if ( # <<<<<<<<<<<<<< - * ULLONG_MAX > self._cparser.content_length > 0 or chunked or - * self._cparser.method == 5 or # CONNECT: 5 - */ - goto __pyx_L13; - } - - /* "aiohttp/_http_parser.pyx":465 - * limit=self._limit) - * else: - * payload = EMPTY_PAYLOAD # <<<<<<<<<<<<<< - * - * self._payload = payload - */ - /*else*/ { - __Pyx_INCREF(__pyx_v_7aiohttp_12_http_parser_EMPTY_PAYLOAD); - __pyx_v_payload = __pyx_v_7aiohttp_12_http_parser_EMPTY_PAYLOAD; - } - __pyx_L13:; - - /* "aiohttp/_http_parser.pyx":467 - * payload = EMPTY_PAYLOAD - * - * self._payload = payload # <<<<<<<<<<<<<< - * if encoding is not None and self._auto_decompress: - * self._payload = DeflateBuffer(payload, encoding) - */ - __Pyx_INCREF(__pyx_v_payload); - __Pyx_GIVEREF(__pyx_v_payload); - __Pyx_GOTREF(__pyx_v_self->_payload); - __Pyx_DECREF(__pyx_v_self->_payload); - __pyx_v_self->_payload = __pyx_v_payload; - - /* "aiohttp/_http_parser.pyx":468 - * - * self._payload = payload - * if encoding is not None and self._auto_decompress: # <<<<<<<<<<<<<< - * self._payload = DeflateBuffer(payload, encoding) - * - */ - __pyx_t_8 = (__pyx_v_encoding != Py_None); - __pyx_t_5 = (__pyx_t_8 != 0); - if (__pyx_t_5) { - } else { - __pyx_t_6 = __pyx_t_5; - goto __pyx_L21_bool_binop_done; - } - __pyx_t_5 = (__pyx_v_self->_auto_decompress != 0); - __pyx_t_6 = __pyx_t_5; - __pyx_L21_bool_binop_done:; - if (__pyx_t_6) { - - /* "aiohttp/_http_parser.pyx":469 - * self._payload = payload - * if encoding is not None and self._auto_decompress: - * self._payload = DeflateBuffer(payload, encoding) # <<<<<<<<<<<<<< - * - * if not self._response_with_body: - */ - __Pyx_INCREF(__pyx_v_7aiohttp_12_http_parser_DeflateBuffer); - __pyx_t_4 = __pyx_v_7aiohttp_12_http_parser_DeflateBuffer; __pyx_t_3 = NULL; - __pyx_t_9 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - __pyx_t_9 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_4)) { - PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_v_payload, __pyx_v_encoding}; - __pyx_t_7 = __Pyx_PyFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_9, 2+__pyx_t_9); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 469, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_7); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_4)) { - PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_v_payload, __pyx_v_encoding}; - __pyx_t_7 = __Pyx_PyCFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_9, 2+__pyx_t_9); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 469, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_7); - } else - #endif - { - __pyx_t_1 = PyTuple_New(2+__pyx_t_9); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 469, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (__pyx_t_3) { - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_3); __pyx_t_3 = NULL; - } - __Pyx_INCREF(__pyx_v_payload); - __Pyx_GIVEREF(__pyx_v_payload); - PyTuple_SET_ITEM(__pyx_t_1, 0+__pyx_t_9, __pyx_v_payload); - __Pyx_INCREF(__pyx_v_encoding); - __Pyx_GIVEREF(__pyx_v_encoding); - PyTuple_SET_ITEM(__pyx_t_1, 1+__pyx_t_9, __pyx_v_encoding); - __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_1, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 469, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_GIVEREF(__pyx_t_7); - __Pyx_GOTREF(__pyx_v_self->_payload); - __Pyx_DECREF(__pyx_v_self->_payload); - __pyx_v_self->_payload = __pyx_t_7; - __pyx_t_7 = 0; - - /* "aiohttp/_http_parser.pyx":468 - * - * self._payload = payload - * if encoding is not None and self._auto_decompress: # <<<<<<<<<<<<<< - * self._payload = DeflateBuffer(payload, encoding) - * - */ - } - - /* "aiohttp/_http_parser.pyx":471 - * self._payload = DeflateBuffer(payload, encoding) - * - * if not self._response_with_body: # <<<<<<<<<<<<<< - * payload = EMPTY_PAYLOAD - * - */ - __pyx_t_6 = ((!(__pyx_v_self->_response_with_body != 0)) != 0); - if (__pyx_t_6) { - - /* "aiohttp/_http_parser.pyx":472 - * - * if not self._response_with_body: - * payload = EMPTY_PAYLOAD # <<<<<<<<<<<<<< - * - * self._messages.append((msg, payload)) - */ - __Pyx_INCREF(__pyx_v_7aiohttp_12_http_parser_EMPTY_PAYLOAD); - __Pyx_DECREF_SET(__pyx_v_payload, __pyx_v_7aiohttp_12_http_parser_EMPTY_PAYLOAD); - - /* "aiohttp/_http_parser.pyx":471 - * self._payload = DeflateBuffer(payload, encoding) - * - * if not self._response_with_body: # <<<<<<<<<<<<<< - * payload = EMPTY_PAYLOAD - * - */ - } - - /* "aiohttp/_http_parser.pyx":474 - * payload = EMPTY_PAYLOAD - * - * self._messages.append((msg, payload)) # <<<<<<<<<<<<<< - * - * cdef _on_message_complete(self): - */ - if (unlikely(__pyx_v_self->_messages == Py_None)) { - PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "append"); - __PYX_ERR(0, 474, __pyx_L1_error) - } - __pyx_t_7 = PyTuple_New(2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 474, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_INCREF(__pyx_v_msg); - __Pyx_GIVEREF(__pyx_v_msg); - PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_v_msg); - __Pyx_INCREF(__pyx_v_payload); - __Pyx_GIVEREF(__pyx_v_payload); - PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_v_payload); - __pyx_t_10 = __Pyx_PyList_Append(__pyx_v_self->_messages, __pyx_t_7); if (unlikely(__pyx_t_10 == ((int)-1))) __PYX_ERR(0, 474, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - - /* "aiohttp/_http_parser.pyx":417 - * self._has_value = True - * - * cdef _on_headers_complete(self): # <<<<<<<<<<<<<< - * self._process_header() - * - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_AddTraceback("aiohttp._http_parser.HttpParser._on_headers_complete", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_method); - __Pyx_XDECREF(__pyx_v_raw_headers); - __Pyx_XDECREF(__pyx_v_headers); - __Pyx_XDECREF(__pyx_v_encoding); - __Pyx_XDECREF(__pyx_v_enc); - __Pyx_XDECREF(__pyx_v_msg); - __Pyx_XDECREF(__pyx_v_payload); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":476 - * self._messages.append((msg, payload)) - * - * cdef _on_message_complete(self): # <<<<<<<<<<<<<< - * self._payload.feed_eof() - * self._payload = None - */ - -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_message_complete(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_on_message_complete", 0); - - /* "aiohttp/_http_parser.pyx":477 - * - * cdef _on_message_complete(self): - * self._payload.feed_eof() # <<<<<<<<<<<<<< - * self._payload = None - * - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self->_payload, __pyx_n_s_feed_eof); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 477, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - __pyx_t_1 = (__pyx_t_3) ? __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3) : __Pyx_PyObject_CallNoArg(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 477, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":478 - * cdef _on_message_complete(self): - * self._payload.feed_eof() - * self._payload = None # <<<<<<<<<<<<<< - * - * cdef _on_chunk_header(self): - */ - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - __Pyx_GOTREF(__pyx_v_self->_payload); - __Pyx_DECREF(__pyx_v_self->_payload); - __pyx_v_self->_payload = Py_None; - - /* "aiohttp/_http_parser.pyx":476 - * self._messages.append((msg, payload)) - * - * cdef _on_message_complete(self): # <<<<<<<<<<<<<< - * self._payload.feed_eof() - * self._payload = None - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("aiohttp._http_parser.HttpParser._on_message_complete", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":480 - * self._payload = None - * - * cdef _on_chunk_header(self): # <<<<<<<<<<<<<< - * self._payload.begin_http_chunk_receiving() - * - */ - -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_chunk_header(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_on_chunk_header", 0); - - /* "aiohttp/_http_parser.pyx":481 - * - * cdef _on_chunk_header(self): - * self._payload.begin_http_chunk_receiving() # <<<<<<<<<<<<<< - * - * cdef _on_chunk_complete(self): - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self->_payload, __pyx_n_s_begin_http_chunk_receiving); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 481, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - __pyx_t_1 = (__pyx_t_3) ? __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3) : __Pyx_PyObject_CallNoArg(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 481, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":480 - * self._payload = None - * - * cdef _on_chunk_header(self): # <<<<<<<<<<<<<< - * self._payload.begin_http_chunk_receiving() - * - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("aiohttp._http_parser.HttpParser._on_chunk_header", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":483 - * self._payload.begin_http_chunk_receiving() - * - * cdef _on_chunk_complete(self): # <<<<<<<<<<<<<< - * self._payload.end_http_chunk_receiving() - * - */ - -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_chunk_complete(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_on_chunk_complete", 0); - - /* "aiohttp/_http_parser.pyx":484 - * - * cdef _on_chunk_complete(self): - * self._payload.end_http_chunk_receiving() # <<<<<<<<<<<<<< - * - * cdef object _on_status_complete(self): - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self->_payload, __pyx_n_s_end_http_chunk_receiving); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 484, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - __pyx_t_1 = (__pyx_t_3) ? __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3) : __Pyx_PyObject_CallNoArg(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 484, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":483 - * self._payload.begin_http_chunk_receiving() - * - * cdef _on_chunk_complete(self): # <<<<<<<<<<<<<< - * self._payload.end_http_chunk_receiving() - * - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("aiohttp._http_parser.HttpParser._on_chunk_complete", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":486 - * self._payload.end_http_chunk_receiving() - * - * cdef object _on_status_complete(self): # <<<<<<<<<<<<<< - * pass - * - */ - -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_status_complete(CYTHON_UNUSED struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_on_status_complete", 0); - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":489 - * pass - * - * cdef inline http_version(self): # <<<<<<<<<<<<<< - * cdef cparser.llhttp_t* parser = self._cparser - * - */ - -static CYTHON_INLINE PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser_http_version(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self) { - llhttp_t *__pyx_v_parser; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - llhttp_t *__pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - int __pyx_t_8; - PyObject *__pyx_t_9 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("http_version", 0); - - /* "aiohttp/_http_parser.pyx":490 - * - * cdef inline http_version(self): - * cdef cparser.llhttp_t* parser = self._cparser # <<<<<<<<<<<<<< - * - * if parser.http_major == 1: - */ - __pyx_t_1 = __pyx_v_self->_cparser; - __pyx_v_parser = __pyx_t_1; - - /* "aiohttp/_http_parser.pyx":492 - * cdef cparser.llhttp_t* parser = self._cparser - * - * if parser.http_major == 1: # <<<<<<<<<<<<<< - * if parser.http_minor == 0: - * return HttpVersion10 - */ - __pyx_t_2 = ((__pyx_v_parser->http_major == 1) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_http_parser.pyx":493 - * - * if parser.http_major == 1: - * if parser.http_minor == 0: # <<<<<<<<<<<<<< - * return HttpVersion10 - * elif parser.http_minor == 1: - */ - switch (__pyx_v_parser->http_minor) { - case 0: - - /* "aiohttp/_http_parser.pyx":494 - * if parser.http_major == 1: - * if parser.http_minor == 0: - * return HttpVersion10 # <<<<<<<<<<<<<< - * elif parser.http_minor == 1: - * return HttpVersion11 - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_7aiohttp_12_http_parser_HttpVersion10); - __pyx_r = __pyx_v_7aiohttp_12_http_parser_HttpVersion10; - goto __pyx_L0; - - /* "aiohttp/_http_parser.pyx":493 - * - * if parser.http_major == 1: - * if parser.http_minor == 0: # <<<<<<<<<<<<<< - * return HttpVersion10 - * elif parser.http_minor == 1: - */ - break; - case 1: - - /* "aiohttp/_http_parser.pyx":496 - * return HttpVersion10 - * elif parser.http_minor == 1: - * return HttpVersion11 # <<<<<<<<<<<<<< - * - * return HttpVersion(parser.http_major, parser.http_minor) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v_7aiohttp_12_http_parser_HttpVersion11); - __pyx_r = __pyx_v_7aiohttp_12_http_parser_HttpVersion11; - goto __pyx_L0; - - /* "aiohttp/_http_parser.pyx":495 - * if parser.http_minor == 0: - * return HttpVersion10 - * elif parser.http_minor == 1: # <<<<<<<<<<<<<< - * return HttpVersion11 - * - */ - break; - default: break; - } - - /* "aiohttp/_http_parser.pyx":492 - * cdef cparser.llhttp_t* parser = self._cparser - * - * if parser.http_major == 1: # <<<<<<<<<<<<<< - * if parser.http_minor == 0: - * return HttpVersion10 - */ - } - - /* "aiohttp/_http_parser.pyx":498 - * return HttpVersion11 - * - * return HttpVersion(parser.http_major, parser.http_minor) # <<<<<<<<<<<<<< - * - * ### Public API ### - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_4 = __Pyx_PyInt_From_uint8_t(__pyx_v_parser->http_major); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 498, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = __Pyx_PyInt_From_uint8_t(__pyx_v_parser->http_minor); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 498, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(__pyx_v_7aiohttp_12_http_parser_HttpVersion); - __pyx_t_6 = __pyx_v_7aiohttp_12_http_parser_HttpVersion; __pyx_t_7 = NULL; - __pyx_t_8 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_6))) { - __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_6); - if (likely(__pyx_t_7)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); - __Pyx_INCREF(__pyx_t_7); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_6, function); - __pyx_t_8 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_6)) { - PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_t_4, __pyx_t_5}; - __pyx_t_3 = __Pyx_PyFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 498, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_6)) { - PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_t_4, __pyx_t_5}; - __pyx_t_3 = __Pyx_PyCFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 498, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } else - #endif - { - __pyx_t_9 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 498, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - if (__pyx_t_7) { - __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_7); __pyx_t_7 = NULL; - } - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_9, 0+__pyx_t_8, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_9, 1+__pyx_t_8, __pyx_t_5); - __pyx_t_4 = 0; - __pyx_t_5 = 0; - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_9, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 498, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "aiohttp/_http_parser.pyx":489 - * pass - * - * cdef inline http_version(self): # <<<<<<<<<<<<<< - * cdef cparser.llhttp_t* parser = self._cparser - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_AddTraceback("aiohttp._http_parser.HttpParser.http_version", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":502 - * ### Public API ### - * - * def feed_eof(self): # <<<<<<<<<<<<<< - * cdef bytes desc - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_10HttpParser_5feed_eof(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_10HttpParser_5feed_eof(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("feed_eof (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_10HttpParser_4feed_eof(((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_10HttpParser_4feed_eof(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self) { - PyObject *__pyx_v_desc = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("feed_eof", 0); - - /* "aiohttp/_http_parser.pyx":505 - * cdef bytes desc - * - * if self._payload is not None: # <<<<<<<<<<<<<< - * if self._cparser.flags & cparser.F_CHUNKED: - * raise TransferEncodingError( - */ - __pyx_t_1 = (__pyx_v_self->_payload != Py_None); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "aiohttp/_http_parser.pyx":506 - * - * if self._payload is not None: - * if self._cparser.flags & cparser.F_CHUNKED: # <<<<<<<<<<<<<< - * raise TransferEncodingError( - * "Not enough data for satisfy transfer length header.") - */ - __pyx_t_2 = ((__pyx_v_self->_cparser->flags & F_CHUNKED) != 0); - if (unlikely(__pyx_t_2)) { - - /* "aiohttp/_http_parser.pyx":507 - * if self._payload is not None: - * if self._cparser.flags & cparser.F_CHUNKED: - * raise TransferEncodingError( # <<<<<<<<<<<<<< - * "Not enough data for satisfy transfer length header.") - * elif self._cparser.flags & cparser.F_CONTENT_LENGTH: - */ - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_TransferEncodingError); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 507, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - __pyx_t_3 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_5, __pyx_kp_u_Not_enough_data_for_satisfy_tran) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_kp_u_Not_enough_data_for_satisfy_tran); - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 507, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(0, 507, __pyx_L1_error) - - /* "aiohttp/_http_parser.pyx":506 - * - * if self._payload is not None: - * if self._cparser.flags & cparser.F_CHUNKED: # <<<<<<<<<<<<<< - * raise TransferEncodingError( - * "Not enough data for satisfy transfer length header.") - */ - } - - /* "aiohttp/_http_parser.pyx":509 - * raise TransferEncodingError( - * "Not enough data for satisfy transfer length header.") - * elif self._cparser.flags & cparser.F_CONTENT_LENGTH: # <<<<<<<<<<<<<< - * raise ContentLengthError( - * "Not enough data for satisfy content length header.") - */ - __pyx_t_2 = ((__pyx_v_self->_cparser->flags & F_CONTENT_LENGTH) != 0); - if (unlikely(__pyx_t_2)) { - - /* "aiohttp/_http_parser.pyx":510 - * "Not enough data for satisfy transfer length header.") - * elif self._cparser.flags & cparser.F_CONTENT_LENGTH: - * raise ContentLengthError( # <<<<<<<<<<<<<< - * "Not enough data for satisfy content length header.") - * elif cparser.llhttp_get_errno(self._cparser) != cparser.HPE_OK: - */ - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_ContentLengthError); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 510, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - __pyx_t_3 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_5, __pyx_kp_u_Not_enough_data_for_satisfy_cont) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_kp_u_Not_enough_data_for_satisfy_cont); - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 510, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(0, 510, __pyx_L1_error) - - /* "aiohttp/_http_parser.pyx":509 - * raise TransferEncodingError( - * "Not enough data for satisfy transfer length header.") - * elif self._cparser.flags & cparser.F_CONTENT_LENGTH: # <<<<<<<<<<<<<< - * raise ContentLengthError( - * "Not enough data for satisfy content length header.") - */ - } - - /* "aiohttp/_http_parser.pyx":512 - * raise ContentLengthError( - * "Not enough data for satisfy content length header.") - * elif cparser.llhttp_get_errno(self._cparser) != cparser.HPE_OK: # <<<<<<<<<<<<<< - * desc = cparser.llhttp_get_error_reason(self._cparser) - * raise PayloadEncodingError(desc.decode('latin-1')) - */ - __pyx_t_2 = ((llhttp_get_errno(__pyx_v_self->_cparser) != HPE_OK) != 0); - if (unlikely(__pyx_t_2)) { - - /* "aiohttp/_http_parser.pyx":513 - * "Not enough data for satisfy content length header.") - * elif cparser.llhttp_get_errno(self._cparser) != cparser.HPE_OK: - * desc = cparser.llhttp_get_error_reason(self._cparser) # <<<<<<<<<<<<<< - * raise PayloadEncodingError(desc.decode('latin-1')) - * else: - */ - __pyx_t_3 = __Pyx_PyBytes_FromString(llhttp_get_error_reason(__pyx_v_self->_cparser)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 513, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_v_desc = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_http_parser.pyx":514 - * elif cparser.llhttp_get_errno(self._cparser) != cparser.HPE_OK: - * desc = cparser.llhttp_get_error_reason(self._cparser) - * raise PayloadEncodingError(desc.decode('latin-1')) # <<<<<<<<<<<<<< - * else: - * self._payload.feed_eof() - */ - __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_PayloadEncodingError); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 514, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = __Pyx_decode_bytes(__pyx_v_desc, 0, PY_SSIZE_T_MAX, NULL, NULL, PyUnicode_DecodeLatin1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 514, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_6)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_6); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - __pyx_t_3 = (__pyx_t_6) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_6, __pyx_t_5) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 514, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(0, 514, __pyx_L1_error) - - /* "aiohttp/_http_parser.pyx":512 - * raise ContentLengthError( - * "Not enough data for satisfy content length header.") - * elif cparser.llhttp_get_errno(self._cparser) != cparser.HPE_OK: # <<<<<<<<<<<<<< - * desc = cparser.llhttp_get_error_reason(self._cparser) - * raise PayloadEncodingError(desc.decode('latin-1')) - */ - } - - /* "aiohttp/_http_parser.pyx":516 - * raise PayloadEncodingError(desc.decode('latin-1')) - * else: - * self._payload.feed_eof() # <<<<<<<<<<<<<< - * elif self._started: - * self._on_headers_complete() - */ - /*else*/ { - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self->_payload, __pyx_n_s_feed_eof); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 516, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - __pyx_t_3 = (__pyx_t_5) ? __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_5) : __Pyx_PyObject_CallNoArg(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 516, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } - - /* "aiohttp/_http_parser.pyx":505 - * cdef bytes desc - * - * if self._payload is not None: # <<<<<<<<<<<<<< - * if self._cparser.flags & cparser.F_CHUNKED: - * raise TransferEncodingError( - */ - goto __pyx_L3; - } - - /* "aiohttp/_http_parser.pyx":517 - * else: - * self._payload.feed_eof() - * elif self._started: # <<<<<<<<<<<<<< - * self._on_headers_complete() - * if self._messages: - */ - __pyx_t_2 = (__pyx_v_self->_started != 0); - if (__pyx_t_2) { - - /* "aiohttp/_http_parser.pyx":518 - * self._payload.feed_eof() - * elif self._started: - * self._on_headers_complete() # <<<<<<<<<<<<<< - * if self._messages: - * return self._messages[-1][0] - */ - __pyx_t_3 = ((struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser *)__pyx_v_self->__pyx_vtab)->_on_headers_complete(__pyx_v_self); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 518, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "aiohttp/_http_parser.pyx":519 - * elif self._started: - * self._on_headers_complete() - * if self._messages: # <<<<<<<<<<<<<< - * return self._messages[-1][0] - * - */ - __pyx_t_2 = (__pyx_v_self->_messages != Py_None)&&(PyList_GET_SIZE(__pyx_v_self->_messages) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_http_parser.pyx":520 - * self._on_headers_complete() - * if self._messages: - * return self._messages[-1][0] # <<<<<<<<<<<<<< - * - * def feed_data(self, data): - */ - __Pyx_XDECREF(__pyx_r); - if (unlikely(__pyx_v_self->_messages == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(0, 520, __pyx_L1_error) - } - __pyx_t_3 = __Pyx_GetItemInt_List(__pyx_v_self->_messages, -1L, long, 1, __Pyx_PyInt_From_long, 1, 1, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 520, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_GetItemInt(__pyx_t_3, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 520, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; - goto __pyx_L0; - - /* "aiohttp/_http_parser.pyx":519 - * elif self._started: - * self._on_headers_complete() - * if self._messages: # <<<<<<<<<<<<<< - * return self._messages[-1][0] - * - */ - } - - /* "aiohttp/_http_parser.pyx":517 - * else: - * self._payload.feed_eof() - * elif self._started: # <<<<<<<<<<<<<< - * self._on_headers_complete() - * if self._messages: - */ - } - __pyx_L3:; - - /* "aiohttp/_http_parser.pyx":502 - * ### Public API ### - * - * def feed_eof(self): # <<<<<<<<<<<<<< - * cdef bytes desc - * - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("aiohttp._http_parser.HttpParser.feed_eof", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_desc); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":522 - * return self._messages[-1][0] - * - * def feed_data(self, data): # <<<<<<<<<<<<<< - * cdef: - * size_t data_len - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_10HttpParser_7feed_data(PyObject *__pyx_v_self, PyObject *__pyx_v_data); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_10HttpParser_7feed_data(PyObject *__pyx_v_self, PyObject *__pyx_v_data) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("feed_data (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_10HttpParser_6feed_data(((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)__pyx_v_self), ((PyObject *)__pyx_v_data)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_10HttpParser_6feed_data(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self, PyObject *__pyx_v_data) { - size_t __pyx_v_data_len; - size_t __pyx_v_nb; - llhttp_errno_t __pyx_v_errno; - PyObject *__pyx_v_ex = NULL; - PyObject *__pyx_v_messages = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("feed_data", 0); - - /* "aiohttp/_http_parser.pyx":528 - * cdef cparser.llhttp_errno_t errno - * - * PyObject_GetBuffer(data, &self.py_buf, PyBUF_SIMPLE) # <<<<<<<<<<<<<< - * data_len = self.py_buf.len - * - */ - __pyx_t_1 = PyObject_GetBuffer(__pyx_v_data, (&__pyx_v_self->py_buf), PyBUF_SIMPLE); if (unlikely(__pyx_t_1 == ((int)-1))) __PYX_ERR(0, 528, __pyx_L1_error) - - /* "aiohttp/_http_parser.pyx":529 - * - * PyObject_GetBuffer(data, &self.py_buf, PyBUF_SIMPLE) - * data_len = self.py_buf.len # <<<<<<<<<<<<<< - * - * errno = cparser.llhttp_execute( - */ - __pyx_v_data_len = ((size_t)__pyx_v_self->py_buf.len); - - /* "aiohttp/_http_parser.pyx":531 - * data_len = self.py_buf.len - * - * errno = cparser.llhttp_execute( # <<<<<<<<<<<<<< - * self._cparser, - * self.py_buf.buf, - */ - __pyx_v_errno = llhttp_execute(__pyx_v_self->_cparser, ((char *)__pyx_v_self->py_buf.buf), __pyx_v_data_len); - - /* "aiohttp/_http_parser.pyx":536 - * data_len) - * - * if errno is cparser.HPE_PAUSED_UPGRADE: # <<<<<<<<<<<<<< - * cparser.llhttp_resume_after_upgrade(self._cparser) - * - */ - __pyx_t_2 = ((__pyx_v_errno == HPE_PAUSED_UPGRADE) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_http_parser.pyx":537 - * - * if errno is cparser.HPE_PAUSED_UPGRADE: - * cparser.llhttp_resume_after_upgrade(self._cparser) # <<<<<<<<<<<<<< - * - * nb = cparser.llhttp_get_error_pos(self._cparser) - self.py_buf.buf - */ - llhttp_resume_after_upgrade(__pyx_v_self->_cparser); - - /* "aiohttp/_http_parser.pyx":539 - * cparser.llhttp_resume_after_upgrade(self._cparser) - * - * nb = cparser.llhttp_get_error_pos(self._cparser) - self.py_buf.buf # <<<<<<<<<<<<<< - * - * PyBuffer_Release(&self.py_buf) - */ - __pyx_v_nb = (llhttp_get_error_pos(__pyx_v_self->_cparser) - ((char *)__pyx_v_self->py_buf.buf)); - - /* "aiohttp/_http_parser.pyx":536 - * data_len) - * - * if errno is cparser.HPE_PAUSED_UPGRADE: # <<<<<<<<<<<<<< - * cparser.llhttp_resume_after_upgrade(self._cparser) - * - */ - } - - /* "aiohttp/_http_parser.pyx":541 - * nb = cparser.llhttp_get_error_pos(self._cparser) - self.py_buf.buf - * - * PyBuffer_Release(&self.py_buf) # <<<<<<<<<<<<<< - * - * if errno not in (cparser.HPE_OK, cparser.HPE_PAUSED_UPGRADE): - */ - PyBuffer_Release((&__pyx_v_self->py_buf)); - - /* "aiohttp/_http_parser.pyx":543 - * PyBuffer_Release(&self.py_buf) - * - * if errno not in (cparser.HPE_OK, cparser.HPE_PAUSED_UPGRADE): # <<<<<<<<<<<<<< - * if self._payload_error == 0: - * if self._last_error is not None: - */ - switch (__pyx_v_errno) { - case HPE_OK: - case HPE_PAUSED_UPGRADE: - __pyx_t_2 = 0; - break; - default: - __pyx_t_2 = 1; - break; - } - __pyx_t_3 = (__pyx_t_2 != 0); - if (__pyx_t_3) { - - /* "aiohttp/_http_parser.pyx":544 - * - * if errno not in (cparser.HPE_OK, cparser.HPE_PAUSED_UPGRADE): - * if self._payload_error == 0: # <<<<<<<<<<<<<< - * if self._last_error is not None: - * ex = self._last_error - */ - __pyx_t_3 = ((__pyx_v_self->_payload_error == 0) != 0); - if (__pyx_t_3) { - - /* "aiohttp/_http_parser.pyx":545 - * if errno not in (cparser.HPE_OK, cparser.HPE_PAUSED_UPGRADE): - * if self._payload_error == 0: - * if self._last_error is not None: # <<<<<<<<<<<<<< - * ex = self._last_error - * self._last_error = None - */ - __pyx_t_3 = (__pyx_v_self->_last_error != Py_None); - __pyx_t_2 = (__pyx_t_3 != 0); - if (__pyx_t_2) { - - /* "aiohttp/_http_parser.pyx":546 - * if self._payload_error == 0: - * if self._last_error is not None: - * ex = self._last_error # <<<<<<<<<<<<<< - * self._last_error = None - * else: - */ - __pyx_t_4 = __pyx_v_self->_last_error; - __Pyx_INCREF(__pyx_t_4); - __pyx_v_ex = __pyx_t_4; - __pyx_t_4 = 0; - - /* "aiohttp/_http_parser.pyx":547 - * if self._last_error is not None: - * ex = self._last_error - * self._last_error = None # <<<<<<<<<<<<<< - * else: - * ex = parser_error_from_errno(self._cparser) - */ - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - __Pyx_GOTREF(__pyx_v_self->_last_error); - __Pyx_DECREF(__pyx_v_self->_last_error); - __pyx_v_self->_last_error = Py_None; - - /* "aiohttp/_http_parser.pyx":545 - * if errno not in (cparser.HPE_OK, cparser.HPE_PAUSED_UPGRADE): - * if self._payload_error == 0: - * if self._last_error is not None: # <<<<<<<<<<<<<< - * ex = self._last_error - * self._last_error = None - */ - goto __pyx_L6; - } - - /* "aiohttp/_http_parser.pyx":549 - * self._last_error = None - * else: - * ex = parser_error_from_errno(self._cparser) # <<<<<<<<<<<<<< - * self._payload = None - * raise ex - */ - /*else*/ { - __pyx_t_4 = __pyx_f_7aiohttp_12_http_parser_parser_error_from_errno(__pyx_v_self->_cparser); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 549, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_v_ex = __pyx_t_4; - __pyx_t_4 = 0; - } - __pyx_L6:; - - /* "aiohttp/_http_parser.pyx":550 - * else: - * ex = parser_error_from_errno(self._cparser) - * self._payload = None # <<<<<<<<<<<<<< - * raise ex - * - */ - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - __Pyx_GOTREF(__pyx_v_self->_payload); - __Pyx_DECREF(__pyx_v_self->_payload); - __pyx_v_self->_payload = Py_None; - - /* "aiohttp/_http_parser.pyx":551 - * ex = parser_error_from_errno(self._cparser) - * self._payload = None - * raise ex # <<<<<<<<<<<<<< - * - * if self._messages: - */ - __Pyx_Raise(__pyx_v_ex, 0, 0, 0); - __PYX_ERR(0, 551, __pyx_L1_error) - - /* "aiohttp/_http_parser.pyx":544 - * - * if errno not in (cparser.HPE_OK, cparser.HPE_PAUSED_UPGRADE): - * if self._payload_error == 0: # <<<<<<<<<<<<<< - * if self._last_error is not None: - * ex = self._last_error - */ - } - - /* "aiohttp/_http_parser.pyx":543 - * PyBuffer_Release(&self.py_buf) - * - * if errno not in (cparser.HPE_OK, cparser.HPE_PAUSED_UPGRADE): # <<<<<<<<<<<<<< - * if self._payload_error == 0: - * if self._last_error is not None: - */ - } - - /* "aiohttp/_http_parser.pyx":553 - * raise ex - * - * if self._messages: # <<<<<<<<<<<<<< - * messages = self._messages - * self._messages = [] - */ - __pyx_t_2 = (__pyx_v_self->_messages != Py_None)&&(PyList_GET_SIZE(__pyx_v_self->_messages) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_http_parser.pyx":554 - * - * if self._messages: - * messages = self._messages # <<<<<<<<<<<<<< - * self._messages = [] - * else: - */ - __pyx_t_4 = __pyx_v_self->_messages; - __Pyx_INCREF(__pyx_t_4); - __pyx_v_messages = __pyx_t_4; - __pyx_t_4 = 0; - - /* "aiohttp/_http_parser.pyx":555 - * if self._messages: - * messages = self._messages - * self._messages = [] # <<<<<<<<<<<<<< - * else: - * messages = () - */ - __pyx_t_4 = PyList_New(0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 555, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __Pyx_GOTREF(__pyx_v_self->_messages); - __Pyx_DECREF(__pyx_v_self->_messages); - __pyx_v_self->_messages = ((PyObject*)__pyx_t_4); - __pyx_t_4 = 0; - - /* "aiohttp/_http_parser.pyx":553 - * raise ex - * - * if self._messages: # <<<<<<<<<<<<<< - * messages = self._messages - * self._messages = [] - */ - goto __pyx_L7; - } - - /* "aiohttp/_http_parser.pyx":557 - * self._messages = [] - * else: - * messages = () # <<<<<<<<<<<<<< - * - * if self._upgraded: - */ - /*else*/ { - __Pyx_INCREF(__pyx_empty_tuple); - __pyx_v_messages = __pyx_empty_tuple; - } - __pyx_L7:; - - /* "aiohttp/_http_parser.pyx":559 - * messages = () - * - * if self._upgraded: # <<<<<<<<<<<<<< - * return messages, True, data[nb:] - * else: - */ - __pyx_t_2 = (__pyx_v_self->_upgraded != 0); - if (__pyx_t_2) { - - /* "aiohttp/_http_parser.pyx":560 - * - * if self._upgraded: - * return messages, True, data[nb:] # <<<<<<<<<<<<<< - * else: - * return messages, False, b'' - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_4 = __Pyx_PyObject_GetSlice(__pyx_v_data, __pyx_v_nb, 0, NULL, NULL, NULL, 1, 0, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 560, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 560, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(__pyx_v_messages); - __Pyx_GIVEREF(__pyx_v_messages); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_messages); - __Pyx_INCREF(Py_True); - __Pyx_GIVEREF(Py_True); - PyTuple_SET_ITEM(__pyx_t_5, 1, Py_True); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_4); - __pyx_t_4 = 0; - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - - /* "aiohttp/_http_parser.pyx":559 - * messages = () - * - * if self._upgraded: # <<<<<<<<<<<<<< - * return messages, True, data[nb:] - * else: - */ - } - - /* "aiohttp/_http_parser.pyx":562 - * return messages, True, data[nb:] - * else: - * return messages, False, b'' # <<<<<<<<<<<<<< - * - * def set_upgraded(self, val): - */ - /*else*/ { - __Pyx_XDECREF(__pyx_r); - __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 562, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_INCREF(__pyx_v_messages); - __Pyx_GIVEREF(__pyx_v_messages); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_messages); - __Pyx_INCREF(Py_False); - __Pyx_GIVEREF(Py_False); - PyTuple_SET_ITEM(__pyx_t_5, 1, Py_False); - __Pyx_INCREF(__pyx_kp_b__4); - __Pyx_GIVEREF(__pyx_kp_b__4); - PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_kp_b__4); - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; - } - - /* "aiohttp/_http_parser.pyx":522 - * return self._messages[-1][0] - * - * def feed_data(self, data): # <<<<<<<<<<<<<< - * cdef: - * size_t data_len - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("aiohttp._http_parser.HttpParser.feed_data", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_ex); - __Pyx_XDECREF(__pyx_v_messages); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":564 - * return messages, False, b'' - * - * def set_upgraded(self, val): # <<<<<<<<<<<<<< - * self._upgraded = val - * - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_10HttpParser_9set_upgraded(PyObject *__pyx_v_self, PyObject *__pyx_v_val); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_10HttpParser_9set_upgraded(PyObject *__pyx_v_self, PyObject *__pyx_v_val) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("set_upgraded (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_10HttpParser_8set_upgraded(((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)__pyx_v_self), ((PyObject *)__pyx_v_val)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_10HttpParser_8set_upgraded(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self, PyObject *__pyx_v_val) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("set_upgraded", 0); - - /* "aiohttp/_http_parser.pyx":565 - * - * def set_upgraded(self, val): - * self._upgraded = val # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_val); if (unlikely((__pyx_t_1 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 565, __pyx_L1_error) - __pyx_v_self->_upgraded = __pyx_t_1; - - /* "aiohttp/_http_parser.pyx":564 - * return messages, False, b'' - * - * def set_upgraded(self, val): # <<<<<<<<<<<<<< - * self._upgraded = val - * - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_AddTraceback("aiohttp._http_parser.HttpParser.set_upgraded", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_10HttpParser_11__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_10HttpParser_11__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_10HttpParser_10__reduce_cython__(((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_10HttpParser_10__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce_cython__", 0); - - /* "(tree fragment)":2 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(1, 2, __pyx_L1_error) - - /* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._http_parser.HttpParser.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":3 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_10HttpParser_13__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_10HttpParser_13__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_10HttpParser_12__setstate_cython__(((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_10HttpParser_12__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setstate_cython__", 0); - - /* "(tree fragment)":4 - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(1, 4, __pyx_L1_error) - - /* "(tree fragment)":3 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._http_parser.HttpParser.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":570 - * cdef class HttpRequestParser(HttpParser): - * - * def __init__( # <<<<<<<<<<<<<< - * self, protocol, loop, int limit, timer=None, - * size_t max_line_size=8190, size_t max_headers=32768, - */ - -/* Python wrapper */ -static int __pyx_pw_7aiohttp_12_http_parser_17HttpRequestParser_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pw_7aiohttp_12_http_parser_17HttpRequestParser_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_protocol = 0; - PyObject *__pyx_v_loop = 0; - int __pyx_v_limit; - PyObject *__pyx_v_timer = 0; - size_t __pyx_v_max_line_size; - size_t __pyx_v_max_headers; - size_t __pyx_v_max_field_size; - PyObject *__pyx_v_payload_exception = 0; - int __pyx_v_response_with_body; - int __pyx_v_read_until_eof; - int __pyx_v_auto_decompress; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_protocol,&__pyx_n_s_loop,&__pyx_n_s_limit,&__pyx_n_s_timer,&__pyx_n_s_max_line_size,&__pyx_n_s_max_headers,&__pyx_n_s_max_field_size,&__pyx_n_s_payload_exception,&__pyx_n_s_response_with_body,&__pyx_n_s_read_until_eof,&__pyx_n_s_auto_decompress,0}; - PyObject* values[11] = {0,0,0,0,0,0,0,0,0,0,0}; - - /* "aiohttp/_http_parser.pyx":571 - * - * def __init__( - * self, protocol, loop, int limit, timer=None, # <<<<<<<<<<<<<< - * size_t max_line_size=8190, size_t max_headers=32768, - * size_t max_field_size=8190, payload_exception=None, - */ - values[3] = ((PyObject *)Py_None); - - /* "aiohttp/_http_parser.pyx":573 - * self, protocol, loop, int limit, timer=None, - * size_t max_line_size=8190, size_t max_headers=32768, - * size_t max_field_size=8190, payload_exception=None, # <<<<<<<<<<<<<< - * bint response_with_body=True, bint read_until_eof=False, - * bint auto_decompress=True, - */ - values[7] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); - CYTHON_FALLTHROUGH; - case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); - CYTHON_FALLTHROUGH; - case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); - CYTHON_FALLTHROUGH; - case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); - CYTHON_FALLTHROUGH; - case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); - CYTHON_FALLTHROUGH; - case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); - CYTHON_FALLTHROUGH; - case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - CYTHON_FALLTHROUGH; - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - CYTHON_FALLTHROUGH; - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_protocol)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_loop)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__init__", 0, 3, 11, 1); __PYX_ERR(0, 570, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_limit)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__init__", 0, 3, 11, 2); __PYX_ERR(0, 570, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_timer); - if (value) { values[3] = value; kw_args--; } - } - CYTHON_FALLTHROUGH; - case 4: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_max_line_size); - if (value) { values[4] = value; kw_args--; } - } - CYTHON_FALLTHROUGH; - case 5: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_max_headers); - if (value) { values[5] = value; kw_args--; } - } - CYTHON_FALLTHROUGH; - case 6: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_max_field_size); - if (value) { values[6] = value; kw_args--; } - } - CYTHON_FALLTHROUGH; - case 7: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_payload_exception); - if (value) { values[7] = value; kw_args--; } - } - CYTHON_FALLTHROUGH; - case 8: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_response_with_body); - if (value) { values[8] = value; kw_args--; } - } - CYTHON_FALLTHROUGH; - case 9: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_read_until_eof); - if (value) { values[9] = value; kw_args--; } - } - CYTHON_FALLTHROUGH; - case 10: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_auto_decompress); - if (value) { values[10] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) __PYX_ERR(0, 570, __pyx_L3_error) - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); - CYTHON_FALLTHROUGH; - case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); - CYTHON_FALLTHROUGH; - case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); - CYTHON_FALLTHROUGH; - case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); - CYTHON_FALLTHROUGH; - case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); - CYTHON_FALLTHROUGH; - case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); - CYTHON_FALLTHROUGH; - case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - CYTHON_FALLTHROUGH; - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - CYTHON_FALLTHROUGH; - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_protocol = values[0]; - __pyx_v_loop = values[1]; - __pyx_v_limit = __Pyx_PyInt_As_int(values[2]); if (unlikely((__pyx_v_limit == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 571, __pyx_L3_error) - __pyx_v_timer = values[3]; - if (values[4]) { - __pyx_v_max_line_size = __Pyx_PyInt_As_size_t(values[4]); if (unlikely((__pyx_v_max_line_size == (size_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 572, __pyx_L3_error) - } else { - __pyx_v_max_line_size = ((size_t)0x1FFE); - } - if (values[5]) { - __pyx_v_max_headers = __Pyx_PyInt_As_size_t(values[5]); if (unlikely((__pyx_v_max_headers == (size_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 572, __pyx_L3_error) - } else { - __pyx_v_max_headers = ((size_t)0x8000); - } - if (values[6]) { - __pyx_v_max_field_size = __Pyx_PyInt_As_size_t(values[6]); if (unlikely((__pyx_v_max_field_size == (size_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 573, __pyx_L3_error) - } else { - __pyx_v_max_field_size = ((size_t)0x1FFE); - } - __pyx_v_payload_exception = values[7]; - if (values[8]) { - __pyx_v_response_with_body = __Pyx_PyObject_IsTrue(values[8]); if (unlikely((__pyx_v_response_with_body == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 574, __pyx_L3_error) - } else { - - /* "aiohttp/_http_parser.pyx":574 - * size_t max_line_size=8190, size_t max_headers=32768, - * size_t max_field_size=8190, payload_exception=None, - * bint response_with_body=True, bint read_until_eof=False, # <<<<<<<<<<<<<< - * bint auto_decompress=True, - * ): - */ - __pyx_v_response_with_body = ((int)1); - } - if (values[9]) { - __pyx_v_read_until_eof = __Pyx_PyObject_IsTrue(values[9]); if (unlikely((__pyx_v_read_until_eof == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 574, __pyx_L3_error) - } else { - __pyx_v_read_until_eof = ((int)0); - } - if (values[10]) { - __pyx_v_auto_decompress = __Pyx_PyObject_IsTrue(values[10]); if (unlikely((__pyx_v_auto_decompress == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 575, __pyx_L3_error) - } else { - - /* "aiohttp/_http_parser.pyx":575 - * size_t max_field_size=8190, payload_exception=None, - * bint response_with_body=True, bint read_until_eof=False, - * bint auto_decompress=True, # <<<<<<<<<<<<<< - * ): - * self._init(cparser.HTTP_REQUEST, protocol, loop, limit, timer, - */ - __pyx_v_auto_decompress = ((int)1); - } - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__init__", 0, 3, 11, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 570, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._http_parser.HttpRequestParser.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_17HttpRequestParser___init__(((struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParser *)__pyx_v_self), __pyx_v_protocol, __pyx_v_loop, __pyx_v_limit, __pyx_v_timer, __pyx_v_max_line_size, __pyx_v_max_headers, __pyx_v_max_field_size, __pyx_v_payload_exception, __pyx_v_response_with_body, __pyx_v_read_until_eof, __pyx_v_auto_decompress); - - /* "aiohttp/_http_parser.pyx":570 - * cdef class HttpRequestParser(HttpParser): - * - * def __init__( # <<<<<<<<<<<<<< - * self, protocol, loop, int limit, timer=None, - * size_t max_line_size=8190, size_t max_headers=32768, - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_7aiohttp_12_http_parser_17HttpRequestParser___init__(struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParser *__pyx_v_self, PyObject *__pyx_v_protocol, PyObject *__pyx_v_loop, int __pyx_v_limit, PyObject *__pyx_v_timer, size_t __pyx_v_max_line_size, size_t __pyx_v_max_headers, size_t __pyx_v_max_field_size, PyObject *__pyx_v_payload_exception, int __pyx_v_response_with_body, int __pyx_v_read_until_eof, int __pyx_v_auto_decompress) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - struct __pyx_opt_args_7aiohttp_12_http_parser_10HttpParser__init __pyx_t_2; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__init__", 0); - - /* "aiohttp/_http_parser.pyx":577 - * bint auto_decompress=True, - * ): - * self._init(cparser.HTTP_REQUEST, protocol, loop, limit, timer, # <<<<<<<<<<<<<< - * max_line_size, max_headers, max_field_size, - * payload_exception, response_with_body, read_until_eof, - */ - __pyx_t_2.__pyx_n = 8; - __pyx_t_2.timer = __pyx_v_timer; - __pyx_t_2.max_line_size = __pyx_v_max_line_size; - __pyx_t_2.max_headers = __pyx_v_max_headers; - __pyx_t_2.max_field_size = __pyx_v_max_field_size; - __pyx_t_2.payload_exception = __pyx_v_payload_exception; - __pyx_t_2.response_with_body = __pyx_v_response_with_body; - __pyx_t_2.read_until_eof = __pyx_v_read_until_eof; - __pyx_t_2.auto_decompress = __pyx_v_auto_decompress; - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpRequestParser *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base._init(((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)__pyx_v_self), HTTP_REQUEST, __pyx_v_protocol, __pyx_v_loop, __pyx_v_limit, &__pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 577, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":570 - * cdef class HttpRequestParser(HttpParser): - * - * def __init__( # <<<<<<<<<<<<<< - * self, protocol, loop, int limit, timer=None, - * size_t max_line_size=8190, size_t max_headers=32768, - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._http_parser.HttpRequestParser.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":582 - * auto_decompress) - * - * cdef object _on_status_complete(self): # <<<<<<<<<<<<<< - * cdef int idx1, idx2 - * if not self._buf: - */ - -static PyObject *__pyx_f_7aiohttp_12_http_parser_17HttpRequestParser__on_status_complete(struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParser *__pyx_v_self) { - int __pyx_v_idx1; - int __pyx_v_idx2; - CYTHON_UNUSED Py_ssize_t __pyx_v_idx3; - PyObject *__pyx_v_query = NULL; - PyObject *__pyx_v_path = NULL; - PyObject *__pyx_v_fragment = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - Py_ssize_t __pyx_t_4; - Py_ssize_t __pyx_t_5; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - int __pyx_t_8; - int __pyx_t_9; - char const *__pyx_t_10; - PyObject *__pyx_t_11 = NULL; - PyObject *__pyx_t_12 = NULL; - PyObject *__pyx_t_13 = NULL; - PyObject *__pyx_t_14 = NULL; - PyObject *__pyx_t_15 = NULL; - PyObject *__pyx_t_16 = NULL; - int __pyx_t_17; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_on_status_complete", 0); - - /* "aiohttp/_http_parser.pyx":584 - * cdef object _on_status_complete(self): - * cdef int idx1, idx2 - * if not self._buf: # <<<<<<<<<<<<<< - * return - * self._path = self._buf.decode('utf-8', 'surrogateescape') - */ - __pyx_t_1 = (__pyx_v_self->__pyx_base._buf != Py_None)&&(PyByteArray_GET_SIZE(__pyx_v_self->__pyx_base._buf) != 0); - __pyx_t_2 = ((!__pyx_t_1) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_http_parser.pyx":585 - * cdef int idx1, idx2 - * if not self._buf: - * return # <<<<<<<<<<<<<< - * self._path = self._buf.decode('utf-8', 'surrogateescape') - * try: - */ - __Pyx_XDECREF(__pyx_r); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - - /* "aiohttp/_http_parser.pyx":584 - * cdef object _on_status_complete(self): - * cdef int idx1, idx2 - * if not self._buf: # <<<<<<<<<<<<<< - * return - * self._path = self._buf.decode('utf-8', 'surrogateescape') - */ - } - - /* "aiohttp/_http_parser.pyx":586 - * if not self._buf: - * return - * self._path = self._buf.decode('utf-8', 'surrogateescape') # <<<<<<<<<<<<<< - * try: - * idx3 = len(self._path) - */ - if (unlikely(__pyx_v_self->__pyx_base._buf == Py_None)) { - PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "decode"); - __PYX_ERR(0, 586, __pyx_L1_error) - } - __pyx_t_3 = __Pyx_decode_bytearray(__pyx_v_self->__pyx_base._buf, 0, PY_SSIZE_T_MAX, NULL, ((char const *)"surrogateescape"), PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 586, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __Pyx_GOTREF(__pyx_v_self->__pyx_base._path); - __Pyx_DECREF(__pyx_v_self->__pyx_base._path); - __pyx_v_self->__pyx_base._path = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_http_parser.pyx":587 - * return - * self._path = self._buf.decode('utf-8', 'surrogateescape') - * try: # <<<<<<<<<<<<<< - * idx3 = len(self._path) - * idx1 = self._path.find("?") - */ - /*try:*/ { - - /* "aiohttp/_http_parser.pyx":588 - * self._path = self._buf.decode('utf-8', 'surrogateescape') - * try: - * idx3 = len(self._path) # <<<<<<<<<<<<<< - * idx1 = self._path.find("?") - * if idx1 == -1: - */ - __pyx_t_3 = __pyx_v_self->__pyx_base._path; - __Pyx_INCREF(__pyx_t_3); - if (unlikely(__pyx_t_3 == Py_None)) { - PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - __PYX_ERR(0, 588, __pyx_L5_error) - } - __pyx_t_4 = __Pyx_PyUnicode_GET_LENGTH(__pyx_t_3); if (unlikely(__pyx_t_4 == ((Py_ssize_t)-1))) __PYX_ERR(0, 588, __pyx_L5_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_idx3 = __pyx_t_4; - - /* "aiohttp/_http_parser.pyx":589 - * try: - * idx3 = len(self._path) - * idx1 = self._path.find("?") # <<<<<<<<<<<<<< - * if idx1 == -1: - * query = "" - */ - if (unlikely(__pyx_v_self->__pyx_base._path == Py_None)) { - PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "find"); - __PYX_ERR(0, 589, __pyx_L5_error) - } - __pyx_t_4 = PyUnicode_Find(__pyx_v_self->__pyx_base._path, __pyx_kp_u__7, 0, PY_SSIZE_T_MAX, 1); if (unlikely(__pyx_t_4 == ((Py_ssize_t)-2))) __PYX_ERR(0, 589, __pyx_L5_error) - __pyx_v_idx1 = __pyx_t_4; - - /* "aiohttp/_http_parser.pyx":590 - * idx3 = len(self._path) - * idx1 = self._path.find("?") - * if idx1 == -1: # <<<<<<<<<<<<<< - * query = "" - * idx2 = self._path.find("#") - */ - __pyx_t_2 = ((__pyx_v_idx1 == -1L) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_http_parser.pyx":591 - * idx1 = self._path.find("?") - * if idx1 == -1: - * query = "" # <<<<<<<<<<<<<< - * idx2 = self._path.find("#") - * if idx2 == -1: - */ - __Pyx_INCREF(__pyx_kp_u__4); - __pyx_v_query = __pyx_kp_u__4; - - /* "aiohttp/_http_parser.pyx":592 - * if idx1 == -1: - * query = "" - * idx2 = self._path.find("#") # <<<<<<<<<<<<<< - * if idx2 == -1: - * path = self._path - */ - if (unlikely(__pyx_v_self->__pyx_base._path == Py_None)) { - PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "find"); - __PYX_ERR(0, 592, __pyx_L5_error) - } - __pyx_t_4 = PyUnicode_Find(__pyx_v_self->__pyx_base._path, __pyx_kp_u__8, 0, PY_SSIZE_T_MAX, 1); if (unlikely(__pyx_t_4 == ((Py_ssize_t)-2))) __PYX_ERR(0, 592, __pyx_L5_error) - __pyx_v_idx2 = __pyx_t_4; - - /* "aiohttp/_http_parser.pyx":593 - * query = "" - * idx2 = self._path.find("#") - * if idx2 == -1: # <<<<<<<<<<<<<< - * path = self._path - * fragment = "" - */ - __pyx_t_2 = ((__pyx_v_idx2 == -1L) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_http_parser.pyx":594 - * idx2 = self._path.find("#") - * if idx2 == -1: - * path = self._path # <<<<<<<<<<<<<< - * fragment = "" - * else: - */ - __pyx_t_3 = __pyx_v_self->__pyx_base._path; - __Pyx_INCREF(__pyx_t_3); - __pyx_v_path = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_http_parser.pyx":595 - * if idx2 == -1: - * path = self._path - * fragment = "" # <<<<<<<<<<<<<< - * else: - * path = self._path[0: idx2] - */ - __Pyx_INCREF(__pyx_kp_u__4); - __pyx_v_fragment = __pyx_kp_u__4; - - /* "aiohttp/_http_parser.pyx":593 - * query = "" - * idx2 = self._path.find("#") - * if idx2 == -1: # <<<<<<<<<<<<<< - * path = self._path - * fragment = "" - */ - goto __pyx_L8; - } - - /* "aiohttp/_http_parser.pyx":597 - * fragment = "" - * else: - * path = self._path[0: idx2] # <<<<<<<<<<<<<< - * fragment = self._path[idx2+1:] - * - */ - /*else*/ { - if (unlikely(__pyx_v_self->__pyx_base._path == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(0, 597, __pyx_L5_error) - } - __pyx_t_3 = __Pyx_PyUnicode_Substring(__pyx_v_self->__pyx_base._path, 0, __pyx_v_idx2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 597, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_v_path = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_http_parser.pyx":598 - * else: - * path = self._path[0: idx2] - * fragment = self._path[idx2+1:] # <<<<<<<<<<<<<< - * - * else: - */ - if (unlikely(__pyx_v_self->__pyx_base._path == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(0, 598, __pyx_L5_error) - } - __pyx_t_3 = __Pyx_PyUnicode_Substring(__pyx_v_self->__pyx_base._path, (__pyx_v_idx2 + 1), PY_SSIZE_T_MAX); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 598, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_v_fragment = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - } - __pyx_L8:; - - /* "aiohttp/_http_parser.pyx":590 - * idx3 = len(self._path) - * idx1 = self._path.find("?") - * if idx1 == -1: # <<<<<<<<<<<<<< - * query = "" - * idx2 = self._path.find("#") - */ - goto __pyx_L7; - } - - /* "aiohttp/_http_parser.pyx":601 - * - * else: - * path = self._path[0:idx1] # <<<<<<<<<<<<<< - * idx1 += 1 - * idx2 = self._path.find("#", idx1+1) - */ - /*else*/ { - if (unlikely(__pyx_v_self->__pyx_base._path == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(0, 601, __pyx_L5_error) - } - __pyx_t_3 = __Pyx_PyUnicode_Substring(__pyx_v_self->__pyx_base._path, 0, __pyx_v_idx1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 601, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_v_path = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_http_parser.pyx":602 - * else: - * path = self._path[0:idx1] - * idx1 += 1 # <<<<<<<<<<<<<< - * idx2 = self._path.find("#", idx1+1) - * if idx2 == -1: - */ - __pyx_v_idx1 = (__pyx_v_idx1 + 1); - - /* "aiohttp/_http_parser.pyx":603 - * path = self._path[0:idx1] - * idx1 += 1 - * idx2 = self._path.find("#", idx1+1) # <<<<<<<<<<<<<< - * if idx2 == -1: - * query = self._path[idx1:] - */ - if (unlikely(__pyx_v_self->__pyx_base._path == Py_None)) { - PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "find"); - __PYX_ERR(0, 603, __pyx_L5_error) - } - __pyx_t_3 = __Pyx_PyInt_From_long((__pyx_v_idx1 + 1)); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 603, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyIndex_AsSsize_t(__pyx_t_3); if (unlikely((__pyx_t_4 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 603, __pyx_L5_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_5 = PyUnicode_Find(__pyx_v_self->__pyx_base._path, __pyx_kp_u__8, __pyx_t_4, PY_SSIZE_T_MAX, 1); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-2))) __PYX_ERR(0, 603, __pyx_L5_error) - __pyx_v_idx2 = __pyx_t_5; - - /* "aiohttp/_http_parser.pyx":604 - * idx1 += 1 - * idx2 = self._path.find("#", idx1+1) - * if idx2 == -1: # <<<<<<<<<<<<<< - * query = self._path[idx1:] - * fragment = "" - */ - __pyx_t_2 = ((__pyx_v_idx2 == -1L) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_http_parser.pyx":605 - * idx2 = self._path.find("#", idx1+1) - * if idx2 == -1: - * query = self._path[idx1:] # <<<<<<<<<<<<<< - * fragment = "" - * else: - */ - if (unlikely(__pyx_v_self->__pyx_base._path == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(0, 605, __pyx_L5_error) - } - __pyx_t_3 = __Pyx_PyUnicode_Substring(__pyx_v_self->__pyx_base._path, __pyx_v_idx1, PY_SSIZE_T_MAX); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 605, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_v_query = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_http_parser.pyx":606 - * if idx2 == -1: - * query = self._path[idx1:] - * fragment = "" # <<<<<<<<<<<<<< - * else: - * query = self._path[idx1: idx2] - */ - __Pyx_INCREF(__pyx_kp_u__4); - __pyx_v_fragment = __pyx_kp_u__4; - - /* "aiohttp/_http_parser.pyx":604 - * idx1 += 1 - * idx2 = self._path.find("#", idx1+1) - * if idx2 == -1: # <<<<<<<<<<<<<< - * query = self._path[idx1:] - * fragment = "" - */ - goto __pyx_L9; - } - - /* "aiohttp/_http_parser.pyx":608 - * fragment = "" - * else: - * query = self._path[idx1: idx2] # <<<<<<<<<<<<<< - * fragment = self._path[idx2+1:] - * - */ - /*else*/ { - if (unlikely(__pyx_v_self->__pyx_base._path == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(0, 608, __pyx_L5_error) - } - __pyx_t_3 = __Pyx_PyUnicode_Substring(__pyx_v_self->__pyx_base._path, __pyx_v_idx1, __pyx_v_idx2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 608, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_v_query = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_http_parser.pyx":609 - * else: - * query = self._path[idx1: idx2] - * fragment = self._path[idx2+1:] # <<<<<<<<<<<<<< - * - * self._url = URL.build( - */ - if (unlikely(__pyx_v_self->__pyx_base._path == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(0, 609, __pyx_L5_error) - } - __pyx_t_3 = __Pyx_PyUnicode_Substring(__pyx_v_self->__pyx_base._path, (__pyx_v_idx2 + 1), PY_SSIZE_T_MAX); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 609, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_v_fragment = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - } - __pyx_L9:; - } - __pyx_L7:; - - /* "aiohttp/_http_parser.pyx":611 - * fragment = self._path[idx2+1:] - * - * self._url = URL.build( # <<<<<<<<<<<<<< - * path=path, - * query_string=query, - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_7aiohttp_12_http_parser_URL, __pyx_n_s_build); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 611, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_3); - - /* "aiohttp/_http_parser.pyx":612 - * - * self._url = URL.build( - * path=path, # <<<<<<<<<<<<<< - * query_string=query, - * fragment=fragment, - */ - __pyx_t_6 = __Pyx_PyDict_NewPresized(4); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 612, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_6); - if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_path, __pyx_v_path) < 0) __PYX_ERR(0, 612, __pyx_L5_error) - - /* "aiohttp/_http_parser.pyx":613 - * self._url = URL.build( - * path=path, - * query_string=query, # <<<<<<<<<<<<<< - * fragment=fragment, - * encoded=True, - */ - if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_query_string, __pyx_v_query) < 0) __PYX_ERR(0, 612, __pyx_L5_error) - - /* "aiohttp/_http_parser.pyx":614 - * path=path, - * query_string=query, - * fragment=fragment, # <<<<<<<<<<<<<< - * encoded=True, - * ) - */ - if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_fragment, __pyx_v_fragment) < 0) __PYX_ERR(0, 612, __pyx_L5_error) - - /* "aiohttp/_http_parser.pyx":615 - * query_string=query, - * fragment=fragment, - * encoded=True, # <<<<<<<<<<<<<< - * ) - * finally: - */ - if (PyDict_SetItem(__pyx_t_6, __pyx_n_s_encoded, Py_True) < 0) __PYX_ERR(0, 612, __pyx_L5_error) - - /* "aiohttp/_http_parser.pyx":611 - * fragment = self._path[idx2+1:] - * - * self._url = URL.build( # <<<<<<<<<<<<<< - * path=path, - * query_string=query, - */ - __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_empty_tuple, __pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 611, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_GIVEREF(__pyx_t_7); - __Pyx_GOTREF(__pyx_v_self->__pyx_base._url); - __Pyx_DECREF(__pyx_v_self->__pyx_base._url); - __pyx_v_self->__pyx_base._url = __pyx_t_7; - __pyx_t_7 = 0; - } - - /* "aiohttp/_http_parser.pyx":618 - * ) - * finally: - * PyByteArray_Resize(self._buf, 0) # <<<<<<<<<<<<<< - * - * - */ - /*finally:*/ { - /*normal exit:*/{ - __pyx_t_7 = __pyx_v_self->__pyx_base._buf; - __Pyx_INCREF(__pyx_t_7); - __pyx_t_8 = PyByteArray_Resize(__pyx_t_7, 0); if (unlikely(__pyx_t_8 == ((int)-1))) __PYX_ERR(0, 618, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - goto __pyx_L6; - } - __pyx_L5_error:; - /*exception exit:*/{ - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __pyx_t_11 = 0; __pyx_t_12 = 0; __pyx_t_13 = 0; __pyx_t_14 = 0; __pyx_t_15 = 0; __pyx_t_16 = 0; - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_14, &__pyx_t_15, &__pyx_t_16); - if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_11, &__pyx_t_12, &__pyx_t_13) < 0)) __Pyx_ErrFetch(&__pyx_t_11, &__pyx_t_12, &__pyx_t_13); - __Pyx_XGOTREF(__pyx_t_11); - __Pyx_XGOTREF(__pyx_t_12); - __Pyx_XGOTREF(__pyx_t_13); - __Pyx_XGOTREF(__pyx_t_14); - __Pyx_XGOTREF(__pyx_t_15); - __Pyx_XGOTREF(__pyx_t_16); - __pyx_t_8 = __pyx_lineno; __pyx_t_9 = __pyx_clineno; __pyx_t_10 = __pyx_filename; - { - __pyx_t_7 = __pyx_v_self->__pyx_base._buf; - __Pyx_INCREF(__pyx_t_7); - __pyx_t_17 = PyByteArray_Resize(__pyx_t_7, 0); if (unlikely(__pyx_t_17 == ((int)-1))) __PYX_ERR(0, 618, __pyx_L11_error) - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } - if (PY_MAJOR_VERSION >= 3) { - __Pyx_XGIVEREF(__pyx_t_14); - __Pyx_XGIVEREF(__pyx_t_15); - __Pyx_XGIVEREF(__pyx_t_16); - __Pyx_ExceptionReset(__pyx_t_14, __pyx_t_15, __pyx_t_16); - } - __Pyx_XGIVEREF(__pyx_t_11); - __Pyx_XGIVEREF(__pyx_t_12); - __Pyx_XGIVEREF(__pyx_t_13); - __Pyx_ErrRestore(__pyx_t_11, __pyx_t_12, __pyx_t_13); - __pyx_t_11 = 0; __pyx_t_12 = 0; __pyx_t_13 = 0; __pyx_t_14 = 0; __pyx_t_15 = 0; __pyx_t_16 = 0; - __pyx_lineno = __pyx_t_8; __pyx_clineno = __pyx_t_9; __pyx_filename = __pyx_t_10; - goto __pyx_L1_error; - __pyx_L11_error:; - if (PY_MAJOR_VERSION >= 3) { - __Pyx_XGIVEREF(__pyx_t_14); - __Pyx_XGIVEREF(__pyx_t_15); - __Pyx_XGIVEREF(__pyx_t_16); - __Pyx_ExceptionReset(__pyx_t_14, __pyx_t_15, __pyx_t_16); - } - __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_XDECREF(__pyx_t_12); __pyx_t_12 = 0; - __Pyx_XDECREF(__pyx_t_13); __pyx_t_13 = 0; - __pyx_t_14 = 0; __pyx_t_15 = 0; __pyx_t_16 = 0; - goto __pyx_L1_error; - } - __pyx_L6:; - } - - /* "aiohttp/_http_parser.pyx":582 - * auto_decompress) - * - * cdef object _on_status_complete(self): # <<<<<<<<<<<<<< - * cdef int idx1, idx2 - * if not self._buf: - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_AddTraceback("aiohttp._http_parser.HttpRequestParser._on_status_complete", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_query); - __Pyx_XDECREF(__pyx_v_path); - __Pyx_XDECREF(__pyx_v_fragment); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17HttpRequestParser_3__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17HttpRequestParser_3__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_17HttpRequestParser_2__reduce_cython__(((struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParser *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_17HttpRequestParser_2__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParser *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce_cython__", 0); - - /* "(tree fragment)":2 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__9, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(1, 2, __pyx_L1_error) - - /* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._http_parser.HttpRequestParser.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":3 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17HttpRequestParser_5__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_17HttpRequestParser_5__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_17HttpRequestParser_4__setstate_cython__(((struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParser *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_17HttpRequestParser_4__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParser *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setstate_cython__", 0); - - /* "(tree fragment)":4 - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__10, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(1, 4, __pyx_L1_error) - - /* "(tree fragment)":3 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._http_parser.HttpRequestParser.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":623 - * cdef class HttpResponseParser(HttpParser): - * - * def __init__( # <<<<<<<<<<<<<< - * self, protocol, loop, int limit, timer=None, - * size_t max_line_size=8190, size_t max_headers=32768, - */ - -/* Python wrapper */ -static int __pyx_pw_7aiohttp_12_http_parser_18HttpResponseParser_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pw_7aiohttp_12_http_parser_18HttpResponseParser_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_protocol = 0; - PyObject *__pyx_v_loop = 0; - int __pyx_v_limit; - PyObject *__pyx_v_timer = 0; - size_t __pyx_v_max_line_size; - size_t __pyx_v_max_headers; - size_t __pyx_v_max_field_size; - PyObject *__pyx_v_payload_exception = 0; - int __pyx_v_response_with_body; - int __pyx_v_read_until_eof; - int __pyx_v_auto_decompress; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_protocol,&__pyx_n_s_loop,&__pyx_n_s_limit,&__pyx_n_s_timer,&__pyx_n_s_max_line_size,&__pyx_n_s_max_headers,&__pyx_n_s_max_field_size,&__pyx_n_s_payload_exception,&__pyx_n_s_response_with_body,&__pyx_n_s_read_until_eof,&__pyx_n_s_auto_decompress,0}; - PyObject* values[11] = {0,0,0,0,0,0,0,0,0,0,0}; - - /* "aiohttp/_http_parser.pyx":624 - * - * def __init__( - * self, protocol, loop, int limit, timer=None, # <<<<<<<<<<<<<< - * size_t max_line_size=8190, size_t max_headers=32768, - * size_t max_field_size=8190, payload_exception=None, - */ - values[3] = ((PyObject *)Py_None); - - /* "aiohttp/_http_parser.pyx":626 - * self, protocol, loop, int limit, timer=None, - * size_t max_line_size=8190, size_t max_headers=32768, - * size_t max_field_size=8190, payload_exception=None, # <<<<<<<<<<<<<< - * bint response_with_body=True, bint read_until_eof=False, - * bint auto_decompress=True - */ - values[7] = ((PyObject *)Py_None); - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); - CYTHON_FALLTHROUGH; - case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); - CYTHON_FALLTHROUGH; - case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); - CYTHON_FALLTHROUGH; - case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); - CYTHON_FALLTHROUGH; - case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); - CYTHON_FALLTHROUGH; - case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); - CYTHON_FALLTHROUGH; - case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - CYTHON_FALLTHROUGH; - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - CYTHON_FALLTHROUGH; - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_protocol)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_loop)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__init__", 0, 3, 11, 1); __PYX_ERR(0, 623, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_limit)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__init__", 0, 3, 11, 2); __PYX_ERR(0, 623, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 3: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_timer); - if (value) { values[3] = value; kw_args--; } - } - CYTHON_FALLTHROUGH; - case 4: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_max_line_size); - if (value) { values[4] = value; kw_args--; } - } - CYTHON_FALLTHROUGH; - case 5: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_max_headers); - if (value) { values[5] = value; kw_args--; } - } - CYTHON_FALLTHROUGH; - case 6: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_max_field_size); - if (value) { values[6] = value; kw_args--; } - } - CYTHON_FALLTHROUGH; - case 7: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_payload_exception); - if (value) { values[7] = value; kw_args--; } - } - CYTHON_FALLTHROUGH; - case 8: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_response_with_body); - if (value) { values[8] = value; kw_args--; } - } - CYTHON_FALLTHROUGH; - case 9: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_read_until_eof); - if (value) { values[9] = value; kw_args--; } - } - CYTHON_FALLTHROUGH; - case 10: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_auto_decompress); - if (value) { values[10] = value; kw_args--; } - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) __PYX_ERR(0, 623, __pyx_L3_error) - } - } else { - switch (PyTuple_GET_SIZE(__pyx_args)) { - case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); - CYTHON_FALLTHROUGH; - case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); - CYTHON_FALLTHROUGH; - case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); - CYTHON_FALLTHROUGH; - case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); - CYTHON_FALLTHROUGH; - case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); - CYTHON_FALLTHROUGH; - case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); - CYTHON_FALLTHROUGH; - case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); - CYTHON_FALLTHROUGH; - case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); - CYTHON_FALLTHROUGH; - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; - } - } - __pyx_v_protocol = values[0]; - __pyx_v_loop = values[1]; - __pyx_v_limit = __Pyx_PyInt_As_int(values[2]); if (unlikely((__pyx_v_limit == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 624, __pyx_L3_error) - __pyx_v_timer = values[3]; - if (values[4]) { - __pyx_v_max_line_size = __Pyx_PyInt_As_size_t(values[4]); if (unlikely((__pyx_v_max_line_size == (size_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 625, __pyx_L3_error) - } else { - __pyx_v_max_line_size = ((size_t)0x1FFE); - } - if (values[5]) { - __pyx_v_max_headers = __Pyx_PyInt_As_size_t(values[5]); if (unlikely((__pyx_v_max_headers == (size_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 625, __pyx_L3_error) - } else { - __pyx_v_max_headers = ((size_t)0x8000); - } - if (values[6]) { - __pyx_v_max_field_size = __Pyx_PyInt_As_size_t(values[6]); if (unlikely((__pyx_v_max_field_size == (size_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 626, __pyx_L3_error) - } else { - __pyx_v_max_field_size = ((size_t)0x1FFE); - } - __pyx_v_payload_exception = values[7]; - if (values[8]) { - __pyx_v_response_with_body = __Pyx_PyObject_IsTrue(values[8]); if (unlikely((__pyx_v_response_with_body == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 627, __pyx_L3_error) - } else { - - /* "aiohttp/_http_parser.pyx":627 - * size_t max_line_size=8190, size_t max_headers=32768, - * size_t max_field_size=8190, payload_exception=None, - * bint response_with_body=True, bint read_until_eof=False, # <<<<<<<<<<<<<< - * bint auto_decompress=True - * ): - */ - __pyx_v_response_with_body = ((int)1); - } - if (values[9]) { - __pyx_v_read_until_eof = __Pyx_PyObject_IsTrue(values[9]); if (unlikely((__pyx_v_read_until_eof == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 627, __pyx_L3_error) - } else { - __pyx_v_read_until_eof = ((int)0); - } - if (values[10]) { - __pyx_v_auto_decompress = __Pyx_PyObject_IsTrue(values[10]); if (unlikely((__pyx_v_auto_decompress == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 628, __pyx_L3_error) - } else { - - /* "aiohttp/_http_parser.pyx":628 - * size_t max_field_size=8190, payload_exception=None, - * bint response_with_body=True, bint read_until_eof=False, - * bint auto_decompress=True # <<<<<<<<<<<<<< - * ): - * self._init(cparser.HTTP_RESPONSE, protocol, loop, limit, timer, - */ - __pyx_v_auto_decompress = ((int)1); - } - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__init__", 0, 3, 11, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 623, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._http_parser.HttpResponseParser.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_18HttpResponseParser___init__(((struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParser *)__pyx_v_self), __pyx_v_protocol, __pyx_v_loop, __pyx_v_limit, __pyx_v_timer, __pyx_v_max_line_size, __pyx_v_max_headers, __pyx_v_max_field_size, __pyx_v_payload_exception, __pyx_v_response_with_body, __pyx_v_read_until_eof, __pyx_v_auto_decompress); - - /* "aiohttp/_http_parser.pyx":623 - * cdef class HttpResponseParser(HttpParser): - * - * def __init__( # <<<<<<<<<<<<<< - * self, protocol, loop, int limit, timer=None, - * size_t max_line_size=8190, size_t max_headers=32768, - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static int __pyx_pf_7aiohttp_12_http_parser_18HttpResponseParser___init__(struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParser *__pyx_v_self, PyObject *__pyx_v_protocol, PyObject *__pyx_v_loop, int __pyx_v_limit, PyObject *__pyx_v_timer, size_t __pyx_v_max_line_size, size_t __pyx_v_max_headers, size_t __pyx_v_max_field_size, PyObject *__pyx_v_payload_exception, int __pyx_v_response_with_body, int __pyx_v_read_until_eof, int __pyx_v_auto_decompress) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - struct __pyx_opt_args_7aiohttp_12_http_parser_10HttpParser__init __pyx_t_2; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__init__", 0); - - /* "aiohttp/_http_parser.pyx":630 - * bint auto_decompress=True - * ): - * self._init(cparser.HTTP_RESPONSE, protocol, loop, limit, timer, # <<<<<<<<<<<<<< - * max_line_size, max_headers, max_field_size, - * payload_exception, response_with_body, read_until_eof, - */ - __pyx_t_2.__pyx_n = 8; - __pyx_t_2.timer = __pyx_v_timer; - __pyx_t_2.max_line_size = __pyx_v_max_line_size; - __pyx_t_2.max_headers = __pyx_v_max_headers; - __pyx_t_2.max_field_size = __pyx_v_max_field_size; - __pyx_t_2.payload_exception = __pyx_v_payload_exception; - __pyx_t_2.response_with_body = __pyx_v_response_with_body; - __pyx_t_2.read_until_eof = __pyx_v_read_until_eof; - __pyx_t_2.auto_decompress = __pyx_v_auto_decompress; - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpResponseParser *)__pyx_v_self->__pyx_base.__pyx_vtab)->__pyx_base._init(((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)__pyx_v_self), HTTP_RESPONSE, __pyx_v_protocol, __pyx_v_loop, __pyx_v_limit, &__pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 630, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":623 - * cdef class HttpResponseParser(HttpParser): - * - * def __init__( # <<<<<<<<<<<<<< - * self, protocol, loop, int limit, timer=None, - * size_t max_line_size=8190, size_t max_headers=32768, - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._http_parser.HttpResponseParser.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":635 - * auto_decompress) - * - * cdef object _on_status_complete(self): # <<<<<<<<<<<<<< - * if self._buf: - * self._reason = self._buf.decode('utf-8', 'surrogateescape') - */ - -static PyObject *__pyx_f_7aiohttp_12_http_parser_18HttpResponseParser__on_status_complete(struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParser *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - int __pyx_t_3; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_on_status_complete", 0); - - /* "aiohttp/_http_parser.pyx":636 - * - * cdef object _on_status_complete(self): - * if self._buf: # <<<<<<<<<<<<<< - * self._reason = self._buf.decode('utf-8', 'surrogateescape') - * PyByteArray_Resize(self._buf, 0) - */ - __pyx_t_1 = (__pyx_v_self->__pyx_base._buf != Py_None)&&(PyByteArray_GET_SIZE(__pyx_v_self->__pyx_base._buf) != 0); - if (__pyx_t_1) { - - /* "aiohttp/_http_parser.pyx":637 - * cdef object _on_status_complete(self): - * if self._buf: - * self._reason = self._buf.decode('utf-8', 'surrogateescape') # <<<<<<<<<<<<<< - * PyByteArray_Resize(self._buf, 0) - * else: - */ - if (unlikely(__pyx_v_self->__pyx_base._buf == Py_None)) { - PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "decode"); - __PYX_ERR(0, 637, __pyx_L1_error) - } - __pyx_t_2 = __Pyx_decode_bytearray(__pyx_v_self->__pyx_base._buf, 0, PY_SSIZE_T_MAX, NULL, ((char const *)"surrogateescape"), PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 637, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __Pyx_GOTREF(__pyx_v_self->__pyx_base._reason); - __Pyx_DECREF(__pyx_v_self->__pyx_base._reason); - __pyx_v_self->__pyx_base._reason = ((PyObject*)__pyx_t_2); - __pyx_t_2 = 0; - - /* "aiohttp/_http_parser.pyx":638 - * if self._buf: - * self._reason = self._buf.decode('utf-8', 'surrogateescape') - * PyByteArray_Resize(self._buf, 0) # <<<<<<<<<<<<<< - * else: - * self._reason = self._reason or '' - */ - __pyx_t_2 = __pyx_v_self->__pyx_base._buf; - __Pyx_INCREF(__pyx_t_2); - __pyx_t_3 = PyByteArray_Resize(__pyx_t_2, 0); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(0, 638, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_http_parser.pyx":636 - * - * cdef object _on_status_complete(self): - * if self._buf: # <<<<<<<<<<<<<< - * self._reason = self._buf.decode('utf-8', 'surrogateescape') - * PyByteArray_Resize(self._buf, 0) - */ - goto __pyx_L3; - } - - /* "aiohttp/_http_parser.pyx":640 - * PyByteArray_Resize(self._buf, 0) - * else: - * self._reason = self._reason or '' # <<<<<<<<<<<<<< - * - * cdef int cb_on_message_begin(cparser.llhttp_t* parser) except -1: - */ - /*else*/ { - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_v_self->__pyx_base._reason); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(0, 640, __pyx_L1_error) - if (!__pyx_t_1) { - } else { - __Pyx_INCREF(__pyx_v_self->__pyx_base._reason); - __pyx_t_2 = __pyx_v_self->__pyx_base._reason; - goto __pyx_L4_bool_binop_done; - } - __Pyx_INCREF(__pyx_kp_u__4); - __pyx_t_2 = __pyx_kp_u__4; - __pyx_L4_bool_binop_done:; - __Pyx_GIVEREF(__pyx_t_2); - __Pyx_GOTREF(__pyx_v_self->__pyx_base._reason); - __Pyx_DECREF(__pyx_v_self->__pyx_base._reason); - __pyx_v_self->__pyx_base._reason = ((PyObject*)__pyx_t_2); - __pyx_t_2 = 0; - } - __pyx_L3:; - - /* "aiohttp/_http_parser.pyx":635 - * auto_decompress) - * - * cdef object _on_status_complete(self): # <<<<<<<<<<<<<< - * if self._buf: - * self._reason = self._buf.decode('utf-8', 'surrogateescape') - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_AddTraceback("aiohttp._http_parser.HttpResponseParser._on_status_complete", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18HttpResponseParser_3__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18HttpResponseParser_3__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_18HttpResponseParser_2__reduce_cython__(((struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParser *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_18HttpResponseParser_2__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParser *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__reduce_cython__", 0); - - /* "(tree fragment)":2 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__11, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(1, 2, __pyx_L1_error) - - /* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._http_parser.HttpResponseParser.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":3 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18HttpResponseParser_5__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18HttpResponseParser_5__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_18HttpResponseParser_4__setstate_cython__(((struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParser *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_18HttpResponseParser_4__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParser *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__setstate_cython__", 0); - - /* "(tree fragment)":4 - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__12, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(1, 4, __pyx_L1_error) - - /* "(tree fragment)":3 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._http_parser.HttpResponseParser.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":642 - * self._reason = self._reason or '' - * - * cdef int cb_on_message_begin(cparser.llhttp_t* parser) except -1: # <<<<<<<<<<<<<< - * cdef HttpParser pyparser = parser.data - * - */ - -static int __pyx_f_7aiohttp_12_http_parser_cb_on_message_begin(llhttp_t *__pyx_v_parser) { - struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_pyparser = 0; - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("cb_on_message_begin", 0); - - /* "aiohttp/_http_parser.pyx":643 - * - * cdef int cb_on_message_begin(cparser.llhttp_t* parser) except -1: - * cdef HttpParser pyparser = parser.data # <<<<<<<<<<<<<< - * - * pyparser._started = True - */ - __pyx_t_1 = ((PyObject *)__pyx_v_parser->data); - __Pyx_INCREF(__pyx_t_1); - __pyx_v_pyparser = ((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":645 - * cdef HttpParser pyparser = parser.data - * - * pyparser._started = True # <<<<<<<<<<<<<< - * pyparser._headers = CIMultiDict() - * pyparser._raw_headers = [] - */ - __pyx_v_pyparser->_started = 1; - - /* "aiohttp/_http_parser.pyx":646 - * - * pyparser._started = True - * pyparser._headers = CIMultiDict() # <<<<<<<<<<<<<< - * pyparser._raw_headers = [] - * PyByteArray_Resize(pyparser._buf, 0) - */ - __Pyx_INCREF(__pyx_v_7aiohttp_12_http_parser_CIMultiDict); - __pyx_t_2 = __pyx_v_7aiohttp_12_http_parser_CIMultiDict; __pyx_t_3 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_3)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_3); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - __pyx_t_1 = (__pyx_t_3) ? __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3) : __Pyx_PyObject_CallNoArg(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 646, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v_pyparser->_headers); - __Pyx_DECREF(__pyx_v_pyparser->_headers); - __pyx_v_pyparser->_headers = __pyx_t_1; - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":647 - * pyparser._started = True - * pyparser._headers = CIMultiDict() - * pyparser._raw_headers = [] # <<<<<<<<<<<<<< - * PyByteArray_Resize(pyparser._buf, 0) - * pyparser._path = None - */ - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 647, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v_pyparser->_raw_headers); - __Pyx_DECREF(__pyx_v_pyparser->_raw_headers); - __pyx_v_pyparser->_raw_headers = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":648 - * pyparser._headers = CIMultiDict() - * pyparser._raw_headers = [] - * PyByteArray_Resize(pyparser._buf, 0) # <<<<<<<<<<<<<< - * pyparser._path = None - * pyparser._reason = None - */ - __pyx_t_1 = __pyx_v_pyparser->_buf; - __Pyx_INCREF(__pyx_t_1); - __pyx_t_4 = PyByteArray_Resize(__pyx_t_1, 0); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(0, 648, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":649 - * pyparser._raw_headers = [] - * PyByteArray_Resize(pyparser._buf, 0) - * pyparser._path = None # <<<<<<<<<<<<<< - * pyparser._reason = None - * return 0 - */ - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - __Pyx_GOTREF(__pyx_v_pyparser->_path); - __Pyx_DECREF(__pyx_v_pyparser->_path); - __pyx_v_pyparser->_path = ((PyObject*)Py_None); - - /* "aiohttp/_http_parser.pyx":650 - * PyByteArray_Resize(pyparser._buf, 0) - * pyparser._path = None - * pyparser._reason = None # <<<<<<<<<<<<<< - * return 0 - * - */ - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - __Pyx_GOTREF(__pyx_v_pyparser->_reason); - __Pyx_DECREF(__pyx_v_pyparser->_reason); - __pyx_v_pyparser->_reason = ((PyObject*)Py_None); - - /* "aiohttp/_http_parser.pyx":651 - * pyparser._path = None - * pyparser._reason = None - * return 0 # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = 0; - goto __pyx_L0; - - /* "aiohttp/_http_parser.pyx":642 - * self._reason = self._reason or '' - * - * cdef int cb_on_message_begin(cparser.llhttp_t* parser) except -1: # <<<<<<<<<<<<<< - * cdef HttpParser pyparser = parser.data - * - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("aiohttp._http_parser.cb_on_message_begin", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_pyparser); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":654 - * - * - * cdef int cb_on_url(cparser.llhttp_t* parser, # <<<<<<<<<<<<<< - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data - */ - -static int __pyx_f_7aiohttp_12_http_parser_cb_on_url(llhttp_t *__pyx_v_parser, char const *__pyx_v_at, size_t __pyx_v_length) { - struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_pyparser = 0; - PyObject *__pyx_v_ex = NULL; - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - int __pyx_t_10; - PyObject *__pyx_t_11 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("cb_on_url", 0); - - /* "aiohttp/_http_parser.pyx":656 - * cdef int cb_on_url(cparser.llhttp_t* parser, - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data # <<<<<<<<<<<<<< - * try: - * if length > pyparser._max_line_size: - */ - __pyx_t_1 = ((PyObject *)__pyx_v_parser->data); - __Pyx_INCREF(__pyx_t_1); - __pyx_v_pyparser = ((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":657 - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * if length > pyparser._max_line_size: - * raise LineTooLong( - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); - __Pyx_XGOTREF(__pyx_t_2); - __Pyx_XGOTREF(__pyx_t_3); - __Pyx_XGOTREF(__pyx_t_4); - /*try:*/ { - - /* "aiohttp/_http_parser.pyx":658 - * cdef HttpParser pyparser = parser.data - * try: - * if length > pyparser._max_line_size: # <<<<<<<<<<<<<< - * raise LineTooLong( - * 'Status line is too long', pyparser._max_line_size, length) - */ - __pyx_t_5 = ((__pyx_v_length > __pyx_v_pyparser->_max_line_size) != 0); - if (unlikely(__pyx_t_5)) { - - /* "aiohttp/_http_parser.pyx":659 - * try: - * if length > pyparser._max_line_size: - * raise LineTooLong( # <<<<<<<<<<<<<< - * 'Status line is too long', pyparser._max_line_size, length) - * extend(pyparser._buf, at, length) - */ - __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_n_s_LineTooLong); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 659, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_6); - - /* "aiohttp/_http_parser.pyx":660 - * if length > pyparser._max_line_size: - * raise LineTooLong( - * 'Status line is too long', pyparser._max_line_size, length) # <<<<<<<<<<<<<< - * extend(pyparser._buf, at, length) - * except BaseException as ex: - */ - __pyx_t_7 = __Pyx_PyInt_FromSize_t(__pyx_v_pyparser->_max_line_size); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 660, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_8 = __Pyx_PyInt_FromSize_t(__pyx_v_length); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 660, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_9 = NULL; - __pyx_t_10 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_6))) { - __pyx_t_9 = PyMethod_GET_SELF(__pyx_t_6); - if (likely(__pyx_t_9)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); - __Pyx_INCREF(__pyx_t_9); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_6, function); - __pyx_t_10 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_6)) { - PyObject *__pyx_temp[4] = {__pyx_t_9, __pyx_kp_u_Status_line_is_too_long, __pyx_t_7, __pyx_t_8}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_10, 3+__pyx_t_10); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 659, __pyx_L3_error) - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_6)) { - PyObject *__pyx_temp[4] = {__pyx_t_9, __pyx_kp_u_Status_line_is_too_long, __pyx_t_7, __pyx_t_8}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_10, 3+__pyx_t_10); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 659, __pyx_L3_error) - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - } else - #endif - { - __pyx_t_11 = PyTuple_New(3+__pyx_t_10); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 659, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_11); - if (__pyx_t_9) { - __Pyx_GIVEREF(__pyx_t_9); PyTuple_SET_ITEM(__pyx_t_11, 0, __pyx_t_9); __pyx_t_9 = NULL; - } - __Pyx_INCREF(__pyx_kp_u_Status_line_is_too_long); - __Pyx_GIVEREF(__pyx_kp_u_Status_line_is_too_long); - PyTuple_SET_ITEM(__pyx_t_11, 0+__pyx_t_10, __pyx_kp_u_Status_line_is_too_long); - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_11, 1+__pyx_t_10, __pyx_t_7); - __Pyx_GIVEREF(__pyx_t_8); - PyTuple_SET_ITEM(__pyx_t_11, 2+__pyx_t_10, __pyx_t_8); - __pyx_t_7 = 0; - __pyx_t_8 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_11, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 659, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - } - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(0, 659, __pyx_L3_error) - - /* "aiohttp/_http_parser.pyx":658 - * cdef HttpParser pyparser = parser.data - * try: - * if length > pyparser._max_line_size: # <<<<<<<<<<<<<< - * raise LineTooLong( - * 'Status line is too long', pyparser._max_line_size, length) - */ - } - - /* "aiohttp/_http_parser.pyx":661 - * raise LineTooLong( - * 'Status line is too long', pyparser._max_line_size, length) - * extend(pyparser._buf, at, length) # <<<<<<<<<<<<<< - * except BaseException as ex: - * pyparser._last_error = ex - */ - __pyx_t_1 = __pyx_v_pyparser->_buf; - __Pyx_INCREF(__pyx_t_1); - __pyx_t_6 = __pyx_f_7aiohttp_12_http_parser_extend(__pyx_t_1, __pyx_v_at, __pyx_v_length); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 661, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - - /* "aiohttp/_http_parser.pyx":657 - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * if length > pyparser._max_line_size: - * raise LineTooLong( - */ - } - - /* "aiohttp/_http_parser.pyx":666 - * return -1 - * else: - * return 0 # <<<<<<<<<<<<<< - * - * - */ - /*else:*/ { - __pyx_r = 0; - goto __pyx_L6_except_return; - } - __pyx_L3_error:; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "aiohttp/_http_parser.pyx":662 - * 'Status line is too long', pyparser._max_line_size, length) - * extend(pyparser._buf, at, length) - * except BaseException as ex: # <<<<<<<<<<<<<< - * pyparser._last_error = ex - * return -1 - */ - __pyx_t_10 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_BaseException); - if (__pyx_t_10) { - __Pyx_AddTraceback("aiohttp._http_parser.cb_on_url", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_6, &__pyx_t_1, &__pyx_t_11) < 0) __PYX_ERR(0, 662, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_t_11); - __Pyx_INCREF(__pyx_t_1); - __pyx_v_ex = __pyx_t_1; - /*try:*/ { - - /* "aiohttp/_http_parser.pyx":663 - * extend(pyparser._buf, at, length) - * except BaseException as ex: - * pyparser._last_error = ex # <<<<<<<<<<<<<< - * return -1 - * else: - */ - __Pyx_INCREF(__pyx_v_ex); - __Pyx_GIVEREF(__pyx_v_ex); - __Pyx_GOTREF(__pyx_v_pyparser->_last_error); - __Pyx_DECREF(__pyx_v_pyparser->_last_error); - __pyx_v_pyparser->_last_error = __pyx_v_ex; - - /* "aiohttp/_http_parser.pyx":664 - * except BaseException as ex: - * pyparser._last_error = ex - * return -1 # <<<<<<<<<<<<<< - * else: - * return 0 - */ - __pyx_r = -1; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - goto __pyx_L14_return; - } - - /* "aiohttp/_http_parser.pyx":662 - * 'Status line is too long', pyparser._max_line_size, length) - * extend(pyparser._buf, at, length) - * except BaseException as ex: # <<<<<<<<<<<<<< - * pyparser._last_error = ex - * return -1 - */ - /*finally:*/ { - __pyx_L14_return: { - __pyx_t_10 = __pyx_r; - __Pyx_DECREF(__pyx_v_ex); - __pyx_v_ex = NULL; - __pyx_r = __pyx_t_10; - goto __pyx_L6_except_return; - } - } - } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; - - /* "aiohttp/_http_parser.pyx":657 - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * if length > pyparser._max_line_size: - * raise LineTooLong( - */ - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); - goto __pyx_L1_error; - __pyx_L6_except_return:; - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); - goto __pyx_L0; - } - - /* "aiohttp/_http_parser.pyx":654 - * - * - * cdef int cb_on_url(cparser.llhttp_t* parser, # <<<<<<<<<<<<<< - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_XDECREF(__pyx_t_11); - __Pyx_AddTraceback("aiohttp._http_parser.cb_on_url", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_pyparser); - __Pyx_XDECREF(__pyx_v_ex); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":669 - * - * - * cdef int cb_on_status(cparser.llhttp_t* parser, # <<<<<<<<<<<<<< - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data - */ - -static int __pyx_f_7aiohttp_12_http_parser_cb_on_status(llhttp_t *__pyx_v_parser, char const *__pyx_v_at, size_t __pyx_v_length) { - struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_pyparser = 0; - PyObject *__pyx_v_ex = NULL; - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - int __pyx_t_10; - PyObject *__pyx_t_11 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("cb_on_status", 0); - - /* "aiohttp/_http_parser.pyx":671 - * cdef int cb_on_status(cparser.llhttp_t* parser, - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data # <<<<<<<<<<<<<< - * cdef str reason - * try: - */ - __pyx_t_1 = ((PyObject *)__pyx_v_parser->data); - __Pyx_INCREF(__pyx_t_1); - __pyx_v_pyparser = ((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":673 - * cdef HttpParser pyparser = parser.data - * cdef str reason - * try: # <<<<<<<<<<<<<< - * if length > pyparser._max_line_size: - * raise LineTooLong( - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); - __Pyx_XGOTREF(__pyx_t_2); - __Pyx_XGOTREF(__pyx_t_3); - __Pyx_XGOTREF(__pyx_t_4); - /*try:*/ { - - /* "aiohttp/_http_parser.pyx":674 - * cdef str reason - * try: - * if length > pyparser._max_line_size: # <<<<<<<<<<<<<< - * raise LineTooLong( - * 'Status line is too long', pyparser._max_line_size, length) - */ - __pyx_t_5 = ((__pyx_v_length > __pyx_v_pyparser->_max_line_size) != 0); - if (unlikely(__pyx_t_5)) { - - /* "aiohttp/_http_parser.pyx":675 - * try: - * if length > pyparser._max_line_size: - * raise LineTooLong( # <<<<<<<<<<<<<< - * 'Status line is too long', pyparser._max_line_size, length) - * extend(pyparser._buf, at, length) - */ - __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_n_s_LineTooLong); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 675, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_6); - - /* "aiohttp/_http_parser.pyx":676 - * if length > pyparser._max_line_size: - * raise LineTooLong( - * 'Status line is too long', pyparser._max_line_size, length) # <<<<<<<<<<<<<< - * extend(pyparser._buf, at, length) - * except BaseException as ex: - */ - __pyx_t_7 = __Pyx_PyInt_FromSize_t(__pyx_v_pyparser->_max_line_size); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 676, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_8 = __Pyx_PyInt_FromSize_t(__pyx_v_length); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 676, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_9 = NULL; - __pyx_t_10 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_6))) { - __pyx_t_9 = PyMethod_GET_SELF(__pyx_t_6); - if (likely(__pyx_t_9)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); - __Pyx_INCREF(__pyx_t_9); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_6, function); - __pyx_t_10 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_6)) { - PyObject *__pyx_temp[4] = {__pyx_t_9, __pyx_kp_u_Status_line_is_too_long, __pyx_t_7, __pyx_t_8}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_10, 3+__pyx_t_10); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 675, __pyx_L3_error) - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_6)) { - PyObject *__pyx_temp[4] = {__pyx_t_9, __pyx_kp_u_Status_line_is_too_long, __pyx_t_7, __pyx_t_8}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_10, 3+__pyx_t_10); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 675, __pyx_L3_error) - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - } else - #endif - { - __pyx_t_11 = PyTuple_New(3+__pyx_t_10); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 675, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_11); - if (__pyx_t_9) { - __Pyx_GIVEREF(__pyx_t_9); PyTuple_SET_ITEM(__pyx_t_11, 0, __pyx_t_9); __pyx_t_9 = NULL; - } - __Pyx_INCREF(__pyx_kp_u_Status_line_is_too_long); - __Pyx_GIVEREF(__pyx_kp_u_Status_line_is_too_long); - PyTuple_SET_ITEM(__pyx_t_11, 0+__pyx_t_10, __pyx_kp_u_Status_line_is_too_long); - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_11, 1+__pyx_t_10, __pyx_t_7); - __Pyx_GIVEREF(__pyx_t_8); - PyTuple_SET_ITEM(__pyx_t_11, 2+__pyx_t_10, __pyx_t_8); - __pyx_t_7 = 0; - __pyx_t_8 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_11, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 675, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - } - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(0, 675, __pyx_L3_error) - - /* "aiohttp/_http_parser.pyx":674 - * cdef str reason - * try: - * if length > pyparser._max_line_size: # <<<<<<<<<<<<<< - * raise LineTooLong( - * 'Status line is too long', pyparser._max_line_size, length) - */ - } - - /* "aiohttp/_http_parser.pyx":677 - * raise LineTooLong( - * 'Status line is too long', pyparser._max_line_size, length) - * extend(pyparser._buf, at, length) # <<<<<<<<<<<<<< - * except BaseException as ex: - * pyparser._last_error = ex - */ - __pyx_t_1 = __pyx_v_pyparser->_buf; - __Pyx_INCREF(__pyx_t_1); - __pyx_t_6 = __pyx_f_7aiohttp_12_http_parser_extend(__pyx_t_1, __pyx_v_at, __pyx_v_length); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 677, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - - /* "aiohttp/_http_parser.pyx":673 - * cdef HttpParser pyparser = parser.data - * cdef str reason - * try: # <<<<<<<<<<<<<< - * if length > pyparser._max_line_size: - * raise LineTooLong( - */ - } - - /* "aiohttp/_http_parser.pyx":682 - * return -1 - * else: - * return 0 # <<<<<<<<<<<<<< - * - * - */ - /*else:*/ { - __pyx_r = 0; - goto __pyx_L6_except_return; - } - __pyx_L3_error:; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "aiohttp/_http_parser.pyx":678 - * 'Status line is too long', pyparser._max_line_size, length) - * extend(pyparser._buf, at, length) - * except BaseException as ex: # <<<<<<<<<<<<<< - * pyparser._last_error = ex - * return -1 - */ - __pyx_t_10 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_BaseException); - if (__pyx_t_10) { - __Pyx_AddTraceback("aiohttp._http_parser.cb_on_status", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_6, &__pyx_t_1, &__pyx_t_11) < 0) __PYX_ERR(0, 678, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_t_11); - __Pyx_INCREF(__pyx_t_1); - __pyx_v_ex = __pyx_t_1; - /*try:*/ { - - /* "aiohttp/_http_parser.pyx":679 - * extend(pyparser._buf, at, length) - * except BaseException as ex: - * pyparser._last_error = ex # <<<<<<<<<<<<<< - * return -1 - * else: - */ - __Pyx_INCREF(__pyx_v_ex); - __Pyx_GIVEREF(__pyx_v_ex); - __Pyx_GOTREF(__pyx_v_pyparser->_last_error); - __Pyx_DECREF(__pyx_v_pyparser->_last_error); - __pyx_v_pyparser->_last_error = __pyx_v_ex; - - /* "aiohttp/_http_parser.pyx":680 - * except BaseException as ex: - * pyparser._last_error = ex - * return -1 # <<<<<<<<<<<<<< - * else: - * return 0 - */ - __pyx_r = -1; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - goto __pyx_L14_return; - } - - /* "aiohttp/_http_parser.pyx":678 - * 'Status line is too long', pyparser._max_line_size, length) - * extend(pyparser._buf, at, length) - * except BaseException as ex: # <<<<<<<<<<<<<< - * pyparser._last_error = ex - * return -1 - */ - /*finally:*/ { - __pyx_L14_return: { - __pyx_t_10 = __pyx_r; - __Pyx_DECREF(__pyx_v_ex); - __pyx_v_ex = NULL; - __pyx_r = __pyx_t_10; - goto __pyx_L6_except_return; - } - } - } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; - - /* "aiohttp/_http_parser.pyx":673 - * cdef HttpParser pyparser = parser.data - * cdef str reason - * try: # <<<<<<<<<<<<<< - * if length > pyparser._max_line_size: - * raise LineTooLong( - */ - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); - goto __pyx_L1_error; - __pyx_L6_except_return:; - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); - goto __pyx_L0; - } - - /* "aiohttp/_http_parser.pyx":669 - * - * - * cdef int cb_on_status(cparser.llhttp_t* parser, # <<<<<<<<<<<<<< - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_XDECREF(__pyx_t_11); - __Pyx_AddTraceback("aiohttp._http_parser.cb_on_status", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_pyparser); - __Pyx_XDECREF(__pyx_v_ex); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":685 - * - * - * cdef int cb_on_header_field(cparser.llhttp_t* parser, # <<<<<<<<<<<<<< - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data - */ - -static int __pyx_f_7aiohttp_12_http_parser_cb_on_header_field(llhttp_t *__pyx_v_parser, char const *__pyx_v_at, size_t __pyx_v_length) { - struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_pyparser = 0; - Py_ssize_t __pyx_v_size; - PyObject *__pyx_v_ex = NULL; - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - Py_ssize_t __pyx_t_5; - int __pyx_t_6; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; - int __pyx_t_11; - PyObject *__pyx_t_12 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("cb_on_header_field", 0); - - /* "aiohttp/_http_parser.pyx":687 - * cdef int cb_on_header_field(cparser.llhttp_t* parser, - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data # <<<<<<<<<<<<<< - * cdef Py_ssize_t size - * try: - */ - __pyx_t_1 = ((PyObject *)__pyx_v_parser->data); - __Pyx_INCREF(__pyx_t_1); - __pyx_v_pyparser = ((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":689 - * cdef HttpParser pyparser = parser.data - * cdef Py_ssize_t size - * try: # <<<<<<<<<<<<<< - * pyparser._on_status_complete() - * size = len(pyparser._raw_name) + length - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); - __Pyx_XGOTREF(__pyx_t_2); - __Pyx_XGOTREF(__pyx_t_3); - __Pyx_XGOTREF(__pyx_t_4); - /*try:*/ { - - /* "aiohttp/_http_parser.pyx":690 - * cdef Py_ssize_t size - * try: - * pyparser._on_status_complete() # <<<<<<<<<<<<<< - * size = len(pyparser._raw_name) + length - * if size > pyparser._max_field_size: - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser *)__pyx_v_pyparser->__pyx_vtab)->_on_status_complete(__pyx_v_pyparser); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 690, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":691 - * try: - * pyparser._on_status_complete() - * size = len(pyparser._raw_name) + length # <<<<<<<<<<<<<< - * if size > pyparser._max_field_size: - * raise LineTooLong( - */ - __pyx_t_1 = __pyx_v_pyparser->_raw_name; - __Pyx_INCREF(__pyx_t_1); - if (unlikely(__pyx_t_1 == Py_None)) { - PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - __PYX_ERR(0, 691, __pyx_L3_error) - } - __pyx_t_5 = PyByteArray_GET_SIZE(__pyx_t_1); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(0, 691, __pyx_L3_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_size = (__pyx_t_5 + __pyx_v_length); - - /* "aiohttp/_http_parser.pyx":692 - * pyparser._on_status_complete() - * size = len(pyparser._raw_name) + length - * if size > pyparser._max_field_size: # <<<<<<<<<<<<<< - * raise LineTooLong( - * 'Header name is too long', pyparser._max_field_size, size) - */ - __pyx_t_6 = ((__pyx_v_size > __pyx_v_pyparser->_max_field_size) != 0); - if (unlikely(__pyx_t_6)) { - - /* "aiohttp/_http_parser.pyx":693 - * size = len(pyparser._raw_name) + length - * if size > pyparser._max_field_size: - * raise LineTooLong( # <<<<<<<<<<<<<< - * 'Header name is too long', pyparser._max_field_size, size) - * pyparser._on_header_field(at, length) - */ - __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_n_s_LineTooLong); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 693, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_7); - - /* "aiohttp/_http_parser.pyx":694 - * if size > pyparser._max_field_size: - * raise LineTooLong( - * 'Header name is too long', pyparser._max_field_size, size) # <<<<<<<<<<<<<< - * pyparser._on_header_field(at, length) - * except BaseException as ex: - */ - __pyx_t_8 = __Pyx_PyInt_FromSize_t(__pyx_v_pyparser->_max_field_size); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 694, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_9 = PyInt_FromSsize_t(__pyx_v_size); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 694, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_10 = NULL; - __pyx_t_11 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_7))) { - __pyx_t_10 = PyMethod_GET_SELF(__pyx_t_7); - if (likely(__pyx_t_10)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); - __Pyx_INCREF(__pyx_t_10); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_7, function); - __pyx_t_11 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[4] = {__pyx_t_10, __pyx_kp_u_Header_name_is_too_long, __pyx_t_8, __pyx_t_9}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_11, 3+__pyx_t_11); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 693, __pyx_L3_error) - __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[4] = {__pyx_t_10, __pyx_kp_u_Header_name_is_too_long, __pyx_t_8, __pyx_t_9}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_11, 3+__pyx_t_11); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 693, __pyx_L3_error) - __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } else - #endif - { - __pyx_t_12 = PyTuple_New(3+__pyx_t_11); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 693, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_12); - if (__pyx_t_10) { - __Pyx_GIVEREF(__pyx_t_10); PyTuple_SET_ITEM(__pyx_t_12, 0, __pyx_t_10); __pyx_t_10 = NULL; - } - __Pyx_INCREF(__pyx_kp_u_Header_name_is_too_long); - __Pyx_GIVEREF(__pyx_kp_u_Header_name_is_too_long); - PyTuple_SET_ITEM(__pyx_t_12, 0+__pyx_t_11, __pyx_kp_u_Header_name_is_too_long); - __Pyx_GIVEREF(__pyx_t_8); - PyTuple_SET_ITEM(__pyx_t_12, 1+__pyx_t_11, __pyx_t_8); - __Pyx_GIVEREF(__pyx_t_9); - PyTuple_SET_ITEM(__pyx_t_12, 2+__pyx_t_11, __pyx_t_9); - __pyx_t_8 = 0; - __pyx_t_9 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_12, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 693, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; - } - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(0, 693, __pyx_L3_error) - - /* "aiohttp/_http_parser.pyx":692 - * pyparser._on_status_complete() - * size = len(pyparser._raw_name) + length - * if size > pyparser._max_field_size: # <<<<<<<<<<<<<< - * raise LineTooLong( - * 'Header name is too long', pyparser._max_field_size, size) - */ - } - - /* "aiohttp/_http_parser.pyx":695 - * raise LineTooLong( - * 'Header name is too long', pyparser._max_field_size, size) - * pyparser._on_header_field(at, length) # <<<<<<<<<<<<<< - * except BaseException as ex: - * pyparser._last_error = ex - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser *)__pyx_v_pyparser->__pyx_vtab)->_on_header_field(__pyx_v_pyparser, __pyx_v_at, __pyx_v_length); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 695, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":689 - * cdef HttpParser pyparser = parser.data - * cdef Py_ssize_t size - * try: # <<<<<<<<<<<<<< - * pyparser._on_status_complete() - * size = len(pyparser._raw_name) + length - */ - } - - /* "aiohttp/_http_parser.pyx":700 - * return -1 - * else: - * return 0 # <<<<<<<<<<<<<< - * - * - */ - /*else:*/ { - __pyx_r = 0; - goto __pyx_L6_except_return; - } - __pyx_L3_error:; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_XDECREF(__pyx_t_12); __pyx_t_12 = 0; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "aiohttp/_http_parser.pyx":696 - * 'Header name is too long', pyparser._max_field_size, size) - * pyparser._on_header_field(at, length) - * except BaseException as ex: # <<<<<<<<<<<<<< - * pyparser._last_error = ex - * return -1 - */ - __pyx_t_11 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_BaseException); - if (__pyx_t_11) { - __Pyx_AddTraceback("aiohttp._http_parser.cb_on_header_field", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_1, &__pyx_t_7, &__pyx_t_12) < 0) __PYX_ERR(0, 696, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_t_7); - __Pyx_GOTREF(__pyx_t_12); - __Pyx_INCREF(__pyx_t_7); - __pyx_v_ex = __pyx_t_7; - /*try:*/ { - - /* "aiohttp/_http_parser.pyx":697 - * pyparser._on_header_field(at, length) - * except BaseException as ex: - * pyparser._last_error = ex # <<<<<<<<<<<<<< - * return -1 - * else: - */ - __Pyx_INCREF(__pyx_v_ex); - __Pyx_GIVEREF(__pyx_v_ex); - __Pyx_GOTREF(__pyx_v_pyparser->_last_error); - __Pyx_DECREF(__pyx_v_pyparser->_last_error); - __pyx_v_pyparser->_last_error = __pyx_v_ex; - - /* "aiohttp/_http_parser.pyx":698 - * except BaseException as ex: - * pyparser._last_error = ex - * return -1 # <<<<<<<<<<<<<< - * else: - * return 0 - */ - __pyx_r = -1; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; - goto __pyx_L14_return; - } - - /* "aiohttp/_http_parser.pyx":696 - * 'Header name is too long', pyparser._max_field_size, size) - * pyparser._on_header_field(at, length) - * except BaseException as ex: # <<<<<<<<<<<<<< - * pyparser._last_error = ex - * return -1 - */ - /*finally:*/ { - __pyx_L14_return: { - __pyx_t_11 = __pyx_r; - __Pyx_DECREF(__pyx_v_ex); - __pyx_v_ex = NULL; - __pyx_r = __pyx_t_11; - goto __pyx_L6_except_return; - } - } - } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; - - /* "aiohttp/_http_parser.pyx":689 - * cdef HttpParser pyparser = parser.data - * cdef Py_ssize_t size - * try: # <<<<<<<<<<<<<< - * pyparser._on_status_complete() - * size = len(pyparser._raw_name) + length - */ - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); - goto __pyx_L1_error; - __pyx_L6_except_return:; - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); - goto __pyx_L0; - } - - /* "aiohttp/_http_parser.pyx":685 - * - * - * cdef int cb_on_header_field(cparser.llhttp_t* parser, # <<<<<<<<<<<<<< - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_XDECREF(__pyx_t_12); - __Pyx_AddTraceback("aiohttp._http_parser.cb_on_header_field", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_pyparser); - __Pyx_XDECREF(__pyx_v_ex); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":703 - * - * - * cdef int cb_on_header_value(cparser.llhttp_t* parser, # <<<<<<<<<<<<<< - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data - */ - -static int __pyx_f_7aiohttp_12_http_parser_cb_on_header_value(llhttp_t *__pyx_v_parser, char const *__pyx_v_at, size_t __pyx_v_length) { - struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_pyparser = 0; - Py_ssize_t __pyx_v_size; - PyObject *__pyx_v_ex = NULL; - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - Py_ssize_t __pyx_t_5; - int __pyx_t_6; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; - int __pyx_t_11; - PyObject *__pyx_t_12 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("cb_on_header_value", 0); - - /* "aiohttp/_http_parser.pyx":705 - * cdef int cb_on_header_value(cparser.llhttp_t* parser, - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data # <<<<<<<<<<<<<< - * cdef Py_ssize_t size - * try: - */ - __pyx_t_1 = ((PyObject *)__pyx_v_parser->data); - __Pyx_INCREF(__pyx_t_1); - __pyx_v_pyparser = ((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":707 - * cdef HttpParser pyparser = parser.data - * cdef Py_ssize_t size - * try: # <<<<<<<<<<<<<< - * size = len(pyparser._raw_value) + length - * if size > pyparser._max_field_size: - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); - __Pyx_XGOTREF(__pyx_t_2); - __Pyx_XGOTREF(__pyx_t_3); - __Pyx_XGOTREF(__pyx_t_4); - /*try:*/ { - - /* "aiohttp/_http_parser.pyx":708 - * cdef Py_ssize_t size - * try: - * size = len(pyparser._raw_value) + length # <<<<<<<<<<<<<< - * if size > pyparser._max_field_size: - * raise LineTooLong( - */ - __pyx_t_1 = __pyx_v_pyparser->_raw_value; - __Pyx_INCREF(__pyx_t_1); - if (unlikely(__pyx_t_1 == Py_None)) { - PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - __PYX_ERR(0, 708, __pyx_L3_error) - } - __pyx_t_5 = PyByteArray_GET_SIZE(__pyx_t_1); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(0, 708, __pyx_L3_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_size = (__pyx_t_5 + __pyx_v_length); - - /* "aiohttp/_http_parser.pyx":709 - * try: - * size = len(pyparser._raw_value) + length - * if size > pyparser._max_field_size: # <<<<<<<<<<<<<< - * raise LineTooLong( - * 'Header value is too long', pyparser._max_field_size, size) - */ - __pyx_t_6 = ((__pyx_v_size > __pyx_v_pyparser->_max_field_size) != 0); - if (unlikely(__pyx_t_6)) { - - /* "aiohttp/_http_parser.pyx":710 - * size = len(pyparser._raw_value) + length - * if size > pyparser._max_field_size: - * raise LineTooLong( # <<<<<<<<<<<<<< - * 'Header value is too long', pyparser._max_field_size, size) - * pyparser._on_header_value(at, length) - */ - __Pyx_GetModuleGlobalName(__pyx_t_7, __pyx_n_s_LineTooLong); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 710, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_7); - - /* "aiohttp/_http_parser.pyx":711 - * if size > pyparser._max_field_size: - * raise LineTooLong( - * 'Header value is too long', pyparser._max_field_size, size) # <<<<<<<<<<<<<< - * pyparser._on_header_value(at, length) - * except BaseException as ex: - */ - __pyx_t_8 = __Pyx_PyInt_FromSize_t(__pyx_v_pyparser->_max_field_size); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 711, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_9 = PyInt_FromSsize_t(__pyx_v_size); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 711, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_10 = NULL; - __pyx_t_11 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_7))) { - __pyx_t_10 = PyMethod_GET_SELF(__pyx_t_7); - if (likely(__pyx_t_10)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); - __Pyx_INCREF(__pyx_t_10); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_7, function); - __pyx_t_11 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[4] = {__pyx_t_10, __pyx_kp_u_Header_value_is_too_long, __pyx_t_8, __pyx_t_9}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_11, 3+__pyx_t_11); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 710, __pyx_L3_error) - __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[4] = {__pyx_t_10, __pyx_kp_u_Header_value_is_too_long, __pyx_t_8, __pyx_t_9}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_11, 3+__pyx_t_11); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 710, __pyx_L3_error) - __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } else - #endif - { - __pyx_t_12 = PyTuple_New(3+__pyx_t_11); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 710, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_12); - if (__pyx_t_10) { - __Pyx_GIVEREF(__pyx_t_10); PyTuple_SET_ITEM(__pyx_t_12, 0, __pyx_t_10); __pyx_t_10 = NULL; - } - __Pyx_INCREF(__pyx_kp_u_Header_value_is_too_long); - __Pyx_GIVEREF(__pyx_kp_u_Header_value_is_too_long); - PyTuple_SET_ITEM(__pyx_t_12, 0+__pyx_t_11, __pyx_kp_u_Header_value_is_too_long); - __Pyx_GIVEREF(__pyx_t_8); - PyTuple_SET_ITEM(__pyx_t_12, 1+__pyx_t_11, __pyx_t_8); - __Pyx_GIVEREF(__pyx_t_9); - PyTuple_SET_ITEM(__pyx_t_12, 2+__pyx_t_11, __pyx_t_9); - __pyx_t_8 = 0; - __pyx_t_9 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_12, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 710, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; - } - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(0, 710, __pyx_L3_error) - - /* "aiohttp/_http_parser.pyx":709 - * try: - * size = len(pyparser._raw_value) + length - * if size > pyparser._max_field_size: # <<<<<<<<<<<<<< - * raise LineTooLong( - * 'Header value is too long', pyparser._max_field_size, size) - */ - } - - /* "aiohttp/_http_parser.pyx":712 - * raise LineTooLong( - * 'Header value is too long', pyparser._max_field_size, size) - * pyparser._on_header_value(at, length) # <<<<<<<<<<<<<< - * except BaseException as ex: - * pyparser._last_error = ex - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser *)__pyx_v_pyparser->__pyx_vtab)->_on_header_value(__pyx_v_pyparser, __pyx_v_at, __pyx_v_length); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 712, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":707 - * cdef HttpParser pyparser = parser.data - * cdef Py_ssize_t size - * try: # <<<<<<<<<<<<<< - * size = len(pyparser._raw_value) + length - * if size > pyparser._max_field_size: - */ - } - - /* "aiohttp/_http_parser.pyx":717 - * return -1 - * else: - * return 0 # <<<<<<<<<<<<<< - * - * - */ - /*else:*/ { - __pyx_r = 0; - goto __pyx_L6_except_return; - } - __pyx_L3_error:; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_XDECREF(__pyx_t_12); __pyx_t_12 = 0; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "aiohttp/_http_parser.pyx":713 - * 'Header value is too long', pyparser._max_field_size, size) - * pyparser._on_header_value(at, length) - * except BaseException as ex: # <<<<<<<<<<<<<< - * pyparser._last_error = ex - * return -1 - */ - __pyx_t_11 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_BaseException); - if (__pyx_t_11) { - __Pyx_AddTraceback("aiohttp._http_parser.cb_on_header_value", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_1, &__pyx_t_7, &__pyx_t_12) < 0) __PYX_ERR(0, 713, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_t_7); - __Pyx_GOTREF(__pyx_t_12); - __Pyx_INCREF(__pyx_t_7); - __pyx_v_ex = __pyx_t_7; - /*try:*/ { - - /* "aiohttp/_http_parser.pyx":714 - * pyparser._on_header_value(at, length) - * except BaseException as ex: - * pyparser._last_error = ex # <<<<<<<<<<<<<< - * return -1 - * else: - */ - __Pyx_INCREF(__pyx_v_ex); - __Pyx_GIVEREF(__pyx_v_ex); - __Pyx_GOTREF(__pyx_v_pyparser->_last_error); - __Pyx_DECREF(__pyx_v_pyparser->_last_error); - __pyx_v_pyparser->_last_error = __pyx_v_ex; - - /* "aiohttp/_http_parser.pyx":715 - * except BaseException as ex: - * pyparser._last_error = ex - * return -1 # <<<<<<<<<<<<<< - * else: - * return 0 - */ - __pyx_r = -1; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; - goto __pyx_L14_return; - } - - /* "aiohttp/_http_parser.pyx":713 - * 'Header value is too long', pyparser._max_field_size, size) - * pyparser._on_header_value(at, length) - * except BaseException as ex: # <<<<<<<<<<<<<< - * pyparser._last_error = ex - * return -1 - */ - /*finally:*/ { - __pyx_L14_return: { - __pyx_t_11 = __pyx_r; - __Pyx_DECREF(__pyx_v_ex); - __pyx_v_ex = NULL; - __pyx_r = __pyx_t_11; - goto __pyx_L6_except_return; - } - } - } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; - - /* "aiohttp/_http_parser.pyx":707 - * cdef HttpParser pyparser = parser.data - * cdef Py_ssize_t size - * try: # <<<<<<<<<<<<<< - * size = len(pyparser._raw_value) + length - * if size > pyparser._max_field_size: - */ - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); - goto __pyx_L1_error; - __pyx_L6_except_return:; - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); - goto __pyx_L0; - } - - /* "aiohttp/_http_parser.pyx":703 - * - * - * cdef int cb_on_header_value(cparser.llhttp_t* parser, # <<<<<<<<<<<<<< - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_XDECREF(__pyx_t_12); - __Pyx_AddTraceback("aiohttp._http_parser.cb_on_header_value", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_pyparser); - __Pyx_XDECREF(__pyx_v_ex); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":720 - * - * - * cdef int cb_on_headers_complete(cparser.llhttp_t* parser) except -1: # <<<<<<<<<<<<<< - * cdef HttpParser pyparser = parser.data - * try: - */ - -static int __pyx_f_7aiohttp_12_http_parser_cb_on_headers_complete(llhttp_t *__pyx_v_parser) { - struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_pyparser = 0; - PyObject *__pyx_v_exc = NULL; - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - int __pyx_t_6; - int __pyx_t_7; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("cb_on_headers_complete", 0); - - /* "aiohttp/_http_parser.pyx":721 - * - * cdef int cb_on_headers_complete(cparser.llhttp_t* parser) except -1: - * cdef HttpParser pyparser = parser.data # <<<<<<<<<<<<<< - * try: - * pyparser._on_status_complete() - */ - __pyx_t_1 = ((PyObject *)__pyx_v_parser->data); - __Pyx_INCREF(__pyx_t_1); - __pyx_v_pyparser = ((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":722 - * cdef int cb_on_headers_complete(cparser.llhttp_t* parser) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * pyparser._on_status_complete() - * pyparser._on_headers_complete() - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); - __Pyx_XGOTREF(__pyx_t_2); - __Pyx_XGOTREF(__pyx_t_3); - __Pyx_XGOTREF(__pyx_t_4); - /*try:*/ { - - /* "aiohttp/_http_parser.pyx":723 - * cdef HttpParser pyparser = parser.data - * try: - * pyparser._on_status_complete() # <<<<<<<<<<<<<< - * pyparser._on_headers_complete() - * except BaseException as exc: - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser *)__pyx_v_pyparser->__pyx_vtab)->_on_status_complete(__pyx_v_pyparser); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 723, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":724 - * try: - * pyparser._on_status_complete() - * pyparser._on_headers_complete() # <<<<<<<<<<<<<< - * except BaseException as exc: - * pyparser._last_error = exc - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser *)__pyx_v_pyparser->__pyx_vtab)->_on_headers_complete(__pyx_v_pyparser); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 724, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":722 - * cdef int cb_on_headers_complete(cparser.llhttp_t* parser) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * pyparser._on_status_complete() - * pyparser._on_headers_complete() - */ - } - - /* "aiohttp/_http_parser.pyx":729 - * return -1 - * else: - * if pyparser._cparser.upgrade or pyparser._cparser.method == 5: # CONNECT # <<<<<<<<<<<<<< - * return 2 - * else: - */ - /*else:*/ { - __pyx_t_6 = (__pyx_v_pyparser->_cparser->upgrade != 0); - if (!__pyx_t_6) { - } else { - __pyx_t_5 = __pyx_t_6; - goto __pyx_L10_bool_binop_done; - } - __pyx_t_6 = ((__pyx_v_pyparser->_cparser->method == 5) != 0); - __pyx_t_5 = __pyx_t_6; - __pyx_L10_bool_binop_done:; - if (__pyx_t_5) { - - /* "aiohttp/_http_parser.pyx":730 - * else: - * if pyparser._cparser.upgrade or pyparser._cparser.method == 5: # CONNECT - * return 2 # <<<<<<<<<<<<<< - * else: - * return 0 - */ - __pyx_r = 2; - goto __pyx_L6_except_return; - - /* "aiohttp/_http_parser.pyx":729 - * return -1 - * else: - * if pyparser._cparser.upgrade or pyparser._cparser.method == 5: # CONNECT # <<<<<<<<<<<<<< - * return 2 - * else: - */ - } - - /* "aiohttp/_http_parser.pyx":732 - * return 2 - * else: - * return 0 # <<<<<<<<<<<<<< - * - * - */ - /*else*/ { - __pyx_r = 0; - goto __pyx_L6_except_return; - } - } - __pyx_L3_error:; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":725 - * pyparser._on_status_complete() - * pyparser._on_headers_complete() - * except BaseException as exc: # <<<<<<<<<<<<<< - * pyparser._last_error = exc - * return -1 - */ - __pyx_t_7 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_BaseException); - if (__pyx_t_7) { - __Pyx_AddTraceback("aiohttp._http_parser.cb_on_headers_complete", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_1, &__pyx_t_8, &__pyx_t_9) < 0) __PYX_ERR(0, 725, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_t_8); - __Pyx_GOTREF(__pyx_t_9); - __Pyx_INCREF(__pyx_t_8); - __pyx_v_exc = __pyx_t_8; - /*try:*/ { - - /* "aiohttp/_http_parser.pyx":726 - * pyparser._on_headers_complete() - * except BaseException as exc: - * pyparser._last_error = exc # <<<<<<<<<<<<<< - * return -1 - * else: - */ - __Pyx_INCREF(__pyx_v_exc); - __Pyx_GIVEREF(__pyx_v_exc); - __Pyx_GOTREF(__pyx_v_pyparser->_last_error); - __Pyx_DECREF(__pyx_v_pyparser->_last_error); - __pyx_v_pyparser->_last_error = __pyx_v_exc; - - /* "aiohttp/_http_parser.pyx":727 - * except BaseException as exc: - * pyparser._last_error = exc - * return -1 # <<<<<<<<<<<<<< - * else: - * if pyparser._cparser.upgrade or pyparser._cparser.method == 5: # CONNECT - */ - __pyx_r = -1; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - goto __pyx_L16_return; - } - - /* "aiohttp/_http_parser.pyx":725 - * pyparser._on_status_complete() - * pyparser._on_headers_complete() - * except BaseException as exc: # <<<<<<<<<<<<<< - * pyparser._last_error = exc - * return -1 - */ - /*finally:*/ { - __pyx_L16_return: { - __pyx_t_7 = __pyx_r; - __Pyx_DECREF(__pyx_v_exc); - __pyx_v_exc = NULL; - __pyx_r = __pyx_t_7; - goto __pyx_L6_except_return; - } - } - } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; - - /* "aiohttp/_http_parser.pyx":722 - * cdef int cb_on_headers_complete(cparser.llhttp_t* parser) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * pyparser._on_status_complete() - * pyparser._on_headers_complete() - */ - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); - goto __pyx_L1_error; - __pyx_L6_except_return:; - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); - goto __pyx_L0; - } - - /* "aiohttp/_http_parser.pyx":720 - * - * - * cdef int cb_on_headers_complete(cparser.llhttp_t* parser) except -1: # <<<<<<<<<<<<<< - * cdef HttpParser pyparser = parser.data - * try: - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_AddTraceback("aiohttp._http_parser.cb_on_headers_complete", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_pyparser); - __Pyx_XDECREF(__pyx_v_exc); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":735 - * - * - * cdef int cb_on_body(cparser.llhttp_t* parser, # <<<<<<<<<<<<<< - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data - */ - -static int __pyx_f_7aiohttp_12_http_parser_cb_on_body(llhttp_t *__pyx_v_parser, char const *__pyx_v_at, size_t __pyx_v_length) { - struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_pyparser = 0; - PyObject *__pyx_v_body = 0; - PyObject *__pyx_v_exc = NULL; - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - int __pyx_t_8; - PyObject *__pyx_t_9 = NULL; - int __pyx_t_10; - int __pyx_t_11; - PyObject *__pyx_t_12 = NULL; - PyObject *__pyx_t_13 = NULL; - PyObject *__pyx_t_14 = NULL; - PyObject *__pyx_t_15 = NULL; - int __pyx_t_16; - char const *__pyx_t_17; - PyObject *__pyx_t_18 = NULL; - PyObject *__pyx_t_19 = NULL; - PyObject *__pyx_t_20 = NULL; - PyObject *__pyx_t_21 = NULL; - PyObject *__pyx_t_22 = NULL; - PyObject *__pyx_t_23 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("cb_on_body", 0); - - /* "aiohttp/_http_parser.pyx":737 - * cdef int cb_on_body(cparser.llhttp_t* parser, - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data # <<<<<<<<<<<<<< - * cdef bytes body = at[:length] - * try: - */ - __pyx_t_1 = ((PyObject *)__pyx_v_parser->data); - __Pyx_INCREF(__pyx_t_1); - __pyx_v_pyparser = ((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":738 - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data - * cdef bytes body = at[:length] # <<<<<<<<<<<<<< - * try: - * pyparser._payload.feed_data(body, length) - */ - __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_at + 0, __pyx_v_length - 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 738, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_body = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":739 - * cdef HttpParser pyparser = parser.data - * cdef bytes body = at[:length] - * try: # <<<<<<<<<<<<<< - * pyparser._payload.feed_data(body, length) - * except BaseException as exc: - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); - __Pyx_XGOTREF(__pyx_t_2); - __Pyx_XGOTREF(__pyx_t_3); - __Pyx_XGOTREF(__pyx_t_4); - /*try:*/ { - - /* "aiohttp/_http_parser.pyx":740 - * cdef bytes body = at[:length] - * try: - * pyparser._payload.feed_data(body, length) # <<<<<<<<<<<<<< - * except BaseException as exc: - * if pyparser._payload_exception is not None: - */ - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_pyparser->_payload, __pyx_n_s_feed_data); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 740, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = __Pyx_PyInt_FromSize_t(__pyx_v_length); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 740, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = NULL; - __pyx_t_8 = 0; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_5))) { - __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_5); - if (likely(__pyx_t_7)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); - __Pyx_INCREF(__pyx_t_7); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_5, function); - __pyx_t_8 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_5)) { - PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_v_body, __pyx_t_6}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_5, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 740, __pyx_L3_error) - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_5)) { - PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_v_body, __pyx_t_6}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_5, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 740, __pyx_L3_error) - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } else - #endif - { - __pyx_t_9 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 740, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_9); - if (__pyx_t_7) { - __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_7); __pyx_t_7 = NULL; - } - __Pyx_INCREF(__pyx_v_body); - __Pyx_GIVEREF(__pyx_v_body); - PyTuple_SET_ITEM(__pyx_t_9, 0+__pyx_t_8, __pyx_v_body); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_9, 1+__pyx_t_8, __pyx_t_6); - __pyx_t_6 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_9, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 740, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":739 - * cdef HttpParser pyparser = parser.data - * cdef bytes body = at[:length] - * try: # <<<<<<<<<<<<<< - * pyparser._payload.feed_data(body, length) - * except BaseException as exc: - */ - } - - /* "aiohttp/_http_parser.pyx":749 - * return -1 - * else: - * return 0 # <<<<<<<<<<<<<< - * - * - */ - /*else:*/ { - __pyx_r = 0; - goto __pyx_L6_except_return; - } - __pyx_L3_error:; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - - /* "aiohttp/_http_parser.pyx":741 - * try: - * pyparser._payload.feed_data(body, length) - * except BaseException as exc: # <<<<<<<<<<<<<< - * if pyparser._payload_exception is not None: - * pyparser._payload.set_exception(pyparser._payload_exception(str(exc))) - */ - __pyx_t_8 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_BaseException); - if (__pyx_t_8) { - __Pyx_AddTraceback("aiohttp._http_parser.cb_on_body", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_1, &__pyx_t_5, &__pyx_t_9) < 0) __PYX_ERR(0, 741, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GOTREF(__pyx_t_9); - __Pyx_INCREF(__pyx_t_5); - __pyx_v_exc = __pyx_t_5; - /*try:*/ { - - /* "aiohttp/_http_parser.pyx":742 - * pyparser._payload.feed_data(body, length) - * except BaseException as exc: - * if pyparser._payload_exception is not None: # <<<<<<<<<<<<<< - * pyparser._payload.set_exception(pyparser._payload_exception(str(exc))) - * else: - */ - __pyx_t_10 = (__pyx_v_pyparser->_payload_exception != Py_None); - __pyx_t_11 = (__pyx_t_10 != 0); - if (__pyx_t_11) { - - /* "aiohttp/_http_parser.pyx":743 - * except BaseException as exc: - * if pyparser._payload_exception is not None: - * pyparser._payload.set_exception(pyparser._payload_exception(str(exc))) # <<<<<<<<<<<<<< - * else: - * pyparser._payload.set_exception(exc) - */ - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_v_pyparser->_payload, __pyx_n_s_set_exception); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 743, __pyx_L14_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_13 = __Pyx_PyObject_CallOneArg(((PyObject *)(&PyUnicode_Type)), __pyx_v_exc); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 743, __pyx_L14_error) - __Pyx_GOTREF(__pyx_t_13); - __Pyx_INCREF(__pyx_v_pyparser->_payload_exception); - __pyx_t_14 = __pyx_v_pyparser->_payload_exception; __pyx_t_15 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_14))) { - __pyx_t_15 = PyMethod_GET_SELF(__pyx_t_14); - if (likely(__pyx_t_15)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_14); - __Pyx_INCREF(__pyx_t_15); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_14, function); - } - } - __pyx_t_12 = (__pyx_t_15) ? __Pyx_PyObject_Call2Args(__pyx_t_14, __pyx_t_15, __pyx_t_13) : __Pyx_PyObject_CallOneArg(__pyx_t_14, __pyx_t_13); - __Pyx_XDECREF(__pyx_t_15); __pyx_t_15 = 0; - __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; - if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 743, __pyx_L14_error) - __Pyx_GOTREF(__pyx_t_12); - __Pyx_DECREF(__pyx_t_14); __pyx_t_14 = 0; - __pyx_t_14 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_7))) { - __pyx_t_14 = PyMethod_GET_SELF(__pyx_t_7); - if (likely(__pyx_t_14)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); - __Pyx_INCREF(__pyx_t_14); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_7, function); - } - } - __pyx_t_6 = (__pyx_t_14) ? __Pyx_PyObject_Call2Args(__pyx_t_7, __pyx_t_14, __pyx_t_12) : __Pyx_PyObject_CallOneArg(__pyx_t_7, __pyx_t_12); - __Pyx_XDECREF(__pyx_t_14); __pyx_t_14 = 0; - __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; - if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 743, __pyx_L14_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - - /* "aiohttp/_http_parser.pyx":742 - * pyparser._payload.feed_data(body, length) - * except BaseException as exc: - * if pyparser._payload_exception is not None: # <<<<<<<<<<<<<< - * pyparser._payload.set_exception(pyparser._payload_exception(str(exc))) - * else: - */ - goto __pyx_L16; - } - - /* "aiohttp/_http_parser.pyx":745 - * pyparser._payload.set_exception(pyparser._payload_exception(str(exc))) - * else: - * pyparser._payload.set_exception(exc) # <<<<<<<<<<<<<< - * pyparser._payload_error = 1 - * return -1 - */ - /*else*/ { - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_v_pyparser->_payload, __pyx_n_s_set_exception); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 745, __pyx_L14_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_12 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_7))) { - __pyx_t_12 = PyMethod_GET_SELF(__pyx_t_7); - if (likely(__pyx_t_12)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); - __Pyx_INCREF(__pyx_t_12); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_7, function); - } - } - __pyx_t_6 = (__pyx_t_12) ? __Pyx_PyObject_Call2Args(__pyx_t_7, __pyx_t_12, __pyx_v_exc) : __Pyx_PyObject_CallOneArg(__pyx_t_7, __pyx_v_exc); - __Pyx_XDECREF(__pyx_t_12); __pyx_t_12 = 0; - if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 745, __pyx_L14_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } - __pyx_L16:; - - /* "aiohttp/_http_parser.pyx":746 - * else: - * pyparser._payload.set_exception(exc) - * pyparser._payload_error = 1 # <<<<<<<<<<<<<< - * return -1 - * else: - */ - __pyx_v_pyparser->_payload_error = 1; - - /* "aiohttp/_http_parser.pyx":747 - * pyparser._payload.set_exception(exc) - * pyparser._payload_error = 1 - * return -1 # <<<<<<<<<<<<<< - * else: - * return 0 - */ - __pyx_r = -1; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - goto __pyx_L13_return; - } - - /* "aiohttp/_http_parser.pyx":741 - * try: - * pyparser._payload.feed_data(body, length) - * except BaseException as exc: # <<<<<<<<<<<<<< - * if pyparser._payload_exception is not None: - * pyparser._payload.set_exception(pyparser._payload_exception(str(exc))) - */ - /*finally:*/ { - __pyx_L14_error:; - /*exception exit:*/{ - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __pyx_t_18 = 0; __pyx_t_19 = 0; __pyx_t_20 = 0; __pyx_t_21 = 0; __pyx_t_22 = 0; __pyx_t_23 = 0; - __Pyx_XDECREF(__pyx_t_12); __pyx_t_12 = 0; - __Pyx_XDECREF(__pyx_t_13); __pyx_t_13 = 0; - __Pyx_XDECREF(__pyx_t_14); __pyx_t_14 = 0; - __Pyx_XDECREF(__pyx_t_15); __pyx_t_15 = 0; - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_21, &__pyx_t_22, &__pyx_t_23); - if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_18, &__pyx_t_19, &__pyx_t_20) < 0)) __Pyx_ErrFetch(&__pyx_t_18, &__pyx_t_19, &__pyx_t_20); - __Pyx_XGOTREF(__pyx_t_18); - __Pyx_XGOTREF(__pyx_t_19); - __Pyx_XGOTREF(__pyx_t_20); - __Pyx_XGOTREF(__pyx_t_21); - __Pyx_XGOTREF(__pyx_t_22); - __Pyx_XGOTREF(__pyx_t_23); - __pyx_t_8 = __pyx_lineno; __pyx_t_16 = __pyx_clineno; __pyx_t_17 = __pyx_filename; - { - __Pyx_DECREF(__pyx_v_exc); - __pyx_v_exc = NULL; - } - if (PY_MAJOR_VERSION >= 3) { - __Pyx_XGIVEREF(__pyx_t_21); - __Pyx_XGIVEREF(__pyx_t_22); - __Pyx_XGIVEREF(__pyx_t_23); - __Pyx_ExceptionReset(__pyx_t_21, __pyx_t_22, __pyx_t_23); - } - __Pyx_XGIVEREF(__pyx_t_18); - __Pyx_XGIVEREF(__pyx_t_19); - __Pyx_XGIVEREF(__pyx_t_20); - __Pyx_ErrRestore(__pyx_t_18, __pyx_t_19, __pyx_t_20); - __pyx_t_18 = 0; __pyx_t_19 = 0; __pyx_t_20 = 0; __pyx_t_21 = 0; __pyx_t_22 = 0; __pyx_t_23 = 0; - __pyx_lineno = __pyx_t_8; __pyx_clineno = __pyx_t_16; __pyx_filename = __pyx_t_17; - goto __pyx_L5_except_error; - } - __pyx_L13_return: { - __pyx_t_16 = __pyx_r; - __Pyx_DECREF(__pyx_v_exc); - __pyx_v_exc = NULL; - __pyx_r = __pyx_t_16; - goto __pyx_L6_except_return; - } - } - } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; - - /* "aiohttp/_http_parser.pyx":739 - * cdef HttpParser pyparser = parser.data - * cdef bytes body = at[:length] - * try: # <<<<<<<<<<<<<< - * pyparser._payload.feed_data(body, length) - * except BaseException as exc: - */ - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); - goto __pyx_L1_error; - __pyx_L6_except_return:; - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); - goto __pyx_L0; - } - - /* "aiohttp/_http_parser.pyx":735 - * - * - * cdef int cb_on_body(cparser.llhttp_t* parser, # <<<<<<<<<<<<<< - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_XDECREF(__pyx_t_12); - __Pyx_XDECREF(__pyx_t_13); - __Pyx_XDECREF(__pyx_t_14); - __Pyx_XDECREF(__pyx_t_15); - __Pyx_AddTraceback("aiohttp._http_parser.cb_on_body", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_pyparser); - __Pyx_XDECREF(__pyx_v_body); - __Pyx_XDECREF(__pyx_v_exc); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":752 - * - * - * cdef int cb_on_message_complete(cparser.llhttp_t* parser) except -1: # <<<<<<<<<<<<<< - * cdef HttpParser pyparser = parser.data - * try: - */ - -static int __pyx_f_7aiohttp_12_http_parser_cb_on_message_complete(llhttp_t *__pyx_v_parser) { - struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_pyparser = 0; - PyObject *__pyx_v_exc = NULL; - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("cb_on_message_complete", 0); - - /* "aiohttp/_http_parser.pyx":753 - * - * cdef int cb_on_message_complete(cparser.llhttp_t* parser) except -1: - * cdef HttpParser pyparser = parser.data # <<<<<<<<<<<<<< - * try: - * pyparser._started = False - */ - __pyx_t_1 = ((PyObject *)__pyx_v_parser->data); - __Pyx_INCREF(__pyx_t_1); - __pyx_v_pyparser = ((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":754 - * cdef int cb_on_message_complete(cparser.llhttp_t* parser) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * pyparser._started = False - * pyparser._on_message_complete() - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); - __Pyx_XGOTREF(__pyx_t_2); - __Pyx_XGOTREF(__pyx_t_3); - __Pyx_XGOTREF(__pyx_t_4); - /*try:*/ { - - /* "aiohttp/_http_parser.pyx":755 - * cdef HttpParser pyparser = parser.data - * try: - * pyparser._started = False # <<<<<<<<<<<<<< - * pyparser._on_message_complete() - * except BaseException as exc: - */ - __pyx_v_pyparser->_started = 0; - - /* "aiohttp/_http_parser.pyx":756 - * try: - * pyparser._started = False - * pyparser._on_message_complete() # <<<<<<<<<<<<<< - * except BaseException as exc: - * pyparser._last_error = exc - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser *)__pyx_v_pyparser->__pyx_vtab)->_on_message_complete(__pyx_v_pyparser); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 756, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":754 - * cdef int cb_on_message_complete(cparser.llhttp_t* parser) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * pyparser._started = False - * pyparser._on_message_complete() - */ - } - - /* "aiohttp/_http_parser.pyx":761 - * return -1 - * else: - * return 0 # <<<<<<<<<<<<<< - * - * - */ - /*else:*/ { - __pyx_r = 0; - goto __pyx_L6_except_return; - } - __pyx_L3_error:; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":757 - * pyparser._started = False - * pyparser._on_message_complete() - * except BaseException as exc: # <<<<<<<<<<<<<< - * pyparser._last_error = exc - * return -1 - */ - __pyx_t_5 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_BaseException); - if (__pyx_t_5) { - __Pyx_AddTraceback("aiohttp._http_parser.cb_on_message_complete", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_1, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(0, 757, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GOTREF(__pyx_t_7); - __Pyx_INCREF(__pyx_t_6); - __pyx_v_exc = __pyx_t_6; - /*try:*/ { - - /* "aiohttp/_http_parser.pyx":758 - * pyparser._on_message_complete() - * except BaseException as exc: - * pyparser._last_error = exc # <<<<<<<<<<<<<< - * return -1 - * else: - */ - __Pyx_INCREF(__pyx_v_exc); - __Pyx_GIVEREF(__pyx_v_exc); - __Pyx_GOTREF(__pyx_v_pyparser->_last_error); - __Pyx_DECREF(__pyx_v_pyparser->_last_error); - __pyx_v_pyparser->_last_error = __pyx_v_exc; - - /* "aiohttp/_http_parser.pyx":759 - * except BaseException as exc: - * pyparser._last_error = exc - * return -1 # <<<<<<<<<<<<<< - * else: - * return 0 - */ - __pyx_r = -1; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - goto __pyx_L13_return; - } - - /* "aiohttp/_http_parser.pyx":757 - * pyparser._started = False - * pyparser._on_message_complete() - * except BaseException as exc: # <<<<<<<<<<<<<< - * pyparser._last_error = exc - * return -1 - */ - /*finally:*/ { - __pyx_L13_return: { - __pyx_t_5 = __pyx_r; - __Pyx_DECREF(__pyx_v_exc); - __pyx_v_exc = NULL; - __pyx_r = __pyx_t_5; - goto __pyx_L6_except_return; - } - } - } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; - - /* "aiohttp/_http_parser.pyx":754 - * cdef int cb_on_message_complete(cparser.llhttp_t* parser) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * pyparser._started = False - * pyparser._on_message_complete() - */ - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); - goto __pyx_L1_error; - __pyx_L6_except_return:; - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); - goto __pyx_L0; - } - - /* "aiohttp/_http_parser.pyx":752 - * - * - * cdef int cb_on_message_complete(cparser.llhttp_t* parser) except -1: # <<<<<<<<<<<<<< - * cdef HttpParser pyparser = parser.data - * try: - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_AddTraceback("aiohttp._http_parser.cb_on_message_complete", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_pyparser); - __Pyx_XDECREF(__pyx_v_exc); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":764 - * - * - * cdef int cb_on_chunk_header(cparser.llhttp_t* parser) except -1: # <<<<<<<<<<<<<< - * cdef HttpParser pyparser = parser.data - * try: - */ - -static int __pyx_f_7aiohttp_12_http_parser_cb_on_chunk_header(llhttp_t *__pyx_v_parser) { - struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_pyparser = 0; - PyObject *__pyx_v_exc = NULL; - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("cb_on_chunk_header", 0); - - /* "aiohttp/_http_parser.pyx":765 - * - * cdef int cb_on_chunk_header(cparser.llhttp_t* parser) except -1: - * cdef HttpParser pyparser = parser.data # <<<<<<<<<<<<<< - * try: - * pyparser._on_chunk_header() - */ - __pyx_t_1 = ((PyObject *)__pyx_v_parser->data); - __Pyx_INCREF(__pyx_t_1); - __pyx_v_pyparser = ((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":766 - * cdef int cb_on_chunk_header(cparser.llhttp_t* parser) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * pyparser._on_chunk_header() - * except BaseException as exc: - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); - __Pyx_XGOTREF(__pyx_t_2); - __Pyx_XGOTREF(__pyx_t_3); - __Pyx_XGOTREF(__pyx_t_4); - /*try:*/ { - - /* "aiohttp/_http_parser.pyx":767 - * cdef HttpParser pyparser = parser.data - * try: - * pyparser._on_chunk_header() # <<<<<<<<<<<<<< - * except BaseException as exc: - * pyparser._last_error = exc - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser *)__pyx_v_pyparser->__pyx_vtab)->_on_chunk_header(__pyx_v_pyparser); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 767, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":766 - * cdef int cb_on_chunk_header(cparser.llhttp_t* parser) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * pyparser._on_chunk_header() - * except BaseException as exc: - */ - } - - /* "aiohttp/_http_parser.pyx":772 - * return -1 - * else: - * return 0 # <<<<<<<<<<<<<< - * - * - */ - /*else:*/ { - __pyx_r = 0; - goto __pyx_L6_except_return; - } - __pyx_L3_error:; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":768 - * try: - * pyparser._on_chunk_header() - * except BaseException as exc: # <<<<<<<<<<<<<< - * pyparser._last_error = exc - * return -1 - */ - __pyx_t_5 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_BaseException); - if (__pyx_t_5) { - __Pyx_AddTraceback("aiohttp._http_parser.cb_on_chunk_header", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_1, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(0, 768, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GOTREF(__pyx_t_7); - __Pyx_INCREF(__pyx_t_6); - __pyx_v_exc = __pyx_t_6; - /*try:*/ { - - /* "aiohttp/_http_parser.pyx":769 - * pyparser._on_chunk_header() - * except BaseException as exc: - * pyparser._last_error = exc # <<<<<<<<<<<<<< - * return -1 - * else: - */ - __Pyx_INCREF(__pyx_v_exc); - __Pyx_GIVEREF(__pyx_v_exc); - __Pyx_GOTREF(__pyx_v_pyparser->_last_error); - __Pyx_DECREF(__pyx_v_pyparser->_last_error); - __pyx_v_pyparser->_last_error = __pyx_v_exc; - - /* "aiohttp/_http_parser.pyx":770 - * except BaseException as exc: - * pyparser._last_error = exc - * return -1 # <<<<<<<<<<<<<< - * else: - * return 0 - */ - __pyx_r = -1; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - goto __pyx_L13_return; - } - - /* "aiohttp/_http_parser.pyx":768 - * try: - * pyparser._on_chunk_header() - * except BaseException as exc: # <<<<<<<<<<<<<< - * pyparser._last_error = exc - * return -1 - */ - /*finally:*/ { - __pyx_L13_return: { - __pyx_t_5 = __pyx_r; - __Pyx_DECREF(__pyx_v_exc); - __pyx_v_exc = NULL; - __pyx_r = __pyx_t_5; - goto __pyx_L6_except_return; - } - } - } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; - - /* "aiohttp/_http_parser.pyx":766 - * cdef int cb_on_chunk_header(cparser.llhttp_t* parser) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * pyparser._on_chunk_header() - * except BaseException as exc: - */ - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); - goto __pyx_L1_error; - __pyx_L6_except_return:; - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); - goto __pyx_L0; - } - - /* "aiohttp/_http_parser.pyx":764 - * - * - * cdef int cb_on_chunk_header(cparser.llhttp_t* parser) except -1: # <<<<<<<<<<<<<< - * cdef HttpParser pyparser = parser.data - * try: - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_AddTraceback("aiohttp._http_parser.cb_on_chunk_header", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_pyparser); - __Pyx_XDECREF(__pyx_v_exc); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":775 - * - * - * cdef int cb_on_chunk_complete(cparser.llhttp_t* parser) except -1: # <<<<<<<<<<<<<< - * cdef HttpParser pyparser = parser.data - * try: - */ - -static int __pyx_f_7aiohttp_12_http_parser_cb_on_chunk_complete(llhttp_t *__pyx_v_parser) { - struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_pyparser = 0; - PyObject *__pyx_v_exc = NULL; - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("cb_on_chunk_complete", 0); - - /* "aiohttp/_http_parser.pyx":776 - * - * cdef int cb_on_chunk_complete(cparser.llhttp_t* parser) except -1: - * cdef HttpParser pyparser = parser.data # <<<<<<<<<<<<<< - * try: - * pyparser._on_chunk_complete() - */ - __pyx_t_1 = ((PyObject *)__pyx_v_parser->data); - __Pyx_INCREF(__pyx_t_1); - __pyx_v_pyparser = ((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":777 - * cdef int cb_on_chunk_complete(cparser.llhttp_t* parser) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * pyparser._on_chunk_complete() - * except BaseException as exc: - */ - { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); - __Pyx_XGOTREF(__pyx_t_2); - __Pyx_XGOTREF(__pyx_t_3); - __Pyx_XGOTREF(__pyx_t_4); - /*try:*/ { - - /* "aiohttp/_http_parser.pyx":778 - * cdef HttpParser pyparser = parser.data - * try: - * pyparser._on_chunk_complete() # <<<<<<<<<<<<<< - * except BaseException as exc: - * pyparser._last_error = exc - */ - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser *)__pyx_v_pyparser->__pyx_vtab)->_on_chunk_complete(__pyx_v_pyparser); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 778, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":777 - * cdef int cb_on_chunk_complete(cparser.llhttp_t* parser) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * pyparser._on_chunk_complete() - * except BaseException as exc: - */ - } - - /* "aiohttp/_http_parser.pyx":783 - * return -1 - * else: - * return 0 # <<<<<<<<<<<<<< - * - * - */ - /*else:*/ { - __pyx_r = 0; - goto __pyx_L6_except_return; - } - __pyx_L3_error:; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":779 - * try: - * pyparser._on_chunk_complete() - * except BaseException as exc: # <<<<<<<<<<<<<< - * pyparser._last_error = exc - * return -1 - */ - __pyx_t_5 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_BaseException); - if (__pyx_t_5) { - __Pyx_AddTraceback("aiohttp._http_parser.cb_on_chunk_complete", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_1, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(0, 779, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GOTREF(__pyx_t_7); - __Pyx_INCREF(__pyx_t_6); - __pyx_v_exc = __pyx_t_6; - /*try:*/ { - - /* "aiohttp/_http_parser.pyx":780 - * pyparser._on_chunk_complete() - * except BaseException as exc: - * pyparser._last_error = exc # <<<<<<<<<<<<<< - * return -1 - * else: - */ - __Pyx_INCREF(__pyx_v_exc); - __Pyx_GIVEREF(__pyx_v_exc); - __Pyx_GOTREF(__pyx_v_pyparser->_last_error); - __Pyx_DECREF(__pyx_v_pyparser->_last_error); - __pyx_v_pyparser->_last_error = __pyx_v_exc; - - /* "aiohttp/_http_parser.pyx":781 - * except BaseException as exc: - * pyparser._last_error = exc - * return -1 # <<<<<<<<<<<<<< - * else: - * return 0 - */ - __pyx_r = -1; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - goto __pyx_L13_return; - } - - /* "aiohttp/_http_parser.pyx":779 - * try: - * pyparser._on_chunk_complete() - * except BaseException as exc: # <<<<<<<<<<<<<< - * pyparser._last_error = exc - * return -1 - */ - /*finally:*/ { - __pyx_L13_return: { - __pyx_t_5 = __pyx_r; - __Pyx_DECREF(__pyx_v_exc); - __pyx_v_exc = NULL; - __pyx_r = __pyx_t_5; - goto __pyx_L6_except_return; - } - } - } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; - - /* "aiohttp/_http_parser.pyx":777 - * cdef int cb_on_chunk_complete(cparser.llhttp_t* parser) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * pyparser._on_chunk_complete() - * except BaseException as exc: - */ - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); - goto __pyx_L1_error; - __pyx_L6_except_return:; - __Pyx_XGIVEREF(__pyx_t_2); - __Pyx_XGIVEREF(__pyx_t_3); - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); - goto __pyx_L0; - } - - /* "aiohttp/_http_parser.pyx":775 - * - * - * cdef int cb_on_chunk_complete(cparser.llhttp_t* parser) except -1: # <<<<<<<<<<<<<< - * cdef HttpParser pyparser = parser.data - * try: - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_AddTraceback("aiohttp._http_parser.cb_on_chunk_complete", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_pyparser); - __Pyx_XDECREF(__pyx_v_exc); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":786 - * - * - * cdef parser_error_from_errno(cparser.llhttp_t* parser): # <<<<<<<<<<<<<< - * cdef cparser.llhttp_errno_t errno = cparser.llhttp_get_errno(parser) - * cdef bytes desc = cparser.llhttp_get_error_reason(parser) - */ - -static PyObject *__pyx_f_7aiohttp_12_http_parser_parser_error_from_errno(llhttp_t *__pyx_v_parser) { - llhttp_errno_t __pyx_v_errno; - PyObject *__pyx_v_desc = 0; - PyObject *__pyx_v_cls = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("parser_error_from_errno", 0); - - /* "aiohttp/_http_parser.pyx":787 - * - * cdef parser_error_from_errno(cparser.llhttp_t* parser): - * cdef cparser.llhttp_errno_t errno = cparser.llhttp_get_errno(parser) # <<<<<<<<<<<<<< - * cdef bytes desc = cparser.llhttp_get_error_reason(parser) - * - */ - __pyx_v_errno = llhttp_get_errno(__pyx_v_parser); - - /* "aiohttp/_http_parser.pyx":788 - * cdef parser_error_from_errno(cparser.llhttp_t* parser): - * cdef cparser.llhttp_errno_t errno = cparser.llhttp_get_errno(parser) - * cdef bytes desc = cparser.llhttp_get_error_reason(parser) # <<<<<<<<<<<<<< - * - * if errno in (cparser.HPE_CB_MESSAGE_BEGIN, - */ - __pyx_t_1 = __Pyx_PyBytes_FromString(llhttp_get_error_reason(__pyx_v_parser)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 788, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_desc = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":790 - * cdef bytes desc = cparser.llhttp_get_error_reason(parser) - * - * if errno in (cparser.HPE_CB_MESSAGE_BEGIN, # <<<<<<<<<<<<<< - * cparser.HPE_CB_HEADERS_COMPLETE, - * cparser.HPE_CB_MESSAGE_COMPLETE, - */ - switch (__pyx_v_errno) { - case HPE_CB_MESSAGE_BEGIN: - case HPE_CB_HEADERS_COMPLETE: - - /* "aiohttp/_http_parser.pyx":791 - * - * if errno in (cparser.HPE_CB_MESSAGE_BEGIN, - * cparser.HPE_CB_HEADERS_COMPLETE, # <<<<<<<<<<<<<< - * cparser.HPE_CB_MESSAGE_COMPLETE, - * cparser.HPE_CB_CHUNK_HEADER, - */ - case HPE_CB_MESSAGE_COMPLETE: - - /* "aiohttp/_http_parser.pyx":792 - * if errno in (cparser.HPE_CB_MESSAGE_BEGIN, - * cparser.HPE_CB_HEADERS_COMPLETE, - * cparser.HPE_CB_MESSAGE_COMPLETE, # <<<<<<<<<<<<<< - * cparser.HPE_CB_CHUNK_HEADER, - * cparser.HPE_CB_CHUNK_COMPLETE, - */ - case HPE_CB_CHUNK_HEADER: - - /* "aiohttp/_http_parser.pyx":793 - * cparser.HPE_CB_HEADERS_COMPLETE, - * cparser.HPE_CB_MESSAGE_COMPLETE, - * cparser.HPE_CB_CHUNK_HEADER, # <<<<<<<<<<<<<< - * cparser.HPE_CB_CHUNK_COMPLETE, - * cparser.HPE_INVALID_CONSTANT, - */ - case HPE_CB_CHUNK_COMPLETE: - - /* "aiohttp/_http_parser.pyx":794 - * cparser.HPE_CB_MESSAGE_COMPLETE, - * cparser.HPE_CB_CHUNK_HEADER, - * cparser.HPE_CB_CHUNK_COMPLETE, # <<<<<<<<<<<<<< - * cparser.HPE_INVALID_CONSTANT, - * cparser.HPE_INVALID_HEADER_TOKEN, - */ - case HPE_INVALID_CONSTANT: - - /* "aiohttp/_http_parser.pyx":795 - * cparser.HPE_CB_CHUNK_HEADER, - * cparser.HPE_CB_CHUNK_COMPLETE, - * cparser.HPE_INVALID_CONSTANT, # <<<<<<<<<<<<<< - * cparser.HPE_INVALID_HEADER_TOKEN, - * cparser.HPE_INVALID_CONTENT_LENGTH, - */ - case HPE_INVALID_HEADER_TOKEN: - - /* "aiohttp/_http_parser.pyx":796 - * cparser.HPE_CB_CHUNK_COMPLETE, - * cparser.HPE_INVALID_CONSTANT, - * cparser.HPE_INVALID_HEADER_TOKEN, # <<<<<<<<<<<<<< - * cparser.HPE_INVALID_CONTENT_LENGTH, - * cparser.HPE_INVALID_CHUNK_SIZE, - */ - case HPE_INVALID_CONTENT_LENGTH: - - /* "aiohttp/_http_parser.pyx":797 - * cparser.HPE_INVALID_CONSTANT, - * cparser.HPE_INVALID_HEADER_TOKEN, - * cparser.HPE_INVALID_CONTENT_LENGTH, # <<<<<<<<<<<<<< - * cparser.HPE_INVALID_CHUNK_SIZE, - * cparser.HPE_INVALID_EOF_STATE, - */ - case HPE_INVALID_CHUNK_SIZE: - - /* "aiohttp/_http_parser.pyx":798 - * cparser.HPE_INVALID_HEADER_TOKEN, - * cparser.HPE_INVALID_CONTENT_LENGTH, - * cparser.HPE_INVALID_CHUNK_SIZE, # <<<<<<<<<<<<<< - * cparser.HPE_INVALID_EOF_STATE, - * cparser.HPE_INVALID_TRANSFER_ENCODING): - */ - case HPE_INVALID_EOF_STATE: - - /* "aiohttp/_http_parser.pyx":799 - * cparser.HPE_INVALID_CONTENT_LENGTH, - * cparser.HPE_INVALID_CHUNK_SIZE, - * cparser.HPE_INVALID_EOF_STATE, # <<<<<<<<<<<<<< - * cparser.HPE_INVALID_TRANSFER_ENCODING): - * cls = BadHttpMessage - */ - case HPE_INVALID_TRANSFER_ENCODING: - - /* "aiohttp/_http_parser.pyx":801 - * cparser.HPE_INVALID_EOF_STATE, - * cparser.HPE_INVALID_TRANSFER_ENCODING): - * cls = BadHttpMessage # <<<<<<<<<<<<<< - * - * elif errno == cparser.HPE_INVALID_STATUS: - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_BadHttpMessage); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 801, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_cls = __pyx_t_1; - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":790 - * cdef bytes desc = cparser.llhttp_get_error_reason(parser) - * - * if errno in (cparser.HPE_CB_MESSAGE_BEGIN, # <<<<<<<<<<<<<< - * cparser.HPE_CB_HEADERS_COMPLETE, - * cparser.HPE_CB_MESSAGE_COMPLETE, - */ - break; - case HPE_INVALID_STATUS: - - /* "aiohttp/_http_parser.pyx":804 - * - * elif errno == cparser.HPE_INVALID_STATUS: - * cls = BadStatusLine # <<<<<<<<<<<<<< - * - * elif errno == cparser.HPE_INVALID_METHOD: - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_BadStatusLine); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 804, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_cls = __pyx_t_1; - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":803 - * cls = BadHttpMessage - * - * elif errno == cparser.HPE_INVALID_STATUS: # <<<<<<<<<<<<<< - * cls = BadStatusLine - * - */ - break; - case HPE_INVALID_METHOD: - - /* "aiohttp/_http_parser.pyx":807 - * - * elif errno == cparser.HPE_INVALID_METHOD: - * cls = BadStatusLine # <<<<<<<<<<<<<< - * - * elif errno == cparser.HPE_INVALID_VERSION: - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_BadStatusLine); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 807, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_cls = __pyx_t_1; - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":806 - * cls = BadStatusLine - * - * elif errno == cparser.HPE_INVALID_METHOD: # <<<<<<<<<<<<<< - * cls = BadStatusLine - * - */ - break; - case HPE_INVALID_VERSION: - - /* "aiohttp/_http_parser.pyx":810 - * - * elif errno == cparser.HPE_INVALID_VERSION: - * cls = BadStatusLine # <<<<<<<<<<<<<< - * - * elif errno == cparser.HPE_INVALID_URL: - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_BadStatusLine); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 810, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_cls = __pyx_t_1; - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":809 - * cls = BadStatusLine - * - * elif errno == cparser.HPE_INVALID_VERSION: # <<<<<<<<<<<<<< - * cls = BadStatusLine - * - */ - break; - case HPE_INVALID_URL: - - /* "aiohttp/_http_parser.pyx":813 - * - * elif errno == cparser.HPE_INVALID_URL: - * cls = InvalidURLError # <<<<<<<<<<<<<< - * - * else: - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_InvalidURLError); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 813, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_cls = __pyx_t_1; - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":812 - * cls = BadStatusLine - * - * elif errno == cparser.HPE_INVALID_URL: # <<<<<<<<<<<<<< - * cls = InvalidURLError - * - */ - break; - default: - - /* "aiohttp/_http_parser.pyx":816 - * - * else: - * cls = BadHttpMessage # <<<<<<<<<<<<<< - * - * return cls(desc.decode('latin-1')) - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_BadHttpMessage); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 816, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_cls = __pyx_t_1; - __pyx_t_1 = 0; - break; - } - - /* "aiohttp/_http_parser.pyx":818 - * cls = BadHttpMessage - * - * return cls(desc.decode('latin-1')) # <<<<<<<<<<<<<< - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __Pyx_decode_bytes(__pyx_v_desc, 0, PY_SSIZE_T_MAX, NULL, NULL, PyUnicode_DecodeLatin1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 818, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_v_cls); - __pyx_t_3 = __pyx_v_cls; __pyx_t_4 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - } - } - __pyx_t_1 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_4, __pyx_t_2) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_2); - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 818, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L0; - - /* "aiohttp/_http_parser.pyx":786 - * - * - * cdef parser_error_from_errno(cparser.llhttp_t* parser): # <<<<<<<<<<<<<< - * cdef cparser.llhttp_errno_t errno = cparser.llhttp_get_errno(parser) - * cdef bytes desc = cparser.llhttp_get_error_reason(parser) - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("aiohttp._http_parser.parser_error_from_errno", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_desc); - __Pyx_XDECREF(__pyx_v_cls); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":1 - * def __pyx_unpickle_RawRequestMessage(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * cdef object __pyx_PickleError - * cdef object __pyx_result - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_1__pyx_unpickle_RawRequestMessage(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyMethodDef __pyx_mdef_7aiohttp_12_http_parser_1__pyx_unpickle_RawRequestMessage = {"__pyx_unpickle_RawRequestMessage", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_7aiohttp_12_http_parser_1__pyx_unpickle_RawRequestMessage, METH_VARARGS|METH_KEYWORDS, 0}; -static PyObject *__pyx_pw_7aiohttp_12_http_parser_1__pyx_unpickle_RawRequestMessage(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v___pyx_type = 0; - long __pyx_v___pyx_checksum; - PyObject *__pyx_v___pyx_state = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__pyx_unpickle_RawRequestMessage (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pyx_type,&__pyx_n_s_pyx_checksum,&__pyx_n_s_pyx_state,0}; - PyObject* values[3] = {0,0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_type)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_checksum)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_RawRequestMessage", 1, 3, 3, 1); __PYX_ERR(1, 1, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_state)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_RawRequestMessage", 1, 3, 3, 2); __PYX_ERR(1, 1, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__pyx_unpickle_RawRequestMessage") < 0)) __PYX_ERR(1, 1, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - } - __pyx_v___pyx_type = values[0]; - __pyx_v___pyx_checksum = __Pyx_PyInt_As_long(values[1]); if (unlikely((__pyx_v___pyx_checksum == (long)-1) && PyErr_Occurred())) __PYX_ERR(1, 1, __pyx_L3_error) - __pyx_v___pyx_state = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_RawRequestMessage", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(1, 1, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._http_parser.__pyx_unpickle_RawRequestMessage", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_12_http_parser___pyx_unpickle_RawRequestMessage(__pyx_self, __pyx_v___pyx_type, __pyx_v___pyx_checksum, __pyx_v___pyx_state); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser___pyx_unpickle_RawRequestMessage(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_v___pyx_PickleError = 0; - PyObject *__pyx_v___pyx_result = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__pyx_unpickle_RawRequestMessage", 0); - - /* "(tree fragment)":4 - * cdef object __pyx_PickleError - * cdef object __pyx_result - * if __pyx_checksum != 0x1408252: # <<<<<<<<<<<<<< - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (%s vs 0x1408252 = (chunked, compression, headers, method, path, raw_headers, should_close, upgrade, url, version))" % __pyx_checksum) - */ - __pyx_t_1 = ((__pyx_v___pyx_checksum != 0x1408252) != 0); - if (__pyx_t_1) { - - /* "(tree fragment)":5 - * cdef object __pyx_result - * if __pyx_checksum != 0x1408252: - * from pickle import PickleError as __pyx_PickleError # <<<<<<<<<<<<<< - * raise __pyx_PickleError("Incompatible checksums (%s vs 0x1408252 = (chunked, compression, headers, method, path, raw_headers, should_close, upgrade, url, version))" % __pyx_checksum) - * __pyx_result = RawRequestMessage.__new__(__pyx_type) - */ - __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_n_s_PickleError); - __Pyx_GIVEREF(__pyx_n_s_PickleError); - PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_PickleError); - __pyx_t_3 = __Pyx_Import(__pyx_n_s_pickle, __pyx_t_2, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_3, __pyx_n_s_PickleError); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_2); - __pyx_v___pyx_PickleError = __pyx_t_2; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "(tree fragment)":6 - * if __pyx_checksum != 0x1408252: - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (%s vs 0x1408252 = (chunked, compression, headers, method, path, raw_headers, should_close, upgrade, url, version))" % __pyx_checksum) # <<<<<<<<<<<<<< - * __pyx_result = RawRequestMessage.__new__(__pyx_type) - * if __pyx_state is not None: - */ - __pyx_t_2 = __Pyx_PyInt_From_long(__pyx_v___pyx_checksum); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Incompatible_checksums_s_vs_0x14, __pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_INCREF(__pyx_v___pyx_PickleError); - __pyx_t_2 = __pyx_v___pyx_PickleError; __pyx_t_5 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - __pyx_t_3 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_5, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 6, __pyx_L1_error) - - /* "(tree fragment)":4 - * cdef object __pyx_PickleError - * cdef object __pyx_result - * if __pyx_checksum != 0x1408252: # <<<<<<<<<<<<<< - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (%s vs 0x1408252 = (chunked, compression, headers, method, path, raw_headers, should_close, upgrade, url, version))" % __pyx_checksum) - */ - } - - /* "(tree fragment)":7 - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (%s vs 0x1408252 = (chunked, compression, headers, method, path, raw_headers, should_close, upgrade, url, version))" % __pyx_checksum) - * __pyx_result = RawRequestMessage.__new__(__pyx_type) # <<<<<<<<<<<<<< - * if __pyx_state is not None: - * __pyx_unpickle_RawRequestMessage__set_state( __pyx_result, __pyx_state) - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_ptype_7aiohttp_12_http_parser_RawRequestMessage), __pyx_n_s_new); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 7, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - __pyx_t_3 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_4, __pyx_v___pyx_type) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v___pyx_type); - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 7, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v___pyx_result = __pyx_t_3; - __pyx_t_3 = 0; - - /* "(tree fragment)":8 - * raise __pyx_PickleError("Incompatible checksums (%s vs 0x1408252 = (chunked, compression, headers, method, path, raw_headers, should_close, upgrade, url, version))" % __pyx_checksum) - * __pyx_result = RawRequestMessage.__new__(__pyx_type) - * if __pyx_state is not None: # <<<<<<<<<<<<<< - * __pyx_unpickle_RawRequestMessage__set_state( __pyx_result, __pyx_state) - * return __pyx_result - */ - __pyx_t_1 = (__pyx_v___pyx_state != Py_None); - __pyx_t_6 = (__pyx_t_1 != 0); - if (__pyx_t_6) { - - /* "(tree fragment)":9 - * __pyx_result = RawRequestMessage.__new__(__pyx_type) - * if __pyx_state is not None: - * __pyx_unpickle_RawRequestMessage__set_state( __pyx_result, __pyx_state) # <<<<<<<<<<<<<< - * return __pyx_result - * cdef __pyx_unpickle_RawRequestMessage__set_state(RawRequestMessage __pyx_result, tuple __pyx_state): - */ - if (!(likely(PyTuple_CheckExact(__pyx_v___pyx_state))||((__pyx_v___pyx_state) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(1, 9, __pyx_L1_error) - __pyx_t_3 = __pyx_f_7aiohttp_12_http_parser___pyx_unpickle_RawRequestMessage__set_state(((struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *)__pyx_v___pyx_result), ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 9, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "(tree fragment)":8 - * raise __pyx_PickleError("Incompatible checksums (%s vs 0x1408252 = (chunked, compression, headers, method, path, raw_headers, should_close, upgrade, url, version))" % __pyx_checksum) - * __pyx_result = RawRequestMessage.__new__(__pyx_type) - * if __pyx_state is not None: # <<<<<<<<<<<<<< - * __pyx_unpickle_RawRequestMessage__set_state( __pyx_result, __pyx_state) - * return __pyx_result - */ - } - - /* "(tree fragment)":10 - * if __pyx_state is not None: - * __pyx_unpickle_RawRequestMessage__set_state( __pyx_result, __pyx_state) - * return __pyx_result # <<<<<<<<<<<<<< - * cdef __pyx_unpickle_RawRequestMessage__set_state(RawRequestMessage __pyx_result, tuple __pyx_state): - * __pyx_result.chunked = __pyx_state[0]; __pyx_result.compression = __pyx_state[1]; __pyx_result.headers = __pyx_state[2]; __pyx_result.method = __pyx_state[3]; __pyx_result.path = __pyx_state[4]; __pyx_result.raw_headers = __pyx_state[5]; __pyx_result.should_close = __pyx_state[6]; __pyx_result.upgrade = __pyx_state[7]; __pyx_result.url = __pyx_state[8]; __pyx_result.version = __pyx_state[9] - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v___pyx_result); - __pyx_r = __pyx_v___pyx_result; - goto __pyx_L0; - - /* "(tree fragment)":1 - * def __pyx_unpickle_RawRequestMessage(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * cdef object __pyx_PickleError - * cdef object __pyx_result - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("aiohttp._http_parser.__pyx_unpickle_RawRequestMessage", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v___pyx_PickleError); - __Pyx_XDECREF(__pyx_v___pyx_result); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":11 - * __pyx_unpickle_RawRequestMessage__set_state( __pyx_result, __pyx_state) - * return __pyx_result - * cdef __pyx_unpickle_RawRequestMessage__set_state(RawRequestMessage __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< - * __pyx_result.chunked = __pyx_state[0]; __pyx_result.compression = __pyx_state[1]; __pyx_result.headers = __pyx_state[2]; __pyx_result.method = __pyx_state[3]; __pyx_result.path = __pyx_state[4]; __pyx_result.raw_headers = __pyx_state[5]; __pyx_result.should_close = __pyx_state[6]; __pyx_result.upgrade = __pyx_state[7]; __pyx_result.url = __pyx_state[8]; __pyx_result.version = __pyx_state[9] - * if len(__pyx_state) > 10 and hasattr(__pyx_result, '__dict__'): - */ - -static PyObject *__pyx_f_7aiohttp_12_http_parser___pyx_unpickle_RawRequestMessage__set_state(struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *__pyx_v___pyx_result, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - Py_ssize_t __pyx_t_3; - int __pyx_t_4; - int __pyx_t_5; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__pyx_unpickle_RawRequestMessage__set_state", 0); - - /* "(tree fragment)":12 - * return __pyx_result - * cdef __pyx_unpickle_RawRequestMessage__set_state(RawRequestMessage __pyx_result, tuple __pyx_state): - * __pyx_result.chunked = __pyx_state[0]; __pyx_result.compression = __pyx_state[1]; __pyx_result.headers = __pyx_state[2]; __pyx_result.method = __pyx_state[3]; __pyx_result.path = __pyx_state[4]; __pyx_result.raw_headers = __pyx_state[5]; __pyx_result.should_close = __pyx_state[6]; __pyx_result.upgrade = __pyx_state[7]; __pyx_result.url = __pyx_state[8]; __pyx_result.version = __pyx_state[9] # <<<<<<<<<<<<<< - * if len(__pyx_state) > 10 and hasattr(__pyx_result, '__dict__'): - * __pyx_result.__dict__.update(__pyx_state[10]) - */ - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 12, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v___pyx_result->chunked); - __Pyx_DECREF(__pyx_v___pyx_result->chunked); - __pyx_v___pyx_result->chunked = __pyx_t_1; - __pyx_t_1 = 0; - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 12, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v___pyx_result->compression); - __Pyx_DECREF(__pyx_v___pyx_result->compression); - __pyx_v___pyx_result->compression = __pyx_t_1; - __pyx_t_1 = 0; - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 12, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 2, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v___pyx_result->headers); - __Pyx_DECREF(__pyx_v___pyx_result->headers); - __pyx_v___pyx_result->headers = __pyx_t_1; - __pyx_t_1 = 0; - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 12, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 3, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(PyUnicode_CheckExact(__pyx_t_1))||((__pyx_t_1) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "unicode", Py_TYPE(__pyx_t_1)->tp_name), 0))) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v___pyx_result->method); - __Pyx_DECREF(__pyx_v___pyx_result->method); - __pyx_v___pyx_result->method = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 12, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 4, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(PyUnicode_CheckExact(__pyx_t_1))||((__pyx_t_1) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "unicode", Py_TYPE(__pyx_t_1)->tp_name), 0))) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v___pyx_result->path); - __Pyx_DECREF(__pyx_v___pyx_result->path); - __pyx_v___pyx_result->path = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 12, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 5, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v___pyx_result->raw_headers); - __Pyx_DECREF(__pyx_v___pyx_result->raw_headers); - __pyx_v___pyx_result->raw_headers = __pyx_t_1; - __pyx_t_1 = 0; - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 12, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 6, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v___pyx_result->should_close); - __Pyx_DECREF(__pyx_v___pyx_result->should_close); - __pyx_v___pyx_result->should_close = __pyx_t_1; - __pyx_t_1 = 0; - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 12, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 7, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v___pyx_result->upgrade); - __Pyx_DECREF(__pyx_v___pyx_result->upgrade); - __pyx_v___pyx_result->upgrade = __pyx_t_1; - __pyx_t_1 = 0; - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 12, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 8, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v___pyx_result->url); - __Pyx_DECREF(__pyx_v___pyx_result->url); - __pyx_v___pyx_result->url = __pyx_t_1; - __pyx_t_1 = 0; - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 12, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 9, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v___pyx_result->version); - __Pyx_DECREF(__pyx_v___pyx_result->version); - __pyx_v___pyx_result->version = __pyx_t_1; - __pyx_t_1 = 0; - - /* "(tree fragment)":13 - * cdef __pyx_unpickle_RawRequestMessage__set_state(RawRequestMessage __pyx_result, tuple __pyx_state): - * __pyx_result.chunked = __pyx_state[0]; __pyx_result.compression = __pyx_state[1]; __pyx_result.headers = __pyx_state[2]; __pyx_result.method = __pyx_state[3]; __pyx_result.path = __pyx_state[4]; __pyx_result.raw_headers = __pyx_state[5]; __pyx_result.should_close = __pyx_state[6]; __pyx_result.upgrade = __pyx_state[7]; __pyx_result.url = __pyx_state[8]; __pyx_result.version = __pyx_state[9] - * if len(__pyx_state) > 10 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< - * __pyx_result.__dict__.update(__pyx_state[10]) - */ - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - __PYX_ERR(1, 13, __pyx_L1_error) - } - __pyx_t_3 = PyTuple_GET_SIZE(__pyx_v___pyx_state); if (unlikely(__pyx_t_3 == ((Py_ssize_t)-1))) __PYX_ERR(1, 13, __pyx_L1_error) - __pyx_t_4 = ((__pyx_t_3 > 10) != 0); - if (__pyx_t_4) { - } else { - __pyx_t_2 = __pyx_t_4; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_4 = __Pyx_HasAttr(((PyObject *)__pyx_v___pyx_result), __pyx_n_s_dict); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 13, __pyx_L1_error) - __pyx_t_5 = (__pyx_t_4 != 0); - __pyx_t_2 = __pyx_t_5; - __pyx_L4_bool_binop_done:; - if (__pyx_t_2) { - - /* "(tree fragment)":14 - * __pyx_result.chunked = __pyx_state[0]; __pyx_result.compression = __pyx_state[1]; __pyx_result.headers = __pyx_state[2]; __pyx_result.method = __pyx_state[3]; __pyx_result.path = __pyx_state[4]; __pyx_result.raw_headers = __pyx_state[5]; __pyx_result.should_close = __pyx_state[6]; __pyx_result.upgrade = __pyx_state[7]; __pyx_result.url = __pyx_state[8]; __pyx_result.version = __pyx_state[9] - * if len(__pyx_state) > 10 and hasattr(__pyx_result, '__dict__'): - * __pyx_result.__dict__.update(__pyx_state[10]) # <<<<<<<<<<<<<< - */ - __pyx_t_6 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v___pyx_result), __pyx_n_s_dict); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_update); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 14, __pyx_L1_error) - } - __pyx_t_6 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 10, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_8 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_7))) { - __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_7); - if (likely(__pyx_t_8)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); - __Pyx_INCREF(__pyx_t_8); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_7, function); - } - } - __pyx_t_1 = (__pyx_t_8) ? __Pyx_PyObject_Call2Args(__pyx_t_7, __pyx_t_8, __pyx_t_6) : __Pyx_PyObject_CallOneArg(__pyx_t_7, __pyx_t_6); - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "(tree fragment)":13 - * cdef __pyx_unpickle_RawRequestMessage__set_state(RawRequestMessage __pyx_result, tuple __pyx_state): - * __pyx_result.chunked = __pyx_state[0]; __pyx_result.compression = __pyx_state[1]; __pyx_result.headers = __pyx_state[2]; __pyx_result.method = __pyx_state[3]; __pyx_result.path = __pyx_state[4]; __pyx_result.raw_headers = __pyx_state[5]; __pyx_result.should_close = __pyx_state[6]; __pyx_result.upgrade = __pyx_state[7]; __pyx_result.url = __pyx_state[8]; __pyx_result.version = __pyx_state[9] - * if len(__pyx_state) > 10 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< - * __pyx_result.__dict__.update(__pyx_state[10]) - */ - } - - /* "(tree fragment)":11 - * __pyx_unpickle_RawRequestMessage__set_state( __pyx_result, __pyx_state) - * return __pyx_result - * cdef __pyx_unpickle_RawRequestMessage__set_state(RawRequestMessage __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< - * __pyx_result.chunked = __pyx_state[0]; __pyx_result.compression = __pyx_state[1]; __pyx_result.headers = __pyx_state[2]; __pyx_result.method = __pyx_state[3]; __pyx_result.path = __pyx_state[4]; __pyx_result.raw_headers = __pyx_state[5]; __pyx_result.should_close = __pyx_state[6]; __pyx_result.upgrade = __pyx_state[7]; __pyx_result.url = __pyx_state[8]; __pyx_result.version = __pyx_state[9] - * if len(__pyx_state) > 10 and hasattr(__pyx_result, '__dict__'): - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_AddTraceback("aiohttp._http_parser.__pyx_unpickle_RawRequestMessage__set_state", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":1 - * def __pyx_unpickle_RawResponseMessage(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * cdef object __pyx_PickleError - * cdef object __pyx_result - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_3__pyx_unpickle_RawResponseMessage(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyMethodDef __pyx_mdef_7aiohttp_12_http_parser_3__pyx_unpickle_RawResponseMessage = {"__pyx_unpickle_RawResponseMessage", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_7aiohttp_12_http_parser_3__pyx_unpickle_RawResponseMessage, METH_VARARGS|METH_KEYWORDS, 0}; -static PyObject *__pyx_pw_7aiohttp_12_http_parser_3__pyx_unpickle_RawResponseMessage(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v___pyx_type = 0; - long __pyx_v___pyx_checksum; - PyObject *__pyx_v___pyx_state = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__pyx_unpickle_RawResponseMessage (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pyx_type,&__pyx_n_s_pyx_checksum,&__pyx_n_s_pyx_state,0}; - PyObject* values[3] = {0,0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - CYTHON_FALLTHROUGH; - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_type)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_checksum)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_RawResponseMessage", 1, 3, 3, 1); __PYX_ERR(1, 1, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (likely((values[2] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_pyx_state)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_RawResponseMessage", 1, 3, 3, 2); __PYX_ERR(1, 1, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__pyx_unpickle_RawResponseMessage") < 0)) __PYX_ERR(1, 1, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - values[2] = PyTuple_GET_ITEM(__pyx_args, 2); - } - __pyx_v___pyx_type = values[0]; - __pyx_v___pyx_checksum = __Pyx_PyInt_As_long(values[1]); if (unlikely((__pyx_v___pyx_checksum == (long)-1) && PyErr_Occurred())) __PYX_ERR(1, 1, __pyx_L3_error) - __pyx_v___pyx_state = values[2]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_RawResponseMessage", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(1, 1, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._http_parser.__pyx_unpickle_RawResponseMessage", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_2__pyx_unpickle_RawResponseMessage(__pyx_self, __pyx_v___pyx_type, __pyx_v___pyx_checksum, __pyx_v___pyx_state); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_2__pyx_unpickle_RawResponseMessage(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_v___pyx_PickleError = 0; - PyObject *__pyx_v___pyx_result = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__pyx_unpickle_RawResponseMessage", 0); - - /* "(tree fragment)":4 - * cdef object __pyx_PickleError - * cdef object __pyx_result - * if __pyx_checksum != 0xc7706dc: # <<<<<<<<<<<<<< - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xc7706dc = (chunked, code, compression, headers, raw_headers, reason, should_close, upgrade, version))" % __pyx_checksum) - */ - __pyx_t_1 = ((__pyx_v___pyx_checksum != 0xc7706dc) != 0); - if (__pyx_t_1) { - - /* "(tree fragment)":5 - * cdef object __pyx_result - * if __pyx_checksum != 0xc7706dc: - * from pickle import PickleError as __pyx_PickleError # <<<<<<<<<<<<<< - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xc7706dc = (chunked, code, compression, headers, raw_headers, reason, should_close, upgrade, version))" % __pyx_checksum) - * __pyx_result = RawResponseMessage.__new__(__pyx_type) - */ - __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_n_s_PickleError); - __Pyx_GIVEREF(__pyx_n_s_PickleError); - PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_PickleError); - __pyx_t_3 = __Pyx_Import(__pyx_n_s_pickle, __pyx_t_2, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_3, __pyx_n_s_PickleError); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_t_2); - __pyx_v___pyx_PickleError = __pyx_t_2; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "(tree fragment)":6 - * if __pyx_checksum != 0xc7706dc: - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xc7706dc = (chunked, code, compression, headers, raw_headers, reason, should_close, upgrade, version))" % __pyx_checksum) # <<<<<<<<<<<<<< - * __pyx_result = RawResponseMessage.__new__(__pyx_type) - * if __pyx_state is not None: - */ - __pyx_t_2 = __Pyx_PyInt_From_long(__pyx_v___pyx_checksum); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Incompatible_checksums_s_vs_0xc7, __pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_INCREF(__pyx_v___pyx_PickleError); - __pyx_t_2 = __pyx_v___pyx_PickleError; __pyx_t_5 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - __pyx_t_3 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_5, __pyx_t_4) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(1, 6, __pyx_L1_error) - - /* "(tree fragment)":4 - * cdef object __pyx_PickleError - * cdef object __pyx_result - * if __pyx_checksum != 0xc7706dc: # <<<<<<<<<<<<<< - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xc7706dc = (chunked, code, compression, headers, raw_headers, reason, should_close, upgrade, version))" % __pyx_checksum) - */ - } - - /* "(tree fragment)":7 - * from pickle import PickleError as __pyx_PickleError - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xc7706dc = (chunked, code, compression, headers, raw_headers, reason, should_close, upgrade, version))" % __pyx_checksum) - * __pyx_result = RawResponseMessage.__new__(__pyx_type) # <<<<<<<<<<<<<< - * if __pyx_state is not None: - * __pyx_unpickle_RawResponseMessage__set_state( __pyx_result, __pyx_state) - */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_ptype_7aiohttp_12_http_parser_RawResponseMessage), __pyx_n_s_new); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 7, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_2, function); - } - } - __pyx_t_3 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_4, __pyx_v___pyx_type) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v___pyx_type); - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 7, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_v___pyx_result = __pyx_t_3; - __pyx_t_3 = 0; - - /* "(tree fragment)":8 - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xc7706dc = (chunked, code, compression, headers, raw_headers, reason, should_close, upgrade, version))" % __pyx_checksum) - * __pyx_result = RawResponseMessage.__new__(__pyx_type) - * if __pyx_state is not None: # <<<<<<<<<<<<<< - * __pyx_unpickle_RawResponseMessage__set_state( __pyx_result, __pyx_state) - * return __pyx_result - */ - __pyx_t_1 = (__pyx_v___pyx_state != Py_None); - __pyx_t_6 = (__pyx_t_1 != 0); - if (__pyx_t_6) { - - /* "(tree fragment)":9 - * __pyx_result = RawResponseMessage.__new__(__pyx_type) - * if __pyx_state is not None: - * __pyx_unpickle_RawResponseMessage__set_state( __pyx_result, __pyx_state) # <<<<<<<<<<<<<< - * return __pyx_result - * cdef __pyx_unpickle_RawResponseMessage__set_state(RawResponseMessage __pyx_result, tuple __pyx_state): - */ - if (!(likely(PyTuple_CheckExact(__pyx_v___pyx_state))||((__pyx_v___pyx_state) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(1, 9, __pyx_L1_error) - __pyx_t_3 = __pyx_f_7aiohttp_12_http_parser___pyx_unpickle_RawResponseMessage__set_state(((struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *)__pyx_v___pyx_result), ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 9, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "(tree fragment)":8 - * raise __pyx_PickleError("Incompatible checksums (%s vs 0xc7706dc = (chunked, code, compression, headers, raw_headers, reason, should_close, upgrade, version))" % __pyx_checksum) - * __pyx_result = RawResponseMessage.__new__(__pyx_type) - * if __pyx_state is not None: # <<<<<<<<<<<<<< - * __pyx_unpickle_RawResponseMessage__set_state( __pyx_result, __pyx_state) - * return __pyx_result - */ - } - - /* "(tree fragment)":10 - * if __pyx_state is not None: - * __pyx_unpickle_RawResponseMessage__set_state( __pyx_result, __pyx_state) - * return __pyx_result # <<<<<<<<<<<<<< - * cdef __pyx_unpickle_RawResponseMessage__set_state(RawResponseMessage __pyx_result, tuple __pyx_state): - * __pyx_result.chunked = __pyx_state[0]; __pyx_result.code = __pyx_state[1]; __pyx_result.compression = __pyx_state[2]; __pyx_result.headers = __pyx_state[3]; __pyx_result.raw_headers = __pyx_state[4]; __pyx_result.reason = __pyx_state[5]; __pyx_result.should_close = __pyx_state[6]; __pyx_result.upgrade = __pyx_state[7]; __pyx_result.version = __pyx_state[8] - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(__pyx_v___pyx_result); - __pyx_r = __pyx_v___pyx_result; - goto __pyx_L0; - - /* "(tree fragment)":1 - * def __pyx_unpickle_RawResponseMessage(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * cdef object __pyx_PickleError - * cdef object __pyx_result - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("aiohttp._http_parser.__pyx_unpickle_RawResponseMessage", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v___pyx_PickleError); - __Pyx_XDECREF(__pyx_v___pyx_result); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "(tree fragment)":11 - * __pyx_unpickle_RawResponseMessage__set_state( __pyx_result, __pyx_state) - * return __pyx_result - * cdef __pyx_unpickle_RawResponseMessage__set_state(RawResponseMessage __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< - * __pyx_result.chunked = __pyx_state[0]; __pyx_result.code = __pyx_state[1]; __pyx_result.compression = __pyx_state[2]; __pyx_result.headers = __pyx_state[3]; __pyx_result.raw_headers = __pyx_state[4]; __pyx_result.reason = __pyx_state[5]; __pyx_result.should_close = __pyx_state[6]; __pyx_result.upgrade = __pyx_state[7]; __pyx_result.version = __pyx_state[8] - * if len(__pyx_state) > 9 and hasattr(__pyx_result, '__dict__'): - */ - -static PyObject *__pyx_f_7aiohttp_12_http_parser___pyx_unpickle_RawResponseMessage__set_state(struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *__pyx_v___pyx_result, PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - int __pyx_t_3; - Py_ssize_t __pyx_t_4; - int __pyx_t_5; - int __pyx_t_6; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__pyx_unpickle_RawResponseMessage__set_state", 0); - - /* "(tree fragment)":12 - * return __pyx_result - * cdef __pyx_unpickle_RawResponseMessage__set_state(RawResponseMessage __pyx_result, tuple __pyx_state): - * __pyx_result.chunked = __pyx_state[0]; __pyx_result.code = __pyx_state[1]; __pyx_result.compression = __pyx_state[2]; __pyx_result.headers = __pyx_state[3]; __pyx_result.raw_headers = __pyx_state[4]; __pyx_result.reason = __pyx_state[5]; __pyx_result.should_close = __pyx_state[6]; __pyx_result.upgrade = __pyx_state[7]; __pyx_result.version = __pyx_state[8] # <<<<<<<<<<<<<< - * if len(__pyx_state) > 9 and hasattr(__pyx_result, '__dict__'): - * __pyx_result.__dict__.update(__pyx_state[9]) - */ - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 12, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v___pyx_result->chunked); - __Pyx_DECREF(__pyx_v___pyx_result->chunked); - __pyx_v___pyx_result->chunked = __pyx_t_1; - __pyx_t_1 = 0; - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 12, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v___pyx_result->code = __pyx_t_2; - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 12, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 2, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v___pyx_result->compression); - __Pyx_DECREF(__pyx_v___pyx_result->compression); - __pyx_v___pyx_result->compression = __pyx_t_1; - __pyx_t_1 = 0; - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 12, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 3, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v___pyx_result->headers); - __Pyx_DECREF(__pyx_v___pyx_result->headers); - __pyx_v___pyx_result->headers = __pyx_t_1; - __pyx_t_1 = 0; - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 12, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 4, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v___pyx_result->raw_headers); - __Pyx_DECREF(__pyx_v___pyx_result->raw_headers); - __pyx_v___pyx_result->raw_headers = __pyx_t_1; - __pyx_t_1 = 0; - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 12, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 5, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(PyUnicode_CheckExact(__pyx_t_1))||((__pyx_t_1) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "unicode", Py_TYPE(__pyx_t_1)->tp_name), 0))) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v___pyx_result->reason); - __Pyx_DECREF(__pyx_v___pyx_result->reason); - __pyx_v___pyx_result->reason = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 12, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 6, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v___pyx_result->should_close); - __Pyx_DECREF(__pyx_v___pyx_result->should_close); - __pyx_v___pyx_result->should_close = __pyx_t_1; - __pyx_t_1 = 0; - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 12, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 7, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v___pyx_result->upgrade); - __Pyx_DECREF(__pyx_v___pyx_result->upgrade); - __pyx_v___pyx_result->upgrade = __pyx_t_1; - __pyx_t_1 = 0; - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 12, __pyx_L1_error) - } - __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 8, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v___pyx_result->version); - __Pyx_DECREF(__pyx_v___pyx_result->version); - __pyx_v___pyx_result->version = __pyx_t_1; - __pyx_t_1 = 0; - - /* "(tree fragment)":13 - * cdef __pyx_unpickle_RawResponseMessage__set_state(RawResponseMessage __pyx_result, tuple __pyx_state): - * __pyx_result.chunked = __pyx_state[0]; __pyx_result.code = __pyx_state[1]; __pyx_result.compression = __pyx_state[2]; __pyx_result.headers = __pyx_state[3]; __pyx_result.raw_headers = __pyx_state[4]; __pyx_result.reason = __pyx_state[5]; __pyx_result.should_close = __pyx_state[6]; __pyx_result.upgrade = __pyx_state[7]; __pyx_result.version = __pyx_state[8] - * if len(__pyx_state) > 9 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< - * __pyx_result.__dict__.update(__pyx_state[9]) - */ - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - __PYX_ERR(1, 13, __pyx_L1_error) - } - __pyx_t_4 = PyTuple_GET_SIZE(__pyx_v___pyx_state); if (unlikely(__pyx_t_4 == ((Py_ssize_t)-1))) __PYX_ERR(1, 13, __pyx_L1_error) - __pyx_t_5 = ((__pyx_t_4 > 9) != 0); - if (__pyx_t_5) { - } else { - __pyx_t_3 = __pyx_t_5; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_5 = __Pyx_HasAttr(((PyObject *)__pyx_v___pyx_result), __pyx_n_s_dict); if (unlikely(__pyx_t_5 == ((int)-1))) __PYX_ERR(1, 13, __pyx_L1_error) - __pyx_t_6 = (__pyx_t_5 != 0); - __pyx_t_3 = __pyx_t_6; - __pyx_L4_bool_binop_done:; - if (__pyx_t_3) { - - /* "(tree fragment)":14 - * __pyx_result.chunked = __pyx_state[0]; __pyx_result.code = __pyx_state[1]; __pyx_result.compression = __pyx_state[2]; __pyx_result.headers = __pyx_state[3]; __pyx_result.raw_headers = __pyx_state[4]; __pyx_result.reason = __pyx_state[5]; __pyx_result.should_close = __pyx_state[6]; __pyx_result.upgrade = __pyx_state[7]; __pyx_result.version = __pyx_state[8] - * if len(__pyx_state) > 9 and hasattr(__pyx_result, '__dict__'): - * __pyx_result.__dict__.update(__pyx_state[9]) # <<<<<<<<<<<<<< - */ - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v___pyx_result), __pyx_n_s_dict); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_7, __pyx_n_s_update); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - if (unlikely(__pyx_v___pyx_state == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 14, __pyx_L1_error) - } - __pyx_t_7 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 9, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_9 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_8))) { - __pyx_t_9 = PyMethod_GET_SELF(__pyx_t_8); - if (likely(__pyx_t_9)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_8); - __Pyx_INCREF(__pyx_t_9); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_8, function); - } - } - __pyx_t_1 = (__pyx_t_9) ? __Pyx_PyObject_Call2Args(__pyx_t_8, __pyx_t_9, __pyx_t_7) : __Pyx_PyObject_CallOneArg(__pyx_t_8, __pyx_t_7); - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "(tree fragment)":13 - * cdef __pyx_unpickle_RawResponseMessage__set_state(RawResponseMessage __pyx_result, tuple __pyx_state): - * __pyx_result.chunked = __pyx_state[0]; __pyx_result.code = __pyx_state[1]; __pyx_result.compression = __pyx_state[2]; __pyx_result.headers = __pyx_state[3]; __pyx_result.raw_headers = __pyx_state[4]; __pyx_result.reason = __pyx_state[5]; __pyx_result.should_close = __pyx_state[6]; __pyx_result.upgrade = __pyx_state[7]; __pyx_result.version = __pyx_state[8] - * if len(__pyx_state) > 9 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< - * __pyx_result.__dict__.update(__pyx_state[9]) - */ - } - - /* "(tree fragment)":11 - * __pyx_unpickle_RawResponseMessage__set_state( __pyx_result, __pyx_state) - * return __pyx_result - * cdef __pyx_unpickle_RawResponseMessage__set_state(RawResponseMessage __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< - * __pyx_result.chunked = __pyx_state[0]; __pyx_result.code = __pyx_state[1]; __pyx_result.compression = __pyx_state[2]; __pyx_result.headers = __pyx_state[3]; __pyx_result.raw_headers = __pyx_state[4]; __pyx_result.reason = __pyx_state[5]; __pyx_result.should_close = __pyx_state[6]; __pyx_result.upgrade = __pyx_state[7]; __pyx_result.version = __pyx_state[8] - * if len(__pyx_state) > 9 and hasattr(__pyx_result, '__dict__'): - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_AddTraceback("aiohttp._http_parser.__pyx_unpickle_RawResponseMessage__set_state", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *__pyx_freelist_7aiohttp_12_http_parser_RawRequestMessage[250]; -static int __pyx_freecount_7aiohttp_12_http_parser_RawRequestMessage = 0; - -static PyObject *__pyx_tp_new_7aiohttp_12_http_parser_RawRequestMessage(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { - struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *p; - PyObject *o; - if (CYTHON_COMPILING_IN_CPYTHON && likely((__pyx_freecount_7aiohttp_12_http_parser_RawRequestMessage > 0) & (t->tp_basicsize == sizeof(struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage)) & ((t->tp_flags & (Py_TPFLAGS_IS_ABSTRACT | Py_TPFLAGS_HEAPTYPE)) == 0))) { - o = (PyObject*)__pyx_freelist_7aiohttp_12_http_parser_RawRequestMessage[--__pyx_freecount_7aiohttp_12_http_parser_RawRequestMessage]; - memset(o, 0, sizeof(struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage)); - (void) PyObject_INIT(o, t); - PyObject_GC_Track(o); - } else { - if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { - o = (*t->tp_alloc)(t, 0); - } else { - o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); - } - if (unlikely(!o)) return 0; - } - p = ((struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *)o); - p->method = ((PyObject*)Py_None); Py_INCREF(Py_None); - p->path = ((PyObject*)Py_None); Py_INCREF(Py_None); - p->version = Py_None; Py_INCREF(Py_None); - p->headers = Py_None; Py_INCREF(Py_None); - p->raw_headers = Py_None; Py_INCREF(Py_None); - p->should_close = Py_None; Py_INCREF(Py_None); - p->compression = Py_None; Py_INCREF(Py_None); - p->upgrade = Py_None; Py_INCREF(Py_None); - p->chunked = Py_None; Py_INCREF(Py_None); - p->url = Py_None; Py_INCREF(Py_None); - return o; -} - -static void __pyx_tp_dealloc_7aiohttp_12_http_parser_RawRequestMessage(PyObject *o) { - struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *p = (struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *)o; - #if CYTHON_USE_TP_FINALIZE - if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { - if (PyObject_CallFinalizerFromDealloc(o)) return; - } - #endif - PyObject_GC_UnTrack(o); - Py_CLEAR(p->method); - Py_CLEAR(p->path); - Py_CLEAR(p->version); - Py_CLEAR(p->headers); - Py_CLEAR(p->raw_headers); - Py_CLEAR(p->should_close); - Py_CLEAR(p->compression); - Py_CLEAR(p->upgrade); - Py_CLEAR(p->chunked); - Py_CLEAR(p->url); - if (CYTHON_COMPILING_IN_CPYTHON && ((__pyx_freecount_7aiohttp_12_http_parser_RawRequestMessage < 250) & (Py_TYPE(o)->tp_basicsize == sizeof(struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage)) & ((Py_TYPE(o)->tp_flags & (Py_TPFLAGS_IS_ABSTRACT | Py_TPFLAGS_HEAPTYPE)) == 0))) { - __pyx_freelist_7aiohttp_12_http_parser_RawRequestMessage[__pyx_freecount_7aiohttp_12_http_parser_RawRequestMessage++] = ((struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *)o); - } else { - (*Py_TYPE(o)->tp_free)(o); - } -} - -static int __pyx_tp_traverse_7aiohttp_12_http_parser_RawRequestMessage(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *p = (struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *)o; - if (p->version) { - e = (*v)(p->version, a); if (e) return e; - } - if (p->headers) { - e = (*v)(p->headers, a); if (e) return e; - } - if (p->raw_headers) { - e = (*v)(p->raw_headers, a); if (e) return e; - } - if (p->should_close) { - e = (*v)(p->should_close, a); if (e) return e; - } - if (p->compression) { - e = (*v)(p->compression, a); if (e) return e; - } - if (p->upgrade) { - e = (*v)(p->upgrade, a); if (e) return e; - } - if (p->chunked) { - e = (*v)(p->chunked, a); if (e) return e; - } - if (p->url) { - e = (*v)(p->url, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear_7aiohttp_12_http_parser_RawRequestMessage(PyObject *o) { - PyObject* tmp; - struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *p = (struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage *)o; - tmp = ((PyObject*)p->version); - p->version = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->headers); - p->headers = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->raw_headers); - p->raw_headers = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->should_close); - p->should_close = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->compression); - p->compression = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->upgrade); - p->upgrade = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->chunked); - p->chunked = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->url); - p->url = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - return 0; -} - -static PyObject *__pyx_getprop_7aiohttp_12_http_parser_17RawRequestMessage_method(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_6method_1__get__(o); -} - -static PyObject *__pyx_getprop_7aiohttp_12_http_parser_17RawRequestMessage_path(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_4path_1__get__(o); -} - -static PyObject *__pyx_getprop_7aiohttp_12_http_parser_17RawRequestMessage_version(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_7version_1__get__(o); -} - -static PyObject *__pyx_getprop_7aiohttp_12_http_parser_17RawRequestMessage_headers(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_7headers_1__get__(o); -} - -static PyObject *__pyx_getprop_7aiohttp_12_http_parser_17RawRequestMessage_raw_headers(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_11raw_headers_1__get__(o); -} - -static PyObject *__pyx_getprop_7aiohttp_12_http_parser_17RawRequestMessage_should_close(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_12should_close_1__get__(o); -} - -static PyObject *__pyx_getprop_7aiohttp_12_http_parser_17RawRequestMessage_compression(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_11compression_1__get__(o); -} - -static PyObject *__pyx_getprop_7aiohttp_12_http_parser_17RawRequestMessage_upgrade(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_7upgrade_1__get__(o); -} - -static PyObject *__pyx_getprop_7aiohttp_12_http_parser_17RawRequestMessage_chunked(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_7chunked_1__get__(o); -} - -static PyObject *__pyx_getprop_7aiohttp_12_http_parser_17RawRequestMessage_url(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_3url_1__get__(o); -} - -static PyMethodDef __pyx_methods_7aiohttp_12_http_parser_RawRequestMessage[] = { - {"_replace", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_5_replace, METH_VARARGS|METH_KEYWORDS, 0}, - {"__reduce_cython__", (PyCFunction)__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_7__reduce_cython__, METH_NOARGS, 0}, - {"__setstate_cython__", (PyCFunction)__pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_9__setstate_cython__, METH_O, 0}, - {0, 0, 0, 0} -}; - -static struct PyGetSetDef __pyx_getsets_7aiohttp_12_http_parser_RawRequestMessage[] = { - {(char *)"method", __pyx_getprop_7aiohttp_12_http_parser_17RawRequestMessage_method, 0, (char *)0, 0}, - {(char *)"path", __pyx_getprop_7aiohttp_12_http_parser_17RawRequestMessage_path, 0, (char *)0, 0}, - {(char *)"version", __pyx_getprop_7aiohttp_12_http_parser_17RawRequestMessage_version, 0, (char *)0, 0}, - {(char *)"headers", __pyx_getprop_7aiohttp_12_http_parser_17RawRequestMessage_headers, 0, (char *)0, 0}, - {(char *)"raw_headers", __pyx_getprop_7aiohttp_12_http_parser_17RawRequestMessage_raw_headers, 0, (char *)0, 0}, - {(char *)"should_close", __pyx_getprop_7aiohttp_12_http_parser_17RawRequestMessage_should_close, 0, (char *)0, 0}, - {(char *)"compression", __pyx_getprop_7aiohttp_12_http_parser_17RawRequestMessage_compression, 0, (char *)0, 0}, - {(char *)"upgrade", __pyx_getprop_7aiohttp_12_http_parser_17RawRequestMessage_upgrade, 0, (char *)0, 0}, - {(char *)"chunked", __pyx_getprop_7aiohttp_12_http_parser_17RawRequestMessage_chunked, 0, (char *)0, 0}, - {(char *)"url", __pyx_getprop_7aiohttp_12_http_parser_17RawRequestMessage_url, 0, (char *)0, 0}, - {0, 0, 0, 0, 0} -}; - -static PyTypeObject __pyx_type_7aiohttp_12_http_parser_RawRequestMessage = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._http_parser.RawRequestMessage", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_12_http_parser_RawRequestMessage), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_12_http_parser_RawRequestMessage, /*tp_dealloc*/ - #if PY_VERSION_HEX < 0x030800b4 - 0, /*tp_print*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 - 0, /*tp_vectorcall_offset*/ - #endif - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - __pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_3__repr__, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_7aiohttp_12_http_parser_RawRequestMessage, /*tp_traverse*/ - __pyx_tp_clear_7aiohttp_12_http_parser_RawRequestMessage, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7aiohttp_12_http_parser_RawRequestMessage, /*tp_methods*/ - 0, /*tp_members*/ - __pyx_getsets_7aiohttp_12_http_parser_RawRequestMessage, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - __pyx_pw_7aiohttp_12_http_parser_17RawRequestMessage_1__init__, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_12_http_parser_RawRequestMessage, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif - #if PY_VERSION_HEX >= 0x030800b1 - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif -}; - -static struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *__pyx_freelist_7aiohttp_12_http_parser_RawResponseMessage[250]; -static int __pyx_freecount_7aiohttp_12_http_parser_RawResponseMessage = 0; - -static PyObject *__pyx_tp_new_7aiohttp_12_http_parser_RawResponseMessage(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { - struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *p; - PyObject *o; - if (CYTHON_COMPILING_IN_CPYTHON && likely((__pyx_freecount_7aiohttp_12_http_parser_RawResponseMessage > 0) & (t->tp_basicsize == sizeof(struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage)) & ((t->tp_flags & (Py_TPFLAGS_IS_ABSTRACT | Py_TPFLAGS_HEAPTYPE)) == 0))) { - o = (PyObject*)__pyx_freelist_7aiohttp_12_http_parser_RawResponseMessage[--__pyx_freecount_7aiohttp_12_http_parser_RawResponseMessage]; - memset(o, 0, sizeof(struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage)); - (void) PyObject_INIT(o, t); - PyObject_GC_Track(o); - } else { - if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { - o = (*t->tp_alloc)(t, 0); - } else { - o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); - } - if (unlikely(!o)) return 0; - } - p = ((struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *)o); - p->version = Py_None; Py_INCREF(Py_None); - p->reason = ((PyObject*)Py_None); Py_INCREF(Py_None); - p->headers = Py_None; Py_INCREF(Py_None); - p->raw_headers = Py_None; Py_INCREF(Py_None); - p->should_close = Py_None; Py_INCREF(Py_None); - p->compression = Py_None; Py_INCREF(Py_None); - p->upgrade = Py_None; Py_INCREF(Py_None); - p->chunked = Py_None; Py_INCREF(Py_None); - return o; -} - -static void __pyx_tp_dealloc_7aiohttp_12_http_parser_RawResponseMessage(PyObject *o) { - struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *p = (struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *)o; - #if CYTHON_USE_TP_FINALIZE - if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { - if (PyObject_CallFinalizerFromDealloc(o)) return; - } - #endif - PyObject_GC_UnTrack(o); - Py_CLEAR(p->version); - Py_CLEAR(p->reason); - Py_CLEAR(p->headers); - Py_CLEAR(p->raw_headers); - Py_CLEAR(p->should_close); - Py_CLEAR(p->compression); - Py_CLEAR(p->upgrade); - Py_CLEAR(p->chunked); - if (CYTHON_COMPILING_IN_CPYTHON && ((__pyx_freecount_7aiohttp_12_http_parser_RawResponseMessage < 250) & (Py_TYPE(o)->tp_basicsize == sizeof(struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage)) & ((Py_TYPE(o)->tp_flags & (Py_TPFLAGS_IS_ABSTRACT | Py_TPFLAGS_HEAPTYPE)) == 0))) { - __pyx_freelist_7aiohttp_12_http_parser_RawResponseMessage[__pyx_freecount_7aiohttp_12_http_parser_RawResponseMessage++] = ((struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *)o); - } else { - (*Py_TYPE(o)->tp_free)(o); - } -} - -static int __pyx_tp_traverse_7aiohttp_12_http_parser_RawResponseMessage(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *p = (struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *)o; - if (p->version) { - e = (*v)(p->version, a); if (e) return e; - } - if (p->headers) { - e = (*v)(p->headers, a); if (e) return e; - } - if (p->raw_headers) { - e = (*v)(p->raw_headers, a); if (e) return e; - } - if (p->should_close) { - e = (*v)(p->should_close, a); if (e) return e; - } - if (p->compression) { - e = (*v)(p->compression, a); if (e) return e; - } - if (p->upgrade) { - e = (*v)(p->upgrade, a); if (e) return e; - } - if (p->chunked) { - e = (*v)(p->chunked, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear_7aiohttp_12_http_parser_RawResponseMessage(PyObject *o) { - PyObject* tmp; - struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *p = (struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage *)o; - tmp = ((PyObject*)p->version); - p->version = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->headers); - p->headers = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->raw_headers); - p->raw_headers = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->should_close); - p->should_close = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->compression); - p->compression = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->upgrade); - p->upgrade = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->chunked); - p->chunked = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - return 0; -} - -static PyObject *__pyx_getprop_7aiohttp_12_http_parser_18RawResponseMessage_version(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_7version_1__get__(o); -} - -static PyObject *__pyx_getprop_7aiohttp_12_http_parser_18RawResponseMessage_code(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_4code_1__get__(o); -} - -static PyObject *__pyx_getprop_7aiohttp_12_http_parser_18RawResponseMessage_reason(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_6reason_1__get__(o); -} - -static PyObject *__pyx_getprop_7aiohttp_12_http_parser_18RawResponseMessage_headers(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_7headers_1__get__(o); -} - -static PyObject *__pyx_getprop_7aiohttp_12_http_parser_18RawResponseMessage_raw_headers(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_11raw_headers_1__get__(o); -} - -static PyObject *__pyx_getprop_7aiohttp_12_http_parser_18RawResponseMessage_should_close(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_12should_close_1__get__(o); -} - -static PyObject *__pyx_getprop_7aiohttp_12_http_parser_18RawResponseMessage_compression(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_11compression_1__get__(o); -} - -static PyObject *__pyx_getprop_7aiohttp_12_http_parser_18RawResponseMessage_upgrade(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_7upgrade_1__get__(o); -} - -static PyObject *__pyx_getprop_7aiohttp_12_http_parser_18RawResponseMessage_chunked(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_7chunked_1__get__(o); -} - -static PyMethodDef __pyx_methods_7aiohttp_12_http_parser_RawResponseMessage[] = { - {"__reduce_cython__", (PyCFunction)__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_5__reduce_cython__, METH_NOARGS, 0}, - {"__setstate_cython__", (PyCFunction)__pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_7__setstate_cython__, METH_O, 0}, - {0, 0, 0, 0} -}; - -static struct PyGetSetDef __pyx_getsets_7aiohttp_12_http_parser_RawResponseMessage[] = { - {(char *)"version", __pyx_getprop_7aiohttp_12_http_parser_18RawResponseMessage_version, 0, (char *)0, 0}, - {(char *)"code", __pyx_getprop_7aiohttp_12_http_parser_18RawResponseMessage_code, 0, (char *)0, 0}, - {(char *)"reason", __pyx_getprop_7aiohttp_12_http_parser_18RawResponseMessage_reason, 0, (char *)0, 0}, - {(char *)"headers", __pyx_getprop_7aiohttp_12_http_parser_18RawResponseMessage_headers, 0, (char *)0, 0}, - {(char *)"raw_headers", __pyx_getprop_7aiohttp_12_http_parser_18RawResponseMessage_raw_headers, 0, (char *)0, 0}, - {(char *)"should_close", __pyx_getprop_7aiohttp_12_http_parser_18RawResponseMessage_should_close, 0, (char *)0, 0}, - {(char *)"compression", __pyx_getprop_7aiohttp_12_http_parser_18RawResponseMessage_compression, 0, (char *)0, 0}, - {(char *)"upgrade", __pyx_getprop_7aiohttp_12_http_parser_18RawResponseMessage_upgrade, 0, (char *)0, 0}, - {(char *)"chunked", __pyx_getprop_7aiohttp_12_http_parser_18RawResponseMessage_chunked, 0, (char *)0, 0}, - {0, 0, 0, 0, 0} -}; - -static PyTypeObject __pyx_type_7aiohttp_12_http_parser_RawResponseMessage = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._http_parser.RawResponseMessage", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_12_http_parser_RawResponseMessage), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_12_http_parser_RawResponseMessage, /*tp_dealloc*/ - #if PY_VERSION_HEX < 0x030800b4 - 0, /*tp_print*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 - 0, /*tp_vectorcall_offset*/ - #endif - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - __pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_3__repr__, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_7aiohttp_12_http_parser_RawResponseMessage, /*tp_traverse*/ - __pyx_tp_clear_7aiohttp_12_http_parser_RawResponseMessage, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7aiohttp_12_http_parser_RawResponseMessage, /*tp_methods*/ - 0, /*tp_members*/ - __pyx_getsets_7aiohttp_12_http_parser_RawResponseMessage, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - __pyx_pw_7aiohttp_12_http_parser_18RawResponseMessage_1__init__, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_12_http_parser_RawResponseMessage, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif - #if PY_VERSION_HEX >= 0x030800b1 - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif -}; -static struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser __pyx_vtable_7aiohttp_12_http_parser_HttpParser; - -static PyObject *__pyx_tp_new_7aiohttp_12_http_parser_HttpParser(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { - struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *p; - PyObject *o; - if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { - o = (*t->tp_alloc)(t, 0); - } else { - o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); - } - if (unlikely(!o)) return 0; - p = ((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)o); - p->__pyx_vtab = __pyx_vtabptr_7aiohttp_12_http_parser_HttpParser; - p->_raw_name = ((PyObject*)Py_None); Py_INCREF(Py_None); - p->_raw_value = ((PyObject*)Py_None); Py_INCREF(Py_None); - p->_protocol = Py_None; Py_INCREF(Py_None); - p->_loop = Py_None; Py_INCREF(Py_None); - p->_timer = Py_None; Py_INCREF(Py_None); - p->_url = Py_None; Py_INCREF(Py_None); - p->_buf = ((PyObject*)Py_None); Py_INCREF(Py_None); - p->_path = ((PyObject*)Py_None); Py_INCREF(Py_None); - p->_reason = ((PyObject*)Py_None); Py_INCREF(Py_None); - p->_headers = Py_None; Py_INCREF(Py_None); - p->_raw_headers = ((PyObject*)Py_None); Py_INCREF(Py_None); - p->_messages = ((PyObject*)Py_None); Py_INCREF(Py_None); - p->_payload = Py_None; Py_INCREF(Py_None); - p->_payload_exception = Py_None; Py_INCREF(Py_None); - p->_last_error = Py_None; Py_INCREF(Py_None); - p->_content_encoding = ((PyObject*)Py_None); Py_INCREF(Py_None); - p->py_buf.obj = NULL; - if (unlikely(__pyx_pw_7aiohttp_12_http_parser_10HttpParser_1__cinit__(o, __pyx_empty_tuple, NULL) < 0)) goto bad; - return o; - bad: - Py_DECREF(o); o = 0; - return NULL; -} - -static void __pyx_tp_dealloc_7aiohttp_12_http_parser_HttpParser(PyObject *o) { - struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *p = (struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)o; - #if CYTHON_USE_TP_FINALIZE - if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { - if (PyObject_CallFinalizerFromDealloc(o)) return; - } - #endif - PyObject_GC_UnTrack(o); - { - PyObject *etype, *eval, *etb; - PyErr_Fetch(&etype, &eval, &etb); - __Pyx_SET_REFCNT(o, Py_REFCNT(o) + 1); - __pyx_pw_7aiohttp_12_http_parser_10HttpParser_3__dealloc__(o); - __Pyx_SET_REFCNT(o, Py_REFCNT(o) - 1); - PyErr_Restore(etype, eval, etb); - } - Py_CLEAR(p->_raw_name); - Py_CLEAR(p->_raw_value); - Py_CLEAR(p->_protocol); - Py_CLEAR(p->_loop); - Py_CLEAR(p->_timer); - Py_CLEAR(p->_url); - Py_CLEAR(p->_buf); - Py_CLEAR(p->_path); - Py_CLEAR(p->_reason); - Py_CLEAR(p->_headers); - Py_CLEAR(p->_raw_headers); - Py_CLEAR(p->_messages); - Py_CLEAR(p->_payload); - Py_CLEAR(p->_payload_exception); - Py_CLEAR(p->_last_error); - Py_CLEAR(p->_content_encoding); - (*Py_TYPE(o)->tp_free)(o); -} - -static int __pyx_tp_traverse_7aiohttp_12_http_parser_HttpParser(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *p = (struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)o; - if (p->_protocol) { - e = (*v)(p->_protocol, a); if (e) return e; - } - if (p->_loop) { - e = (*v)(p->_loop, a); if (e) return e; - } - if (p->_timer) { - e = (*v)(p->_timer, a); if (e) return e; - } - if (p->_url) { - e = (*v)(p->_url, a); if (e) return e; - } - if (p->_headers) { - e = (*v)(p->_headers, a); if (e) return e; - } - if (p->_raw_headers) { - e = (*v)(p->_raw_headers, a); if (e) return e; - } - if (p->_messages) { - e = (*v)(p->_messages, a); if (e) return e; - } - if (p->_payload) { - e = (*v)(p->_payload, a); if (e) return e; - } - if (p->_payload_exception) { - e = (*v)(p->_payload_exception, a); if (e) return e; - } - if (p->_last_error) { - e = (*v)(p->_last_error, a); if (e) return e; - } - if (p->py_buf.obj) { - e = (*v)(p->py_buf.obj, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear_7aiohttp_12_http_parser_HttpParser(PyObject *o) { - PyObject* tmp; - struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *p = (struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)o; - tmp = ((PyObject*)p->_protocol); - p->_protocol = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->_loop); - p->_loop = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->_timer); - p->_timer = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->_url); - p->_url = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->_headers); - p->_headers = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->_raw_headers); - p->_raw_headers = ((PyObject*)Py_None); Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->_messages); - p->_messages = ((PyObject*)Py_None); Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->_payload); - p->_payload = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->_payload_exception); - p->_payload_exception = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - tmp = ((PyObject*)p->_last_error); - p->_last_error = Py_None; Py_INCREF(Py_None); - Py_XDECREF(tmp); - Py_CLEAR(p->py_buf.obj); - return 0; -} - -static PyMethodDef __pyx_methods_7aiohttp_12_http_parser_HttpParser[] = { - {"feed_eof", (PyCFunction)__pyx_pw_7aiohttp_12_http_parser_10HttpParser_5feed_eof, METH_NOARGS, 0}, - {"feed_data", (PyCFunction)__pyx_pw_7aiohttp_12_http_parser_10HttpParser_7feed_data, METH_O, 0}, - {"set_upgraded", (PyCFunction)__pyx_pw_7aiohttp_12_http_parser_10HttpParser_9set_upgraded, METH_O, 0}, - {"__reduce_cython__", (PyCFunction)__pyx_pw_7aiohttp_12_http_parser_10HttpParser_11__reduce_cython__, METH_NOARGS, 0}, - {"__setstate_cython__", (PyCFunction)__pyx_pw_7aiohttp_12_http_parser_10HttpParser_13__setstate_cython__, METH_O, 0}, - {0, 0, 0, 0} -}; - -static PyTypeObject __pyx_type_7aiohttp_12_http_parser_HttpParser = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._http_parser.HttpParser", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_12_http_parser_HttpParser, /*tp_dealloc*/ - #if PY_VERSION_HEX < 0x030800b4 - 0, /*tp_print*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 - 0, /*tp_vectorcall_offset*/ - #endif - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_7aiohttp_12_http_parser_HttpParser, /*tp_traverse*/ - __pyx_tp_clear_7aiohttp_12_http_parser_HttpParser, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7aiohttp_12_http_parser_HttpParser, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_12_http_parser_HttpParser, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif - #if PY_VERSION_HEX >= 0x030800b1 - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif -}; -static struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpRequestParser __pyx_vtable_7aiohttp_12_http_parser_HttpRequestParser; - -static PyObject *__pyx_tp_new_7aiohttp_12_http_parser_HttpRequestParser(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParser *p; - PyObject *o = __pyx_tp_new_7aiohttp_12_http_parser_HttpParser(t, a, k); - if (unlikely(!o)) return 0; - p = ((struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParser *)o); - p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser*)__pyx_vtabptr_7aiohttp_12_http_parser_HttpRequestParser; - return o; -} - -static PyMethodDef __pyx_methods_7aiohttp_12_http_parser_HttpRequestParser[] = { - {"__reduce_cython__", (PyCFunction)__pyx_pw_7aiohttp_12_http_parser_17HttpRequestParser_3__reduce_cython__, METH_NOARGS, 0}, - {"__setstate_cython__", (PyCFunction)__pyx_pw_7aiohttp_12_http_parser_17HttpRequestParser_5__setstate_cython__, METH_O, 0}, - {0, 0, 0, 0} -}; - -static PyTypeObject __pyx_type_7aiohttp_12_http_parser_HttpRequestParser = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._http_parser.HttpRequestParser", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParser), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_12_http_parser_HttpParser, /*tp_dealloc*/ - #if PY_VERSION_HEX < 0x030800b4 - 0, /*tp_print*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 - 0, /*tp_vectorcall_offset*/ - #endif - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_7aiohttp_12_http_parser_HttpParser, /*tp_traverse*/ - __pyx_tp_clear_7aiohttp_12_http_parser_HttpParser, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7aiohttp_12_http_parser_HttpRequestParser, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - __pyx_pw_7aiohttp_12_http_parser_17HttpRequestParser_1__init__, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_12_http_parser_HttpRequestParser, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif - #if PY_VERSION_HEX >= 0x030800b1 - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif -}; -static struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpResponseParser __pyx_vtable_7aiohttp_12_http_parser_HttpResponseParser; - -static PyObject *__pyx_tp_new_7aiohttp_12_http_parser_HttpResponseParser(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParser *p; - PyObject *o = __pyx_tp_new_7aiohttp_12_http_parser_HttpParser(t, a, k); - if (unlikely(!o)) return 0; - p = ((struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParser *)o); - p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser*)__pyx_vtabptr_7aiohttp_12_http_parser_HttpResponseParser; - return o; -} - -static PyMethodDef __pyx_methods_7aiohttp_12_http_parser_HttpResponseParser[] = { - {"__reduce_cython__", (PyCFunction)__pyx_pw_7aiohttp_12_http_parser_18HttpResponseParser_3__reduce_cython__, METH_NOARGS, 0}, - {"__setstate_cython__", (PyCFunction)__pyx_pw_7aiohttp_12_http_parser_18HttpResponseParser_5__setstate_cython__, METH_O, 0}, - {0, 0, 0, 0} -}; - -static PyTypeObject __pyx_type_7aiohttp_12_http_parser_HttpResponseParser = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._http_parser.HttpResponseParser", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParser), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_12_http_parser_HttpParser, /*tp_dealloc*/ - #if PY_VERSION_HEX < 0x030800b4 - 0, /*tp_print*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 - 0, /*tp_vectorcall_offset*/ - #endif - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_7aiohttp_12_http_parser_HttpParser, /*tp_traverse*/ - __pyx_tp_clear_7aiohttp_12_http_parser_HttpParser, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - __pyx_methods_7aiohttp_12_http_parser_HttpResponseParser, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - __pyx_pw_7aiohttp_12_http_parser_18HttpResponseParser_1__init__, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_12_http_parser_HttpResponseParser, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif - #if PY_VERSION_HEX >= 0x030800b1 - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif -}; - -static struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct____repr__ *__pyx_freelist_7aiohttp_12_http_parser___pyx_scope_struct____repr__[8]; -static int __pyx_freecount_7aiohttp_12_http_parser___pyx_scope_struct____repr__ = 0; - -static PyObject *__pyx_tp_new_7aiohttp_12_http_parser___pyx_scope_struct____repr__(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { - PyObject *o; - if (CYTHON_COMPILING_IN_CPYTHON && likely((__pyx_freecount_7aiohttp_12_http_parser___pyx_scope_struct____repr__ > 0) & (t->tp_basicsize == sizeof(struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct____repr__)))) { - o = (PyObject*)__pyx_freelist_7aiohttp_12_http_parser___pyx_scope_struct____repr__[--__pyx_freecount_7aiohttp_12_http_parser___pyx_scope_struct____repr__]; - memset(o, 0, sizeof(struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct____repr__)); - (void) PyObject_INIT(o, t); - PyObject_GC_Track(o); - } else { - o = (*t->tp_alloc)(t, 0); - if (unlikely(!o)) return 0; - } - return o; -} - -static void __pyx_tp_dealloc_7aiohttp_12_http_parser___pyx_scope_struct____repr__(PyObject *o) { - struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct____repr__ *p = (struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct____repr__ *)o; - PyObject_GC_UnTrack(o); - Py_CLEAR(p->__pyx_v_info); - if (CYTHON_COMPILING_IN_CPYTHON && ((__pyx_freecount_7aiohttp_12_http_parser___pyx_scope_struct____repr__ < 8) & (Py_TYPE(o)->tp_basicsize == sizeof(struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct____repr__)))) { - __pyx_freelist_7aiohttp_12_http_parser___pyx_scope_struct____repr__[__pyx_freecount_7aiohttp_12_http_parser___pyx_scope_struct____repr__++] = ((struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct____repr__ *)o); - } else { - (*Py_TYPE(o)->tp_free)(o); - } -} - -static int __pyx_tp_traverse_7aiohttp_12_http_parser___pyx_scope_struct____repr__(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct____repr__ *p = (struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct____repr__ *)o; - if (p->__pyx_v_info) { - e = (*v)(p->__pyx_v_info, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear_7aiohttp_12_http_parser___pyx_scope_struct____repr__(PyObject *o) { - PyObject* tmp; - struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct____repr__ *p = (struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct____repr__ *)o; - tmp = ((PyObject*)p->__pyx_v_info); - p->__pyx_v_info = ((PyObject*)Py_None); Py_INCREF(Py_None); - Py_XDECREF(tmp); - return 0; -} - -static PyTypeObject __pyx_type_7aiohttp_12_http_parser___pyx_scope_struct____repr__ = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._http_parser.__pyx_scope_struct____repr__", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct____repr__), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_12_http_parser___pyx_scope_struct____repr__, /*tp_dealloc*/ - #if PY_VERSION_HEX < 0x030800b4 - 0, /*tp_print*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 - 0, /*tp_vectorcall_offset*/ - #endif - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_7aiohttp_12_http_parser___pyx_scope_struct____repr__, /*tp_traverse*/ - __pyx_tp_clear_7aiohttp_12_http_parser___pyx_scope_struct____repr__, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_12_http_parser___pyx_scope_struct____repr__, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif - #if PY_VERSION_HEX >= 0x030800b1 - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif -}; - -static struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr *__pyx_freelist_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr[8]; -static int __pyx_freecount_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr = 0; - -static PyObject *__pyx_tp_new_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { - PyObject *o; - if (CYTHON_COMPILING_IN_CPYTHON && likely((__pyx_freecount_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr > 0) & (t->tp_basicsize == sizeof(struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr)))) { - o = (PyObject*)__pyx_freelist_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr[--__pyx_freecount_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr]; - memset(o, 0, sizeof(struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr)); - (void) PyObject_INIT(o, t); - PyObject_GC_Track(o); - } else { - o = (*t->tp_alloc)(t, 0); - if (unlikely(!o)) return 0; - } - return o; -} - -static void __pyx_tp_dealloc_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr(PyObject *o) { - struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr *p = (struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr *)o; - PyObject_GC_UnTrack(o); - Py_CLEAR(p->__pyx_outer_scope); - Py_CLEAR(p->__pyx_v_name); - Py_CLEAR(p->__pyx_v_val); - if (CYTHON_COMPILING_IN_CPYTHON && ((__pyx_freecount_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr < 8) & (Py_TYPE(o)->tp_basicsize == sizeof(struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr)))) { - __pyx_freelist_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr[__pyx_freecount_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr++] = ((struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr *)o); - } else { - (*Py_TYPE(o)->tp_free)(o); - } -} - -static int __pyx_tp_traverse_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr *p = (struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr *)o; - if (p->__pyx_outer_scope) { - e = (*v)(((PyObject *)p->__pyx_outer_scope), a); if (e) return e; - } - if (p->__pyx_v_name) { - e = (*v)(p->__pyx_v_name, a); if (e) return e; - } - if (p->__pyx_v_val) { - e = (*v)(p->__pyx_v_val, a); if (e) return e; - } - return 0; -} - -static PyTypeObject __pyx_type_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._http_parser.__pyx_scope_struct_1_genexpr", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr, /*tp_dealloc*/ - #if PY_VERSION_HEX < 0x030800b4 - 0, /*tp_print*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 - 0, /*tp_vectorcall_offset*/ - #endif - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif - #if PY_VERSION_HEX >= 0x030800b1 - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif -}; - -static struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__ *__pyx_freelist_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__[8]; -static int __pyx_freecount_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__ = 0; - -static PyObject *__pyx_tp_new_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { - PyObject *o; - if (CYTHON_COMPILING_IN_CPYTHON && likely((__pyx_freecount_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__ > 0) & (t->tp_basicsize == sizeof(struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__)))) { - o = (PyObject*)__pyx_freelist_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__[--__pyx_freecount_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__]; - memset(o, 0, sizeof(struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__)); - (void) PyObject_INIT(o, t); - PyObject_GC_Track(o); - } else { - o = (*t->tp_alloc)(t, 0); - if (unlikely(!o)) return 0; - } - return o; -} - -static void __pyx_tp_dealloc_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__(PyObject *o) { - struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__ *p = (struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__ *)o; - PyObject_GC_UnTrack(o); - Py_CLEAR(p->__pyx_v_info); - if (CYTHON_COMPILING_IN_CPYTHON && ((__pyx_freecount_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__ < 8) & (Py_TYPE(o)->tp_basicsize == sizeof(struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__)))) { - __pyx_freelist_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__[__pyx_freecount_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__++] = ((struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__ *)o); - } else { - (*Py_TYPE(o)->tp_free)(o); - } -} - -static int __pyx_tp_traverse_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__ *p = (struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__ *)o; - if (p->__pyx_v_info) { - e = (*v)(p->__pyx_v_info, a); if (e) return e; - } - return 0; -} - -static int __pyx_tp_clear_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__(PyObject *o) { - PyObject* tmp; - struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__ *p = (struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__ *)o; - tmp = ((PyObject*)p->__pyx_v_info); - p->__pyx_v_info = ((PyObject*)Py_None); Py_INCREF(Py_None); - Py_XDECREF(tmp); - return 0; -} - -static PyTypeObject __pyx_type_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__ = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._http_parser.__pyx_scope_struct_2___repr__", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__, /*tp_dealloc*/ - #if PY_VERSION_HEX < 0x030800b4 - 0, /*tp_print*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 - 0, /*tp_vectorcall_offset*/ - #endif - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__, /*tp_traverse*/ - __pyx_tp_clear_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif - #if PY_VERSION_HEX >= 0x030800b1 - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif -}; - -static struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr *__pyx_freelist_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr[8]; -static int __pyx_freecount_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr = 0; - -static PyObject *__pyx_tp_new_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { - PyObject *o; - if (CYTHON_COMPILING_IN_CPYTHON && likely((__pyx_freecount_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr > 0) & (t->tp_basicsize == sizeof(struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr)))) { - o = (PyObject*)__pyx_freelist_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr[--__pyx_freecount_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr]; - memset(o, 0, sizeof(struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr)); - (void) PyObject_INIT(o, t); - PyObject_GC_Track(o); - } else { - o = (*t->tp_alloc)(t, 0); - if (unlikely(!o)) return 0; - } - return o; -} - -static void __pyx_tp_dealloc_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr(PyObject *o) { - struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr *p = (struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr *)o; - PyObject_GC_UnTrack(o); - Py_CLEAR(p->__pyx_outer_scope); - Py_CLEAR(p->__pyx_v_name); - Py_CLEAR(p->__pyx_v_val); - if (CYTHON_COMPILING_IN_CPYTHON && ((__pyx_freecount_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr < 8) & (Py_TYPE(o)->tp_basicsize == sizeof(struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr)))) { - __pyx_freelist_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr[__pyx_freecount_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr++] = ((struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr *)o); - } else { - (*Py_TYPE(o)->tp_free)(o); - } -} - -static int __pyx_tp_traverse_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr(PyObject *o, visitproc v, void *a) { - int e; - struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr *p = (struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr *)o; - if (p->__pyx_outer_scope) { - e = (*v)(((PyObject *)p->__pyx_outer_scope), a); if (e) return e; - } - if (p->__pyx_v_name) { - e = (*v)(p->__pyx_v_name, a); if (e) return e; - } - if (p->__pyx_v_val) { - e = (*v)(p->__pyx_v_val, a); if (e) return e; - } - return 0; -} - -static PyTypeObject __pyx_type_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._http_parser.__pyx_scope_struct_3_genexpr", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr, /*tp_dealloc*/ - #if PY_VERSION_HEX < 0x030800b4 - 0, /*tp_print*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 - 0, /*tp_vectorcall_offset*/ - #endif - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - #if PY_MAJOR_VERSION < 3 - 0, /*tp_compare*/ - #endif - #if PY_MAJOR_VERSION >= 3 - 0, /*tp_as_async*/ - #endif - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - 0, /*tp_doc*/ - __pyx_tp_traverse_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - 0, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ - 0, /*tp_bases*/ - 0, /*tp_mro*/ - 0, /*tp_cache*/ - 0, /*tp_subclasses*/ - 0, /*tp_weaklist*/ - 0, /*tp_del*/ - 0, /*tp_version_tag*/ - #if PY_VERSION_HEX >= 0x030400a1 - 0, /*tp_finalize*/ - #endif - #if PY_VERSION_HEX >= 0x030800b1 - 0, /*tp_vectorcall*/ - #endif - #if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, /*tp_print*/ - #endif -}; - -static PyMethodDef __pyx_methods[] = { - {0, 0, 0, 0} -}; - -#if PY_MAJOR_VERSION >= 3 -#if CYTHON_PEP489_MULTI_PHASE_INIT -static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ -static int __pyx_pymod_exec__http_parser(PyObject* module); /*proto*/ -static PyModuleDef_Slot __pyx_moduledef_slots[] = { - {Py_mod_create, (void*)__pyx_pymod_create}, - {Py_mod_exec, (void*)__pyx_pymod_exec__http_parser}, - {0, NULL} -}; -#endif - -static struct PyModuleDef __pyx_moduledef = { - PyModuleDef_HEAD_INIT, - "_http_parser", - 0, /* m_doc */ - #if CYTHON_PEP489_MULTI_PHASE_INIT - 0, /* m_size */ - #else - -1, /* m_size */ - #endif - __pyx_methods /* m_methods */, - #if CYTHON_PEP489_MULTI_PHASE_INIT - __pyx_moduledef_slots, /* m_slots */ - #else - NULL, /* m_reload */ - #endif - NULL, /* m_traverse */ - NULL, /* m_clear */ - NULL /* m_free */ -}; -#endif -#ifndef CYTHON_SMALL_CODE -#if defined(__clang__) - #define CYTHON_SMALL_CODE -#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) - #define CYTHON_SMALL_CODE __attribute__((cold)) -#else - #define CYTHON_SMALL_CODE -#endif -#endif - -static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_kp_u_, __pyx_k_, sizeof(__pyx_k_), 0, 1, 0, 0}, - {&__pyx_n_s_ACCEPT, __pyx_k_ACCEPT, sizeof(__pyx_k_ACCEPT), 0, 0, 1, 1}, - {&__pyx_n_s_ACCEPT_CHARSET, __pyx_k_ACCEPT_CHARSET, sizeof(__pyx_k_ACCEPT_CHARSET), 0, 0, 1, 1}, - {&__pyx_n_s_ACCEPT_ENCODING, __pyx_k_ACCEPT_ENCODING, sizeof(__pyx_k_ACCEPT_ENCODING), 0, 0, 1, 1}, - {&__pyx_n_s_ACCEPT_LANGUAGE, __pyx_k_ACCEPT_LANGUAGE, sizeof(__pyx_k_ACCEPT_LANGUAGE), 0, 0, 1, 1}, - {&__pyx_n_s_ACCEPT_RANGES, __pyx_k_ACCEPT_RANGES, sizeof(__pyx_k_ACCEPT_RANGES), 0, 0, 1, 1}, - {&__pyx_n_s_ACCESS_CONTROL_ALLOW_CREDENTIALS, __pyx_k_ACCESS_CONTROL_ALLOW_CREDENTIALS, sizeof(__pyx_k_ACCESS_CONTROL_ALLOW_CREDENTIALS), 0, 0, 1, 1}, - {&__pyx_n_s_ACCESS_CONTROL_ALLOW_HEADERS, __pyx_k_ACCESS_CONTROL_ALLOW_HEADERS, sizeof(__pyx_k_ACCESS_CONTROL_ALLOW_HEADERS), 0, 0, 1, 1}, - {&__pyx_n_s_ACCESS_CONTROL_ALLOW_METHODS, __pyx_k_ACCESS_CONTROL_ALLOW_METHODS, sizeof(__pyx_k_ACCESS_CONTROL_ALLOW_METHODS), 0, 0, 1, 1}, - {&__pyx_n_s_ACCESS_CONTROL_ALLOW_ORIGIN, __pyx_k_ACCESS_CONTROL_ALLOW_ORIGIN, sizeof(__pyx_k_ACCESS_CONTROL_ALLOW_ORIGIN), 0, 0, 1, 1}, - {&__pyx_n_s_ACCESS_CONTROL_EXPOSE_HEADERS, __pyx_k_ACCESS_CONTROL_EXPOSE_HEADERS, sizeof(__pyx_k_ACCESS_CONTROL_EXPOSE_HEADERS), 0, 0, 1, 1}, - {&__pyx_n_s_ACCESS_CONTROL_MAX_AGE, __pyx_k_ACCESS_CONTROL_MAX_AGE, sizeof(__pyx_k_ACCESS_CONTROL_MAX_AGE), 0, 0, 1, 1}, - {&__pyx_n_s_ACCESS_CONTROL_REQUEST_HEADERS, __pyx_k_ACCESS_CONTROL_REQUEST_HEADERS, sizeof(__pyx_k_ACCESS_CONTROL_REQUEST_HEADERS), 0, 0, 1, 1}, - {&__pyx_n_s_ACCESS_CONTROL_REQUEST_METHOD, __pyx_k_ACCESS_CONTROL_REQUEST_METHOD, sizeof(__pyx_k_ACCESS_CONTROL_REQUEST_METHOD), 0, 0, 1, 1}, - {&__pyx_n_s_AGE, __pyx_k_AGE, sizeof(__pyx_k_AGE), 0, 0, 1, 1}, - {&__pyx_n_s_ALLOW, __pyx_k_ALLOW, sizeof(__pyx_k_ALLOW), 0, 0, 1, 1}, - {&__pyx_n_s_AUTHORIZATION, __pyx_k_AUTHORIZATION, sizeof(__pyx_k_AUTHORIZATION), 0, 0, 1, 1}, - {&__pyx_n_s_BadHttpMessage, __pyx_k_BadHttpMessage, sizeof(__pyx_k_BadHttpMessage), 0, 0, 1, 1}, - {&__pyx_n_s_BadStatusLine, __pyx_k_BadStatusLine, sizeof(__pyx_k_BadStatusLine), 0, 0, 1, 1}, - {&__pyx_n_s_BaseException, __pyx_k_BaseException, sizeof(__pyx_k_BaseException), 0, 0, 1, 1}, - {&__pyx_n_s_CACHE_CONTROL, __pyx_k_CACHE_CONTROL, sizeof(__pyx_k_CACHE_CONTROL), 0, 0, 1, 1}, - {&__pyx_n_s_CIMultiDict, __pyx_k_CIMultiDict, sizeof(__pyx_k_CIMultiDict), 0, 0, 1, 1}, - {&__pyx_n_s_CIMultiDictProxy, __pyx_k_CIMultiDictProxy, sizeof(__pyx_k_CIMultiDictProxy), 0, 0, 1, 1}, - {&__pyx_n_s_CIMultiDictProxy_2, __pyx_k_CIMultiDictProxy_2, sizeof(__pyx_k_CIMultiDictProxy_2), 0, 0, 1, 1}, - {&__pyx_n_s_CIMultiDict_2, __pyx_k_CIMultiDict_2, sizeof(__pyx_k_CIMultiDict_2), 0, 0, 1, 1}, - {&__pyx_n_s_CONNECTION, __pyx_k_CONNECTION, sizeof(__pyx_k_CONNECTION), 0, 0, 1, 1}, - {&__pyx_n_s_CONTENT_DISPOSITION, __pyx_k_CONTENT_DISPOSITION, sizeof(__pyx_k_CONTENT_DISPOSITION), 0, 0, 1, 1}, - {&__pyx_n_s_CONTENT_ENCODING, __pyx_k_CONTENT_ENCODING, sizeof(__pyx_k_CONTENT_ENCODING), 0, 0, 1, 1}, - {&__pyx_n_s_CONTENT_LANGUAGE, __pyx_k_CONTENT_LANGUAGE, sizeof(__pyx_k_CONTENT_LANGUAGE), 0, 0, 1, 1}, - {&__pyx_n_s_CONTENT_LENGTH, __pyx_k_CONTENT_LENGTH, sizeof(__pyx_k_CONTENT_LENGTH), 0, 0, 1, 1}, - {&__pyx_n_s_CONTENT_LOCATION, __pyx_k_CONTENT_LOCATION, sizeof(__pyx_k_CONTENT_LOCATION), 0, 0, 1, 1}, - {&__pyx_n_s_CONTENT_MD5, __pyx_k_CONTENT_MD5, sizeof(__pyx_k_CONTENT_MD5), 0, 0, 1, 1}, - {&__pyx_n_s_CONTENT_RANGE, __pyx_k_CONTENT_RANGE, sizeof(__pyx_k_CONTENT_RANGE), 0, 0, 1, 1}, - {&__pyx_n_s_CONTENT_TRANSFER_ENCODING, __pyx_k_CONTENT_TRANSFER_ENCODING, sizeof(__pyx_k_CONTENT_TRANSFER_ENCODING), 0, 0, 1, 1}, - {&__pyx_n_s_CONTENT_TYPE, __pyx_k_CONTENT_TYPE, sizeof(__pyx_k_CONTENT_TYPE), 0, 0, 1, 1}, - {&__pyx_n_s_COOKIE, __pyx_k_COOKIE, sizeof(__pyx_k_COOKIE), 0, 0, 1, 1}, - {&__pyx_n_s_ContentLengthError, __pyx_k_ContentLengthError, sizeof(__pyx_k_ContentLengthError), 0, 0, 1, 1}, - {&__pyx_n_s_DATE, __pyx_k_DATE, sizeof(__pyx_k_DATE), 0, 0, 1, 1}, - {&__pyx_n_s_DESTINATION, __pyx_k_DESTINATION, sizeof(__pyx_k_DESTINATION), 0, 0, 1, 1}, - {&__pyx_n_s_DIGEST, __pyx_k_DIGEST, sizeof(__pyx_k_DIGEST), 0, 0, 1, 1}, - {&__pyx_n_s_DeflateBuffer, __pyx_k_DeflateBuffer, sizeof(__pyx_k_DeflateBuffer), 0, 0, 1, 1}, - {&__pyx_n_s_DeflateBuffer_2, __pyx_k_DeflateBuffer_2, sizeof(__pyx_k_DeflateBuffer_2), 0, 0, 1, 1}, - {&__pyx_n_s_EMPTY_PAYLOAD, __pyx_k_EMPTY_PAYLOAD, sizeof(__pyx_k_EMPTY_PAYLOAD), 0, 0, 1, 1}, - {&__pyx_n_s_EMPTY_PAYLOAD_2, __pyx_k_EMPTY_PAYLOAD_2, sizeof(__pyx_k_EMPTY_PAYLOAD_2), 0, 0, 1, 1}, - {&__pyx_n_s_ETAG, __pyx_k_ETAG, sizeof(__pyx_k_ETAG), 0, 0, 1, 1}, - {&__pyx_n_s_EXPECT, __pyx_k_EXPECT, sizeof(__pyx_k_EXPECT), 0, 0, 1, 1}, - {&__pyx_n_s_EXPIRES, __pyx_k_EXPIRES, sizeof(__pyx_k_EXPIRES), 0, 0, 1, 1}, - {&__pyx_n_s_FORWARDED, __pyx_k_FORWARDED, sizeof(__pyx_k_FORWARDED), 0, 0, 1, 1}, - {&__pyx_n_s_FROM, __pyx_k_FROM, sizeof(__pyx_k_FROM), 0, 0, 1, 1}, - {&__pyx_n_s_HOST, __pyx_k_HOST, sizeof(__pyx_k_HOST), 0, 0, 1, 1}, - {&__pyx_kp_u_Header_name_is_too_long, __pyx_k_Header_name_is_too_long, sizeof(__pyx_k_Header_name_is_too_long), 0, 1, 0, 0}, - {&__pyx_kp_u_Header_value_is_too_long, __pyx_k_Header_value_is_too_long, sizeof(__pyx_k_Header_value_is_too_long), 0, 1, 0, 0}, - {&__pyx_n_s_HttpRequestParser, __pyx_k_HttpRequestParser, sizeof(__pyx_k_HttpRequestParser), 0, 0, 1, 1}, - {&__pyx_n_u_HttpRequestParser, __pyx_k_HttpRequestParser, sizeof(__pyx_k_HttpRequestParser), 0, 1, 0, 1}, - {&__pyx_n_s_HttpResponseParser, __pyx_k_HttpResponseParser, sizeof(__pyx_k_HttpResponseParser), 0, 0, 1, 1}, - {&__pyx_n_u_HttpResponseParser, __pyx_k_HttpResponseParser, sizeof(__pyx_k_HttpResponseParser), 0, 1, 0, 1}, - {&__pyx_n_s_HttpVersion, __pyx_k_HttpVersion, sizeof(__pyx_k_HttpVersion), 0, 0, 1, 1}, - {&__pyx_n_s_HttpVersion10, __pyx_k_HttpVersion10, sizeof(__pyx_k_HttpVersion10), 0, 0, 1, 1}, - {&__pyx_n_s_HttpVersion10_2, __pyx_k_HttpVersion10_2, sizeof(__pyx_k_HttpVersion10_2), 0, 0, 1, 1}, - {&__pyx_n_s_HttpVersion11, __pyx_k_HttpVersion11, sizeof(__pyx_k_HttpVersion11), 0, 0, 1, 1}, - {&__pyx_n_s_HttpVersion11_2, __pyx_k_HttpVersion11_2, sizeof(__pyx_k_HttpVersion11_2), 0, 0, 1, 1}, - {&__pyx_n_s_HttpVersion_2, __pyx_k_HttpVersion_2, sizeof(__pyx_k_HttpVersion_2), 0, 0, 1, 1}, - {&__pyx_n_s_IF_MATCH, __pyx_k_IF_MATCH, sizeof(__pyx_k_IF_MATCH), 0, 0, 1, 1}, - {&__pyx_n_s_IF_MODIFIED_SINCE, __pyx_k_IF_MODIFIED_SINCE, sizeof(__pyx_k_IF_MODIFIED_SINCE), 0, 0, 1, 1}, - {&__pyx_n_s_IF_NONE_MATCH, __pyx_k_IF_NONE_MATCH, sizeof(__pyx_k_IF_NONE_MATCH), 0, 0, 1, 1}, - {&__pyx_n_s_IF_RANGE, __pyx_k_IF_RANGE, sizeof(__pyx_k_IF_RANGE), 0, 0, 1, 1}, - {&__pyx_n_s_IF_UNMODIFIED_SINCE, __pyx_k_IF_UNMODIFIED_SINCE, sizeof(__pyx_k_IF_UNMODIFIED_SINCE), 0, 0, 1, 1}, - {&__pyx_kp_s_Incompatible_checksums_s_vs_0x14, __pyx_k_Incompatible_checksums_s_vs_0x14, sizeof(__pyx_k_Incompatible_checksums_s_vs_0x14), 0, 0, 1, 0}, - {&__pyx_kp_s_Incompatible_checksums_s_vs_0xc7, __pyx_k_Incompatible_checksums_s_vs_0xc7, sizeof(__pyx_k_Incompatible_checksums_s_vs_0xc7), 0, 0, 1, 0}, - {&__pyx_n_s_InvalidHeader, __pyx_k_InvalidHeader, sizeof(__pyx_k_InvalidHeader), 0, 0, 1, 1}, - {&__pyx_n_s_InvalidURLError, __pyx_k_InvalidURLError, sizeof(__pyx_k_InvalidURLError), 0, 0, 1, 1}, - {&__pyx_n_s_KEEP_ALIVE, __pyx_k_KEEP_ALIVE, sizeof(__pyx_k_KEEP_ALIVE), 0, 0, 1, 1}, - {&__pyx_n_s_LAST_EVENT_ID, __pyx_k_LAST_EVENT_ID, sizeof(__pyx_k_LAST_EVENT_ID), 0, 0, 1, 1}, - {&__pyx_n_s_LAST_MODIFIED, __pyx_k_LAST_MODIFIED, sizeof(__pyx_k_LAST_MODIFIED), 0, 0, 1, 1}, - {&__pyx_n_s_LINK, __pyx_k_LINK, sizeof(__pyx_k_LINK), 0, 0, 1, 1}, - {&__pyx_n_s_LOCATION, __pyx_k_LOCATION, sizeof(__pyx_k_LOCATION), 0, 0, 1, 1}, - {&__pyx_n_s_LineTooLong, __pyx_k_LineTooLong, sizeof(__pyx_k_LineTooLong), 0, 0, 1, 1}, - {&__pyx_n_s_MAX_FORWARDS, __pyx_k_MAX_FORWARDS, sizeof(__pyx_k_MAX_FORWARDS), 0, 0, 1, 1}, - {&__pyx_n_s_MemoryError, __pyx_k_MemoryError, sizeof(__pyx_k_MemoryError), 0, 0, 1, 1}, - {&__pyx_kp_u_Not_enough_data_for_satisfy_cont, __pyx_k_Not_enough_data_for_satisfy_cont, sizeof(__pyx_k_Not_enough_data_for_satisfy_cont), 0, 1, 0, 0}, - {&__pyx_kp_u_Not_enough_data_for_satisfy_tran, __pyx_k_Not_enough_data_for_satisfy_tran, sizeof(__pyx_k_Not_enough_data_for_satisfy_tran), 0, 1, 0, 0}, - {&__pyx_n_s_ORIGIN, __pyx_k_ORIGIN, sizeof(__pyx_k_ORIGIN), 0, 0, 1, 1}, - {&__pyx_n_s_PRAGMA, __pyx_k_PRAGMA, sizeof(__pyx_k_PRAGMA), 0, 0, 1, 1}, - {&__pyx_n_s_PROXY_AUTHENTICATE, __pyx_k_PROXY_AUTHENTICATE, sizeof(__pyx_k_PROXY_AUTHENTICATE), 0, 0, 1, 1}, - {&__pyx_n_s_PROXY_AUTHORIZATION, __pyx_k_PROXY_AUTHORIZATION, sizeof(__pyx_k_PROXY_AUTHORIZATION), 0, 0, 1, 1}, - {&__pyx_n_s_PayloadEncodingError, __pyx_k_PayloadEncodingError, sizeof(__pyx_k_PayloadEncodingError), 0, 0, 1, 1}, - {&__pyx_n_s_PickleError, __pyx_k_PickleError, sizeof(__pyx_k_PickleError), 0, 0, 1, 1}, - {&__pyx_n_s_RANGE, __pyx_k_RANGE, sizeof(__pyx_k_RANGE), 0, 0, 1, 1}, - {&__pyx_n_s_REFERER, __pyx_k_REFERER, sizeof(__pyx_k_REFERER), 0, 0, 1, 1}, - {&__pyx_n_s_RETRY_AFTER, __pyx_k_RETRY_AFTER, sizeof(__pyx_k_RETRY_AFTER), 0, 0, 1, 1}, - {&__pyx_kp_u_RawRequestMessage, __pyx_k_RawRequestMessage, sizeof(__pyx_k_RawRequestMessage), 0, 1, 0, 0}, - {&__pyx_n_s_RawRequestMessage_2, __pyx_k_RawRequestMessage_2, sizeof(__pyx_k_RawRequestMessage_2), 0, 0, 1, 1}, - {&__pyx_n_u_RawRequestMessage_2, __pyx_k_RawRequestMessage_2, sizeof(__pyx_k_RawRequestMessage_2), 0, 1, 0, 1}, - {&__pyx_kp_u_RawResponseMessage, __pyx_k_RawResponseMessage, sizeof(__pyx_k_RawResponseMessage), 0, 1, 0, 0}, - {&__pyx_n_s_RawResponseMessage_2, __pyx_k_RawResponseMessage_2, sizeof(__pyx_k_RawResponseMessage_2), 0, 0, 1, 1}, - {&__pyx_n_u_RawResponseMessage_2, __pyx_k_RawResponseMessage_2, sizeof(__pyx_k_RawResponseMessage_2), 0, 1, 0, 1}, - {&__pyx_n_s_SEC_WEBSOCKET_ACCEPT, __pyx_k_SEC_WEBSOCKET_ACCEPT, sizeof(__pyx_k_SEC_WEBSOCKET_ACCEPT), 0, 0, 1, 1}, - {&__pyx_n_s_SEC_WEBSOCKET_EXTENSIONS, __pyx_k_SEC_WEBSOCKET_EXTENSIONS, sizeof(__pyx_k_SEC_WEBSOCKET_EXTENSIONS), 0, 0, 1, 1}, - {&__pyx_n_s_SEC_WEBSOCKET_KEY, __pyx_k_SEC_WEBSOCKET_KEY, sizeof(__pyx_k_SEC_WEBSOCKET_KEY), 0, 0, 1, 1}, - {&__pyx_n_s_SEC_WEBSOCKET_KEY1, __pyx_k_SEC_WEBSOCKET_KEY1, sizeof(__pyx_k_SEC_WEBSOCKET_KEY1), 0, 0, 1, 1}, - {&__pyx_n_s_SEC_WEBSOCKET_PROTOCOL, __pyx_k_SEC_WEBSOCKET_PROTOCOL, sizeof(__pyx_k_SEC_WEBSOCKET_PROTOCOL), 0, 0, 1, 1}, - {&__pyx_n_s_SEC_WEBSOCKET_VERSION, __pyx_k_SEC_WEBSOCKET_VERSION, sizeof(__pyx_k_SEC_WEBSOCKET_VERSION), 0, 0, 1, 1}, - {&__pyx_n_s_SERVER, __pyx_k_SERVER, sizeof(__pyx_k_SERVER), 0, 0, 1, 1}, - {&__pyx_n_s_SET_COOKIE, __pyx_k_SET_COOKIE, sizeof(__pyx_k_SET_COOKIE), 0, 0, 1, 1}, - {&__pyx_kp_u_Status_line_is_too_long, __pyx_k_Status_line_is_too_long, sizeof(__pyx_k_Status_line_is_too_long), 0, 1, 0, 0}, - {&__pyx_n_s_StreamReader, __pyx_k_StreamReader, sizeof(__pyx_k_StreamReader), 0, 0, 1, 1}, - {&__pyx_n_s_StreamReader_2, __pyx_k_StreamReader_2, sizeof(__pyx_k_StreamReader_2), 0, 0, 1, 1}, - {&__pyx_n_s_TE, __pyx_k_TE, sizeof(__pyx_k_TE), 0, 0, 1, 1}, - {&__pyx_n_s_TRAILER, __pyx_k_TRAILER, sizeof(__pyx_k_TRAILER), 0, 0, 1, 1}, - {&__pyx_n_s_TRANSFER_ENCODING, __pyx_k_TRANSFER_ENCODING, sizeof(__pyx_k_TRANSFER_ENCODING), 0, 0, 1, 1}, - {&__pyx_n_s_TransferEncodingError, __pyx_k_TransferEncodingError, sizeof(__pyx_k_TransferEncodingError), 0, 0, 1, 1}, - {&__pyx_n_s_TypeError, __pyx_k_TypeError, sizeof(__pyx_k_TypeError), 0, 0, 1, 1}, - {&__pyx_n_s_UPGRADE, __pyx_k_UPGRADE, sizeof(__pyx_k_UPGRADE), 0, 0, 1, 1}, - {&__pyx_n_s_URI, __pyx_k_URI, sizeof(__pyx_k_URI), 0, 0, 1, 1}, - {&__pyx_n_s_URL, __pyx_k_URL, sizeof(__pyx_k_URL), 0, 0, 1, 1}, - {&__pyx_n_s_URL_2, __pyx_k_URL_2, sizeof(__pyx_k_URL_2), 0, 0, 1, 1}, - {&__pyx_n_s_USER_AGENT, __pyx_k_USER_AGENT, sizeof(__pyx_k_USER_AGENT), 0, 0, 1, 1}, - {&__pyx_n_s_VARY, __pyx_k_VARY, sizeof(__pyx_k_VARY), 0, 0, 1, 1}, - {&__pyx_n_s_VIA, __pyx_k_VIA, sizeof(__pyx_k_VIA), 0, 0, 1, 1}, - {&__pyx_n_s_WANT_DIGEST, __pyx_k_WANT_DIGEST, sizeof(__pyx_k_WANT_DIGEST), 0, 0, 1, 1}, - {&__pyx_n_s_WARNING, __pyx_k_WARNING, sizeof(__pyx_k_WARNING), 0, 0, 1, 1}, - {&__pyx_n_s_WWW_AUTHENTICATE, __pyx_k_WWW_AUTHENTICATE, sizeof(__pyx_k_WWW_AUTHENTICATE), 0, 0, 1, 1}, - {&__pyx_n_s_X_FORWARDED_FOR, __pyx_k_X_FORWARDED_FOR, sizeof(__pyx_k_X_FORWARDED_FOR), 0, 0, 1, 1}, - {&__pyx_n_s_X_FORWARDED_HOST, __pyx_k_X_FORWARDED_HOST, sizeof(__pyx_k_X_FORWARDED_HOST), 0, 0, 1, 1}, - {&__pyx_n_s_X_FORWARDED_PROTO, __pyx_k_X_FORWARDED_PROTO, sizeof(__pyx_k_X_FORWARDED_PROTO), 0, 0, 1, 1}, - {&__pyx_kp_u__2, __pyx_k__2, sizeof(__pyx_k__2), 0, 1, 0, 0}, - {&__pyx_kp_u__3, __pyx_k__3, sizeof(__pyx_k__3), 0, 1, 0, 0}, - {&__pyx_n_s__4, __pyx_k__4, sizeof(__pyx_k__4), 0, 0, 1, 1}, - {&__pyx_kp_b__4, __pyx_k__4, sizeof(__pyx_k__4), 0, 0, 0, 0}, - {&__pyx_kp_u__4, __pyx_k__4, sizeof(__pyx_k__4), 0, 1, 0, 0}, - {&__pyx_kp_u__7, __pyx_k__7, sizeof(__pyx_k__7), 0, 1, 0, 0}, - {&__pyx_kp_u__8, __pyx_k__8, sizeof(__pyx_k__8), 0, 1, 0, 0}, - {&__pyx_n_s_add, __pyx_k_add, sizeof(__pyx_k_add), 0, 0, 1, 1}, - {&__pyx_n_s_aiohttp, __pyx_k_aiohttp, sizeof(__pyx_k_aiohttp), 0, 0, 1, 1}, - {&__pyx_n_s_aiohttp__http_parser, __pyx_k_aiohttp__http_parser, sizeof(__pyx_k_aiohttp__http_parser), 0, 0, 1, 1}, - {&__pyx_n_s_all, __pyx_k_all, sizeof(__pyx_k_all), 0, 0, 1, 1}, - {&__pyx_n_s_args, __pyx_k_args, sizeof(__pyx_k_args), 0, 0, 1, 1}, - {&__pyx_n_s_auto_decompress, __pyx_k_auto_decompress, sizeof(__pyx_k_auto_decompress), 0, 0, 1, 1}, - {&__pyx_n_s_begin_http_chunk_receiving, __pyx_k_begin_http_chunk_receiving, sizeof(__pyx_k_begin_http_chunk_receiving), 0, 0, 1, 1}, - {&__pyx_n_u_br, __pyx_k_br, sizeof(__pyx_k_br), 0, 1, 0, 1}, - {&__pyx_n_s_build, __pyx_k_build, sizeof(__pyx_k_build), 0, 0, 1, 1}, - {&__pyx_n_s_chunked, __pyx_k_chunked, sizeof(__pyx_k_chunked), 0, 0, 1, 1}, - {&__pyx_n_u_chunked, __pyx_k_chunked, sizeof(__pyx_k_chunked), 0, 1, 0, 1}, - {&__pyx_n_s_cline_in_traceback, __pyx_k_cline_in_traceback, sizeof(__pyx_k_cline_in_traceback), 0, 0, 1, 1}, - {&__pyx_n_s_close, __pyx_k_close, sizeof(__pyx_k_close), 0, 0, 1, 1}, - {&__pyx_n_s_code, __pyx_k_code, sizeof(__pyx_k_code), 0, 0, 1, 1}, - {&__pyx_n_u_code, __pyx_k_code, sizeof(__pyx_k_code), 0, 1, 0, 1}, - {&__pyx_n_s_compression, __pyx_k_compression, sizeof(__pyx_k_compression), 0, 0, 1, 1}, - {&__pyx_n_u_compression, __pyx_k_compression, sizeof(__pyx_k_compression), 0, 1, 0, 1}, - {&__pyx_n_u_deflate, __pyx_k_deflate, sizeof(__pyx_k_deflate), 0, 1, 0, 1}, - {&__pyx_n_s_dict, __pyx_k_dict, sizeof(__pyx_k_dict), 0, 0, 1, 1}, - {&__pyx_n_s_encoded, __pyx_k_encoded, sizeof(__pyx_k_encoded), 0, 0, 1, 1}, - {&__pyx_n_s_end_http_chunk_receiving, __pyx_k_end_http_chunk_receiving, sizeof(__pyx_k_end_http_chunk_receiving), 0, 0, 1, 1}, - {&__pyx_n_s_feed_data, __pyx_k_feed_data, sizeof(__pyx_k_feed_data), 0, 0, 1, 1}, - {&__pyx_n_s_feed_eof, __pyx_k_feed_eof, sizeof(__pyx_k_feed_eof), 0, 0, 1, 1}, - {&__pyx_n_s_fragment, __pyx_k_fragment, sizeof(__pyx_k_fragment), 0, 0, 1, 1}, - {&__pyx_n_s_genexpr, __pyx_k_genexpr, sizeof(__pyx_k_genexpr), 0, 0, 1, 1}, - {&__pyx_n_s_getstate, __pyx_k_getstate, sizeof(__pyx_k_getstate), 0, 0, 1, 1}, - {&__pyx_n_u_gzip, __pyx_k_gzip, sizeof(__pyx_k_gzip), 0, 1, 0, 1}, - {&__pyx_n_s_hdrs, __pyx_k_hdrs, sizeof(__pyx_k_hdrs), 0, 0, 1, 1}, - {&__pyx_n_s_headers, __pyx_k_headers, sizeof(__pyx_k_headers), 0, 0, 1, 1}, - {&__pyx_n_u_headers, __pyx_k_headers, sizeof(__pyx_k_headers), 0, 1, 0, 1}, - {&__pyx_n_s_http_exceptions, __pyx_k_http_exceptions, sizeof(__pyx_k_http_exceptions), 0, 0, 1, 1}, - {&__pyx_n_s_http_parser, __pyx_k_http_parser, sizeof(__pyx_k_http_parser), 0, 0, 1, 1}, - {&__pyx_n_s_http_writer, __pyx_k_http_writer, sizeof(__pyx_k_http_writer), 0, 0, 1, 1}, - {&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1}, - {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, - {&__pyx_n_s_limit, __pyx_k_limit, sizeof(__pyx_k_limit), 0, 0, 1, 1}, - {&__pyx_n_s_loop, __pyx_k_loop, sizeof(__pyx_k_loop), 0, 0, 1, 1}, - {&__pyx_n_s_lower, __pyx_k_lower, sizeof(__pyx_k_lower), 0, 0, 1, 1}, - {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, - {&__pyx_n_s_max_field_size, __pyx_k_max_field_size, sizeof(__pyx_k_max_field_size), 0, 0, 1, 1}, - {&__pyx_n_s_max_headers, __pyx_k_max_headers, sizeof(__pyx_k_max_headers), 0, 0, 1, 1}, - {&__pyx_n_s_max_line_size, __pyx_k_max_line_size, sizeof(__pyx_k_max_line_size), 0, 0, 1, 1}, - {&__pyx_n_s_method, __pyx_k_method, sizeof(__pyx_k_method), 0, 0, 1, 1}, - {&__pyx_n_u_method, __pyx_k_method, sizeof(__pyx_k_method), 0, 1, 0, 1}, - {&__pyx_n_s_multidict, __pyx_k_multidict, sizeof(__pyx_k_multidict), 0, 0, 1, 1}, - {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, - {&__pyx_n_s_new, __pyx_k_new, sizeof(__pyx_k_new), 0, 0, 1, 1}, - {&__pyx_kp_s_no_default___reduce___due_to_non, __pyx_k_no_default___reduce___due_to_non, sizeof(__pyx_k_no_default___reduce___due_to_non), 0, 0, 1, 0}, - {&__pyx_n_s_path, __pyx_k_path, sizeof(__pyx_k_path), 0, 0, 1, 1}, - {&__pyx_n_u_path, __pyx_k_path, sizeof(__pyx_k_path), 0, 1, 0, 1}, - {&__pyx_n_s_payload_exception, __pyx_k_payload_exception, sizeof(__pyx_k_payload_exception), 0, 0, 1, 1}, - {&__pyx_n_s_pickle, __pyx_k_pickle, sizeof(__pyx_k_pickle), 0, 0, 1, 1}, - {&__pyx_n_s_protocol, __pyx_k_protocol, sizeof(__pyx_k_protocol), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_PickleError, __pyx_k_pyx_PickleError, sizeof(__pyx_k_pyx_PickleError), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_checksum, __pyx_k_pyx_checksum, sizeof(__pyx_k_pyx_checksum), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_result, __pyx_k_pyx_result, sizeof(__pyx_k_pyx_result), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_state, __pyx_k_pyx_state, sizeof(__pyx_k_pyx_state), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_type, __pyx_k_pyx_type, sizeof(__pyx_k_pyx_type), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_unpickle_RawRequestMessage, __pyx_k_pyx_unpickle_RawRequestMessage, sizeof(__pyx_k_pyx_unpickle_RawRequestMessage), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_unpickle_RawResponseMessag, __pyx_k_pyx_unpickle_RawResponseMessag, sizeof(__pyx_k_pyx_unpickle_RawResponseMessag), 0, 0, 1, 1}, - {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, - {&__pyx_n_s_query_string, __pyx_k_query_string, sizeof(__pyx_k_query_string), 0, 0, 1, 1}, - {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, - {&__pyx_n_s_raw_headers, __pyx_k_raw_headers, sizeof(__pyx_k_raw_headers), 0, 0, 1, 1}, - {&__pyx_n_u_raw_headers, __pyx_k_raw_headers, sizeof(__pyx_k_raw_headers), 0, 1, 0, 1}, - {&__pyx_n_s_read_until_eof, __pyx_k_read_until_eof, sizeof(__pyx_k_read_until_eof), 0, 0, 1, 1}, - {&__pyx_n_s_reason, __pyx_k_reason, sizeof(__pyx_k_reason), 0, 0, 1, 1}, - {&__pyx_n_u_reason, __pyx_k_reason, sizeof(__pyx_k_reason), 0, 1, 0, 1}, - {&__pyx_n_s_reduce, __pyx_k_reduce, sizeof(__pyx_k_reduce), 0, 0, 1, 1}, - {&__pyx_n_s_reduce_cython, __pyx_k_reduce_cython, sizeof(__pyx_k_reduce_cython), 0, 0, 1, 1}, - {&__pyx_n_s_reduce_ex, __pyx_k_reduce_ex, sizeof(__pyx_k_reduce_ex), 0, 0, 1, 1}, - {&__pyx_n_s_repr___locals_genexpr, __pyx_k_repr___locals_genexpr, sizeof(__pyx_k_repr___locals_genexpr), 0, 0, 1, 1}, - {&__pyx_n_s_response_with_body, __pyx_k_response_with_body, sizeof(__pyx_k_response_with_body), 0, 0, 1, 1}, - {&__pyx_n_s_send, __pyx_k_send, sizeof(__pyx_k_send), 0, 0, 1, 1}, - {&__pyx_n_s_set_exception, __pyx_k_set_exception, sizeof(__pyx_k_set_exception), 0, 0, 1, 1}, - {&__pyx_n_s_setstate, __pyx_k_setstate, sizeof(__pyx_k_setstate), 0, 0, 1, 1}, - {&__pyx_n_s_setstate_cython, __pyx_k_setstate_cython, sizeof(__pyx_k_setstate_cython), 0, 0, 1, 1}, - {&__pyx_n_s_should_close, __pyx_k_should_close, sizeof(__pyx_k_should_close), 0, 0, 1, 1}, - {&__pyx_n_u_should_close, __pyx_k_should_close, sizeof(__pyx_k_should_close), 0, 1, 0, 1}, - {&__pyx_n_s_streams, __pyx_k_streams, sizeof(__pyx_k_streams), 0, 0, 1, 1}, - {&__pyx_kp_s_stringsource, __pyx_k_stringsource, sizeof(__pyx_k_stringsource), 0, 0, 1, 0}, - {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, - {&__pyx_n_s_throw, __pyx_k_throw, sizeof(__pyx_k_throw), 0, 0, 1, 1}, - {&__pyx_n_s_timer, __pyx_k_timer, sizeof(__pyx_k_timer), 0, 0, 1, 1}, - {&__pyx_kp_u_unknown, __pyx_k_unknown, sizeof(__pyx_k_unknown), 0, 1, 0, 0}, - {&__pyx_n_s_update, __pyx_k_update, sizeof(__pyx_k_update), 0, 0, 1, 1}, - {&__pyx_n_s_upgrade, __pyx_k_upgrade, sizeof(__pyx_k_upgrade), 0, 0, 1, 1}, - {&__pyx_n_u_upgrade, __pyx_k_upgrade, sizeof(__pyx_k_upgrade), 0, 1, 0, 1}, - {&__pyx_n_s_url, __pyx_k_url, sizeof(__pyx_k_url), 0, 0, 1, 1}, - {&__pyx_n_u_url, __pyx_k_url, sizeof(__pyx_k_url), 0, 1, 0, 1}, - {&__pyx_n_s_version, __pyx_k_version, sizeof(__pyx_k_version), 0, 0, 1, 1}, - {&__pyx_n_u_version, __pyx_k_version, sizeof(__pyx_k_version), 0, 1, 0, 1}, - {&__pyx_n_s_yarl, __pyx_k_yarl, sizeof(__pyx_k_yarl), 0, 0, 1, 1}, - {0, 0, 0, 0, 0, 0, 0} -}; -static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 87, __pyx_L1_error) - __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) __PYX_ERR(0, 316, __pyx_L1_error) - __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) __PYX_ERR(1, 2, __pyx_L1_error) - __pyx_builtin_BaseException = __Pyx_GetBuiltinName(__pyx_n_s_BaseException); if (!__pyx_builtin_BaseException) __PYX_ERR(0, 662, __pyx_L1_error) - return 0; - __pyx_L1_error:; - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); - - /* "(tree fragment)":2 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__5)) __PYX_ERR(1, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__5); - __Pyx_GIVEREF(__pyx_tuple__5); - - /* "(tree fragment)":4 - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - */ - __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__6)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__6); - __Pyx_GIVEREF(__pyx_tuple__6); - - /* "(tree fragment)":2 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - __pyx_tuple__9 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__9)) __PYX_ERR(1, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__9); - __Pyx_GIVEREF(__pyx_tuple__9); - - /* "(tree fragment)":4 - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - */ - __pyx_tuple__10 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__10)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__10); - __Pyx_GIVEREF(__pyx_tuple__10); - - /* "(tree fragment)":2 - * def __reduce_cython__(self): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - */ - __pyx_tuple__11 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__11)) __PYX_ERR(1, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__11); - __Pyx_GIVEREF(__pyx_tuple__11); - - /* "(tree fragment)":4 - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< - */ - __pyx_tuple__12 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__12)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__12); - __Pyx_GIVEREF(__pyx_tuple__12); - - /* "aiohttp/_http_parser.pyx":57 - * char* PyByteArray_AsString(object) - * - * __all__ = ('HttpRequestParser', 'HttpResponseParser', # <<<<<<<<<<<<<< - * 'RawRequestMessage', 'RawResponseMessage') - * - */ - __pyx_tuple__13 = PyTuple_Pack(4, __pyx_n_u_HttpRequestParser, __pyx_n_u_HttpResponseParser, __pyx_n_u_RawRequestMessage_2, __pyx_n_u_RawResponseMessage_2); if (unlikely(!__pyx_tuple__13)) __PYX_ERR(0, 57, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__13); - __Pyx_GIVEREF(__pyx_tuple__13); - - /* "(tree fragment)":1 - * def __pyx_unpickle_RawRequestMessage(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * cdef object __pyx_PickleError - * cdef object __pyx_result - */ - __pyx_tuple__14 = PyTuple_Pack(5, __pyx_n_s_pyx_type, __pyx_n_s_pyx_checksum, __pyx_n_s_pyx_state, __pyx_n_s_pyx_PickleError, __pyx_n_s_pyx_result); if (unlikely(!__pyx_tuple__14)) __PYX_ERR(1, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__14); - __Pyx_GIVEREF(__pyx_tuple__14); - __pyx_codeobj__15 = (PyObject*)__Pyx_PyCode_New(3, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__14, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_stringsource, __pyx_n_s_pyx_unpickle_RawRequestMessage, 1, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__15)) __PYX_ERR(1, 1, __pyx_L1_error) - __pyx_tuple__16 = PyTuple_Pack(5, __pyx_n_s_pyx_type, __pyx_n_s_pyx_checksum, __pyx_n_s_pyx_state, __pyx_n_s_pyx_PickleError, __pyx_n_s_pyx_result); if (unlikely(!__pyx_tuple__16)) __PYX_ERR(1, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__16); - __Pyx_GIVEREF(__pyx_tuple__16); - __pyx_codeobj__17 = (PyObject*)__Pyx_PyCode_New(3, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__16, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_stringsource, __pyx_n_s_pyx_unpickle_RawResponseMessag, 1, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__17)) __PYX_ERR(1, 1, __pyx_L1_error) - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_RefNannyFinishContext(); - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) { - if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error); - __pyx_int_21004882 = PyInt_FromLong(21004882L); if (unlikely(!__pyx_int_21004882)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_int_209127132 = PyInt_FromLong(209127132L); if (unlikely(!__pyx_int_209127132)) __PYX_ERR(0, 1, __pyx_L1_error) - return 0; - __pyx_L1_error:; - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(void); /*proto*/ - -static int __Pyx_modinit_global_init_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0); - /*--- Global init code ---*/ - __pyx_v_7aiohttp_12_http_parser_headers = ((PyObject*)Py_None); Py_INCREF(Py_None); - __pyx_v_7aiohttp_12_http_parser_URL = Py_None; Py_INCREF(Py_None); - __pyx_v_7aiohttp_12_http_parser_URL_build = Py_None; Py_INCREF(Py_None); - __pyx_v_7aiohttp_12_http_parser_CIMultiDict = Py_None; Py_INCREF(Py_None); - __pyx_v_7aiohttp_12_http_parser_CIMultiDictProxy = Py_None; Py_INCREF(Py_None); - __pyx_v_7aiohttp_12_http_parser_HttpVersion = Py_None; Py_INCREF(Py_None); - __pyx_v_7aiohttp_12_http_parser_HttpVersion10 = Py_None; Py_INCREF(Py_None); - __pyx_v_7aiohttp_12_http_parser_HttpVersion11 = Py_None; Py_INCREF(Py_None); - __pyx_v_7aiohttp_12_http_parser_SEC_WEBSOCKET_KEY1 = Py_None; Py_INCREF(Py_None); - __pyx_v_7aiohttp_12_http_parser_CONTENT_ENCODING = Py_None; Py_INCREF(Py_None); - __pyx_v_7aiohttp_12_http_parser_EMPTY_PAYLOAD = Py_None; Py_INCREF(Py_None); - __pyx_v_7aiohttp_12_http_parser_StreamReader = Py_None; Py_INCREF(Py_None); - __pyx_v_7aiohttp_12_http_parser_DeflateBuffer = Py_None; Py_INCREF(Py_None); - __pyx_v_7aiohttp_12_http_parser__http_method = ((PyObject*)Py_None); Py_INCREF(Py_None); - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_variable_export_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0); - /*--- Variable export code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_function_export_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0); - /*--- Function export code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_type_init_code(void) { - __Pyx_RefNannyDeclarations - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); - /*--- Type init code ---*/ - if (PyType_Ready(&__pyx_type_7aiohttp_12_http_parser_RawRequestMessage) < 0) __PYX_ERR(0, 110, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type_7aiohttp_12_http_parser_RawRequestMessage.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_7aiohttp_12_http_parser_RawRequestMessage.tp_dictoffset && __pyx_type_7aiohttp_12_http_parser_RawRequestMessage.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type_7aiohttp_12_http_parser_RawRequestMessage.tp_getattro = __Pyx_PyObject_GenericGetAttr; - } - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_RawRequestMessage_2, (PyObject *)&__pyx_type_7aiohttp_12_http_parser_RawRequestMessage) < 0) __PYX_ERR(0, 110, __pyx_L1_error) - if (__Pyx_setup_reduce((PyObject*)&__pyx_type_7aiohttp_12_http_parser_RawRequestMessage) < 0) __PYX_ERR(0, 110, __pyx_L1_error) - __pyx_ptype_7aiohttp_12_http_parser_RawRequestMessage = &__pyx_type_7aiohttp_12_http_parser_RawRequestMessage; - if (PyType_Ready(&__pyx_type_7aiohttp_12_http_parser_RawResponseMessage) < 0) __PYX_ERR(0, 210, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type_7aiohttp_12_http_parser_RawResponseMessage.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_7aiohttp_12_http_parser_RawResponseMessage.tp_dictoffset && __pyx_type_7aiohttp_12_http_parser_RawResponseMessage.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type_7aiohttp_12_http_parser_RawResponseMessage.tp_getattro = __Pyx_PyObject_GenericGetAttr; - } - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_RawResponseMessage_2, (PyObject *)&__pyx_type_7aiohttp_12_http_parser_RawResponseMessage) < 0) __PYX_ERR(0, 210, __pyx_L1_error) - if (__Pyx_setup_reduce((PyObject*)&__pyx_type_7aiohttp_12_http_parser_RawResponseMessage) < 0) __PYX_ERR(0, 210, __pyx_L1_error) - __pyx_ptype_7aiohttp_12_http_parser_RawResponseMessage = &__pyx_type_7aiohttp_12_http_parser_RawResponseMessage; - __pyx_vtabptr_7aiohttp_12_http_parser_HttpParser = &__pyx_vtable_7aiohttp_12_http_parser_HttpParser; - __pyx_vtable_7aiohttp_12_http_parser_HttpParser._init = (PyObject *(*)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *, enum llhttp_type, PyObject *, PyObject *, int, struct __pyx_opt_args_7aiohttp_12_http_parser_10HttpParser__init *__pyx_optional_args))__pyx_f_7aiohttp_12_http_parser_10HttpParser__init; - __pyx_vtable_7aiohttp_12_http_parser_HttpParser._process_header = (PyObject *(*)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *))__pyx_f_7aiohttp_12_http_parser_10HttpParser__process_header; - __pyx_vtable_7aiohttp_12_http_parser_HttpParser._on_header_field = (PyObject *(*)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *, char *, size_t))__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_header_field; - __pyx_vtable_7aiohttp_12_http_parser_HttpParser._on_header_value = (PyObject *(*)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *, char *, size_t))__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_header_value; - __pyx_vtable_7aiohttp_12_http_parser_HttpParser._on_headers_complete = (PyObject *(*)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *))__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_headers_complete; - __pyx_vtable_7aiohttp_12_http_parser_HttpParser._on_message_complete = (PyObject *(*)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *))__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_message_complete; - __pyx_vtable_7aiohttp_12_http_parser_HttpParser._on_chunk_header = (PyObject *(*)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *))__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_chunk_header; - __pyx_vtable_7aiohttp_12_http_parser_HttpParser._on_chunk_complete = (PyObject *(*)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *))__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_chunk_complete; - __pyx_vtable_7aiohttp_12_http_parser_HttpParser._on_status_complete = (PyObject *(*)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *))__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_status_complete; - __pyx_vtable_7aiohttp_12_http_parser_HttpParser.http_version = (PyObject *(*)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *))__pyx_f_7aiohttp_12_http_parser_10HttpParser_http_version; - if (PyType_Ready(&__pyx_type_7aiohttp_12_http_parser_HttpParser) < 0) __PYX_ERR(0, 272, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type_7aiohttp_12_http_parser_HttpParser.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_7aiohttp_12_http_parser_HttpParser.tp_dictoffset && __pyx_type_7aiohttp_12_http_parser_HttpParser.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type_7aiohttp_12_http_parser_HttpParser.tp_getattro = __Pyx_PyObject_GenericGetAttr; - } - if (__Pyx_SetVtable(__pyx_type_7aiohttp_12_http_parser_HttpParser.tp_dict, __pyx_vtabptr_7aiohttp_12_http_parser_HttpParser) < 0) __PYX_ERR(0, 272, __pyx_L1_error) - if (__Pyx_setup_reduce((PyObject*)&__pyx_type_7aiohttp_12_http_parser_HttpParser) < 0) __PYX_ERR(0, 272, __pyx_L1_error) - __pyx_ptype_7aiohttp_12_http_parser_HttpParser = &__pyx_type_7aiohttp_12_http_parser_HttpParser; - __pyx_vtabptr_7aiohttp_12_http_parser_HttpRequestParser = &__pyx_vtable_7aiohttp_12_http_parser_HttpRequestParser; - __pyx_vtable_7aiohttp_12_http_parser_HttpRequestParser.__pyx_base = *__pyx_vtabptr_7aiohttp_12_http_parser_HttpParser; - __pyx_vtable_7aiohttp_12_http_parser_HttpRequestParser.__pyx_base._on_status_complete = (PyObject *(*)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *))__pyx_f_7aiohttp_12_http_parser_17HttpRequestParser__on_status_complete; - __pyx_type_7aiohttp_12_http_parser_HttpRequestParser.tp_base = __pyx_ptype_7aiohttp_12_http_parser_HttpParser; - if (PyType_Ready(&__pyx_type_7aiohttp_12_http_parser_HttpRequestParser) < 0) __PYX_ERR(0, 568, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type_7aiohttp_12_http_parser_HttpRequestParser.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_7aiohttp_12_http_parser_HttpRequestParser.tp_dictoffset && __pyx_type_7aiohttp_12_http_parser_HttpRequestParser.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type_7aiohttp_12_http_parser_HttpRequestParser.tp_getattro = __Pyx_PyObject_GenericGetAttr; - } - if (__Pyx_SetVtable(__pyx_type_7aiohttp_12_http_parser_HttpRequestParser.tp_dict, __pyx_vtabptr_7aiohttp_12_http_parser_HttpRequestParser) < 0) __PYX_ERR(0, 568, __pyx_L1_error) - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_HttpRequestParser, (PyObject *)&__pyx_type_7aiohttp_12_http_parser_HttpRequestParser) < 0) __PYX_ERR(0, 568, __pyx_L1_error) - if (__Pyx_setup_reduce((PyObject*)&__pyx_type_7aiohttp_12_http_parser_HttpRequestParser) < 0) __PYX_ERR(0, 568, __pyx_L1_error) - __pyx_ptype_7aiohttp_12_http_parser_HttpRequestParser = &__pyx_type_7aiohttp_12_http_parser_HttpRequestParser; - __pyx_vtabptr_7aiohttp_12_http_parser_HttpResponseParser = &__pyx_vtable_7aiohttp_12_http_parser_HttpResponseParser; - __pyx_vtable_7aiohttp_12_http_parser_HttpResponseParser.__pyx_base = *__pyx_vtabptr_7aiohttp_12_http_parser_HttpParser; - __pyx_vtable_7aiohttp_12_http_parser_HttpResponseParser.__pyx_base._on_status_complete = (PyObject *(*)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *))__pyx_f_7aiohttp_12_http_parser_18HttpResponseParser__on_status_complete; - __pyx_type_7aiohttp_12_http_parser_HttpResponseParser.tp_base = __pyx_ptype_7aiohttp_12_http_parser_HttpParser; - if (PyType_Ready(&__pyx_type_7aiohttp_12_http_parser_HttpResponseParser) < 0) __PYX_ERR(0, 621, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type_7aiohttp_12_http_parser_HttpResponseParser.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_7aiohttp_12_http_parser_HttpResponseParser.tp_dictoffset && __pyx_type_7aiohttp_12_http_parser_HttpResponseParser.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type_7aiohttp_12_http_parser_HttpResponseParser.tp_getattro = __Pyx_PyObject_GenericGetAttr; - } - if (__Pyx_SetVtable(__pyx_type_7aiohttp_12_http_parser_HttpResponseParser.tp_dict, __pyx_vtabptr_7aiohttp_12_http_parser_HttpResponseParser) < 0) __PYX_ERR(0, 621, __pyx_L1_error) - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_HttpResponseParser, (PyObject *)&__pyx_type_7aiohttp_12_http_parser_HttpResponseParser) < 0) __PYX_ERR(0, 621, __pyx_L1_error) - if (__Pyx_setup_reduce((PyObject*)&__pyx_type_7aiohttp_12_http_parser_HttpResponseParser) < 0) __PYX_ERR(0, 621, __pyx_L1_error) - __pyx_ptype_7aiohttp_12_http_parser_HttpResponseParser = &__pyx_type_7aiohttp_12_http_parser_HttpResponseParser; - if (PyType_Ready(&__pyx_type_7aiohttp_12_http_parser___pyx_scope_struct____repr__) < 0) __PYX_ERR(0, 135, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type_7aiohttp_12_http_parser___pyx_scope_struct____repr__.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_7aiohttp_12_http_parser___pyx_scope_struct____repr__.tp_dictoffset && __pyx_type_7aiohttp_12_http_parser___pyx_scope_struct____repr__.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type_7aiohttp_12_http_parser___pyx_scope_struct____repr__.tp_getattro = __Pyx_PyObject_GenericGetAttrNoDict; - } - __pyx_ptype_7aiohttp_12_http_parser___pyx_scope_struct____repr__ = &__pyx_type_7aiohttp_12_http_parser___pyx_scope_struct____repr__; - if (PyType_Ready(&__pyx_type_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr) < 0) __PYX_ERR(0, 147, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr.tp_dictoffset && __pyx_type_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr.tp_getattro = __Pyx_PyObject_GenericGetAttrNoDict; - } - __pyx_ptype_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr = &__pyx_type_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr; - if (PyType_Ready(&__pyx_type_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__) < 0) __PYX_ERR(0, 233, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__.tp_dictoffset && __pyx_type_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__.tp_getattro = __Pyx_PyObject_GenericGetAttrNoDict; - } - __pyx_ptype_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__ = &__pyx_type_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__; - if (PyType_Ready(&__pyx_type_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr) < 0) __PYX_ERR(0, 244, __pyx_L1_error) - #if PY_VERSION_HEX < 0x030800B1 - __pyx_type_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr.tp_print = 0; - #endif - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr.tp_dictoffset && __pyx_type_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr.tp_getattro = __Pyx_PyObject_GenericGetAttrNoDict; - } - __pyx_ptype_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr = &__pyx_type_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr; - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_RefNannyFinishContext(); - return -1; -} - -static int __Pyx_modinit_type_import_code(void) { - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); - /*--- Type import code ---*/ - __pyx_t_1 = PyImport_ImportModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 9, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__pyx_t_1, __Pyx_BUILTIN_MODULE_NAME, "type", - #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 - sizeof(PyTypeObject), - #else - sizeof(PyHeapTypeObject), - #endif - __Pyx_ImportType_CheckSize_Warn); - if (!__pyx_ptype_7cpython_4type_type) __PYX_ERR(2, 9, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyImport_ImportModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 8, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_ptype_7cpython_4bool_bool = __Pyx_ImportType(__pyx_t_1, __Pyx_BUILTIN_MODULE_NAME, "bool", sizeof(PyBoolObject), __Pyx_ImportType_CheckSize_Warn); - if (!__pyx_ptype_7cpython_4bool_bool) __PYX_ERR(3, 8, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyImport_ImportModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_t_1)) __PYX_ERR(4, 15, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_ptype_7cpython_7complex_complex = __Pyx_ImportType(__pyx_t_1, __Pyx_BUILTIN_MODULE_NAME, "complex", sizeof(PyComplexObject), __Pyx_ImportType_CheckSize_Warn); - if (!__pyx_ptype_7cpython_7complex_complex) __PYX_ERR(4, 15, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_RefNannyFinishContext(); - return -1; -} - -static int __Pyx_modinit_variable_import_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0); - /*--- Variable import code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_function_import_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0); - /*--- Function import code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - - -#ifndef CYTHON_NO_PYINIT_EXPORT -#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC -#elif PY_MAJOR_VERSION < 3 -#ifdef __cplusplus -#define __Pyx_PyMODINIT_FUNC extern "C" void -#else -#define __Pyx_PyMODINIT_FUNC void -#endif -#else -#ifdef __cplusplus -#define __Pyx_PyMODINIT_FUNC extern "C" PyObject * -#else -#define __Pyx_PyMODINIT_FUNC PyObject * -#endif -#endif - - -#if PY_MAJOR_VERSION < 3 -__Pyx_PyMODINIT_FUNC init_http_parser(void) CYTHON_SMALL_CODE; /*proto*/ -__Pyx_PyMODINIT_FUNC init_http_parser(void) -#else -__Pyx_PyMODINIT_FUNC PyInit__http_parser(void) CYTHON_SMALL_CODE; /*proto*/ -__Pyx_PyMODINIT_FUNC PyInit__http_parser(void) -#if CYTHON_PEP489_MULTI_PHASE_INIT -{ - return PyModuleDef_Init(&__pyx_moduledef); -} -static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { - #if PY_VERSION_HEX >= 0x030700A1 - static PY_INT64_T main_interpreter_id = -1; - PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); - if (main_interpreter_id == -1) { - main_interpreter_id = current_id; - return (unlikely(current_id == -1)) ? -1 : 0; - } else if (unlikely(main_interpreter_id != current_id)) - #else - static PyInterpreterState *main_interpreter = NULL; - PyInterpreterState *current_interpreter = PyThreadState_Get()->interp; - if (!main_interpreter) { - main_interpreter = current_interpreter; - } else if (unlikely(main_interpreter != current_interpreter)) - #endif - { - PyErr_SetString( - PyExc_ImportError, - "Interpreter change detected - this module can only be loaded into one interpreter per process."); - return -1; - } - return 0; -} -static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) { - PyObject *value = PyObject_GetAttrString(spec, from_name); - int result = 0; - if (likely(value)) { - if (allow_none || value != Py_None) { - result = PyDict_SetItemString(moddict, to_name, value); - } - Py_DECREF(value); - } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Clear(); - } else { - result = -1; - } - return result; -} -static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, CYTHON_UNUSED PyModuleDef *def) { - PyObject *module = NULL, *moddict, *modname; - if (__Pyx_check_single_interpreter()) - return NULL; - if (__pyx_m) - return __Pyx_NewRef(__pyx_m); - modname = PyObject_GetAttrString(spec, "name"); - if (unlikely(!modname)) goto bad; - module = PyModule_NewObject(modname); - Py_DECREF(modname); - if (unlikely(!module)) goto bad; - moddict = PyModule_GetDict(module); - if (unlikely(!moddict)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; - return module; -bad: - Py_XDECREF(module); - return NULL; -} - - -static CYTHON_SMALL_CODE int __pyx_pymod_exec__http_parser(PyObject *__pyx_pyinit_module) -#endif -#endif -{ - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; - PyObject *__pyx_t_11 = NULL; - PyObject *__pyx_t_12 = NULL; - PyObject *__pyx_t_13 = NULL; - PyObject *__pyx_t_14 = NULL; - PyObject *__pyx_t_15 = NULL; - PyObject *__pyx_t_16 = NULL; - PyObject *__pyx_t_17 = NULL; - PyObject *__pyx_t_18 = NULL; - PyObject *__pyx_t_19 = NULL; - PyObject *__pyx_t_20 = NULL; - PyObject *__pyx_t_21 = NULL; - PyObject *__pyx_t_22 = NULL; - PyObject *__pyx_t_23 = NULL; - PyObject *__pyx_t_24 = NULL; - PyObject *__pyx_t_25 = NULL; - PyObject *__pyx_t_26 = NULL; - PyObject *__pyx_t_27 = NULL; - PyObject *__pyx_t_28 = NULL; - PyObject *__pyx_t_29 = NULL; - PyObject *__pyx_t_30 = NULL; - PyObject *__pyx_t_31 = NULL; - PyObject *__pyx_t_32 = NULL; - PyObject *__pyx_t_33 = NULL; - PyObject *__pyx_t_34 = NULL; - PyObject *__pyx_t_35 = NULL; - PyObject *__pyx_t_36 = NULL; - PyObject *__pyx_t_37 = NULL; - PyObject *__pyx_t_38 = NULL; - PyObject *__pyx_t_39 = NULL; - PyObject *__pyx_t_40 = NULL; - PyObject *__pyx_t_41 = NULL; - PyObject *__pyx_t_42 = NULL; - PyObject *__pyx_t_43 = NULL; - PyObject *__pyx_t_44 = NULL; - PyObject *__pyx_t_45 = NULL; - PyObject *__pyx_t_46 = NULL; - PyObject *__pyx_t_47 = NULL; - PyObject *__pyx_t_48 = NULL; - PyObject *__pyx_t_49 = NULL; - PyObject *__pyx_t_50 = NULL; - PyObject *__pyx_t_51 = NULL; - PyObject *__pyx_t_52 = NULL; - PyObject *__pyx_t_53 = NULL; - PyObject *__pyx_t_54 = NULL; - PyObject *__pyx_t_55 = NULL; - PyObject *__pyx_t_56 = NULL; - PyObject *__pyx_t_57 = NULL; - PyObject *__pyx_t_58 = NULL; - PyObject *__pyx_t_59 = NULL; - PyObject *__pyx_t_60 = NULL; - PyObject *__pyx_t_61 = NULL; - PyObject *__pyx_t_62 = NULL; - PyObject *__pyx_t_63 = NULL; - PyObject *__pyx_t_64 = NULL; - PyObject *__pyx_t_65 = NULL; - PyObject *__pyx_t_66 = NULL; - PyObject *__pyx_t_67 = NULL; - PyObject *__pyx_t_68 = NULL; - PyObject *__pyx_t_69 = NULL; - PyObject *__pyx_t_70 = NULL; - PyObject *__pyx_t_71 = NULL; - PyObject *__pyx_t_72 = NULL; - PyObject *__pyx_t_73 = NULL; - PyObject *__pyx_t_74 = NULL; - PyObject *__pyx_t_75 = NULL; - PyObject *__pyx_t_76 = NULL; - PyObject *__pyx_t_77 = NULL; - PyObject *__pyx_t_78 = NULL; - long __pyx_t_79; - llhttp_method_t __pyx_t_80; - char const *__pyx_t_81; - int __pyx_t_82; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannyDeclarations - #if CYTHON_PEP489_MULTI_PHASE_INIT - if (__pyx_m) { - if (__pyx_m == __pyx_pyinit_module) return 0; - PyErr_SetString(PyExc_RuntimeError, "Module '_http_parser' has already been imported. Re-initialisation is not supported."); - return -1; - } - #elif PY_MAJOR_VERSION >= 3 - if (__pyx_m) return __Pyx_NewRef(__pyx_m); - #endif - #if CYTHON_REFNANNY -__Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); -if (!__Pyx_RefNanny) { - PyErr_Clear(); - __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); - if (!__Pyx_RefNanny) - Py_FatalError("failed to import 'refnanny' module"); -} -#endif - __Pyx_RefNannySetupContext("__Pyx_PyMODINIT_FUNC PyInit__http_parser(void)", 0); - if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #ifdef __Pxy_PyFrame_Initialize_Offsets - __Pxy_PyFrame_Initialize_Offsets(); - #endif - __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) - #ifdef __Pyx_CyFunction_USED - if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_FusedFunction_USED - if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_Coroutine_USED - if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_Generator_USED - if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_AsyncGen_USED - if (__pyx_AsyncGen_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_StopAsyncIteration_USED - if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - /*--- Library function declarations ---*/ - /*--- Threads initialization code ---*/ - #if defined(WITH_THREAD) && PY_VERSION_HEX < 0x030700F0 && defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS - PyEval_InitThreads(); - #endif - /*--- Module creation code ---*/ - #if CYTHON_PEP489_MULTI_PHASE_INIT - __pyx_m = __pyx_pyinit_module; - Py_INCREF(__pyx_m); - #else - #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4("_http_parser", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); - #else - __pyx_m = PyModule_Create(&__pyx_moduledef); - #endif - if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_d); - __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_b); - __pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_cython_runtime); - if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error); - /*--- Initialize various global constants etc. ---*/ - if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) - if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - if (__pyx_module_is_main_aiohttp___http_parser) { - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_name, __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - } - #if PY_MAJOR_VERSION >= 3 - { - PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) - if (!PyDict_GetItemString(modules, "aiohttp._http_parser")) { - if (unlikely(PyDict_SetItemString(modules, "aiohttp._http_parser", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error) - } - } - #endif - /*--- Builtin init code ---*/ - if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - /*--- Constants init code ---*/ - if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - /*--- Global type/function init code ---*/ - (void)__Pyx_modinit_global_init_code(); - (void)__Pyx_modinit_variable_export_code(); - (void)__Pyx_modinit_function_export_code(); - if (unlikely(__Pyx_modinit_type_init_code() < 0)) __PYX_ERR(0, 1, __pyx_L1_error) - if (unlikely(__Pyx_modinit_type_import_code() < 0)) __PYX_ERR(0, 1, __pyx_L1_error) - (void)__Pyx_modinit_variable_import_code(); - (void)__Pyx_modinit_function_import_code(); - /*--- Execution code ---*/ - #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) - if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - - /* "aiohttp/_http_parser.pyx":19 - * from libc.string cimport memcpy - * - * from multidict import CIMultiDict as _CIMultiDict, CIMultiDictProxy as _CIMultiDictProxy # <<<<<<<<<<<<<< - * from yarl import URL as _URL - * - */ - __pyx_t_1 = PyList_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 19, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_s_CIMultiDict); - __Pyx_GIVEREF(__pyx_n_s_CIMultiDict); - PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_CIMultiDict); - __Pyx_INCREF(__pyx_n_s_CIMultiDictProxy); - __Pyx_GIVEREF(__pyx_n_s_CIMultiDictProxy); - PyList_SET_ITEM(__pyx_t_1, 1, __pyx_n_s_CIMultiDictProxy); - __pyx_t_2 = __Pyx_Import(__pyx_n_s_multidict, __pyx_t_1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 19, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_CIMultiDict); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 19, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_CIMultiDict_2, __pyx_t_1) < 0) __PYX_ERR(0, 19, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_CIMultiDictProxy); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 19, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_CIMultiDictProxy_2, __pyx_t_1) < 0) __PYX_ERR(0, 19, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_http_parser.pyx":20 - * - * from multidict import CIMultiDict as _CIMultiDict, CIMultiDictProxy as _CIMultiDictProxy - * from yarl import URL as _URL # <<<<<<<<<<<<<< - * - * from aiohttp import hdrs - */ - __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 20, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_n_s_URL); - __Pyx_GIVEREF(__pyx_n_s_URL); - PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_URL); - __pyx_t_1 = __Pyx_Import(__pyx_n_s_yarl, __pyx_t_2, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 20, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s_URL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 20, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_URL_2, __pyx_t_2) < 0) __PYX_ERR(0, 20, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":22 - * from yarl import URL as _URL - * - * from aiohttp import hdrs # <<<<<<<<<<<<<< - * - * from .http_exceptions import ( - */ - __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 22, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_s_hdrs); - __Pyx_GIVEREF(__pyx_n_s_hdrs); - PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_hdrs); - __pyx_t_2 = __Pyx_Import(__pyx_n_s_aiohttp, __pyx_t_1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 22, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 22, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_hdrs, __pyx_t_1) < 0) __PYX_ERR(0, 22, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_http_parser.pyx":25 - * - * from .http_exceptions import ( - * BadHttpMessage, # <<<<<<<<<<<<<< - * BadStatusLine, - * ContentLengthError, - */ - __pyx_t_2 = PyList_New(8); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 25, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_n_s_BadHttpMessage); - __Pyx_GIVEREF(__pyx_n_s_BadHttpMessage); - PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_BadHttpMessage); - __Pyx_INCREF(__pyx_n_s_BadStatusLine); - __Pyx_GIVEREF(__pyx_n_s_BadStatusLine); - PyList_SET_ITEM(__pyx_t_2, 1, __pyx_n_s_BadStatusLine); - __Pyx_INCREF(__pyx_n_s_ContentLengthError); - __Pyx_GIVEREF(__pyx_n_s_ContentLengthError); - PyList_SET_ITEM(__pyx_t_2, 2, __pyx_n_s_ContentLengthError); - __Pyx_INCREF(__pyx_n_s_InvalidHeader); - __Pyx_GIVEREF(__pyx_n_s_InvalidHeader); - PyList_SET_ITEM(__pyx_t_2, 3, __pyx_n_s_InvalidHeader); - __Pyx_INCREF(__pyx_n_s_InvalidURLError); - __Pyx_GIVEREF(__pyx_n_s_InvalidURLError); - PyList_SET_ITEM(__pyx_t_2, 4, __pyx_n_s_InvalidURLError); - __Pyx_INCREF(__pyx_n_s_LineTooLong); - __Pyx_GIVEREF(__pyx_n_s_LineTooLong); - PyList_SET_ITEM(__pyx_t_2, 5, __pyx_n_s_LineTooLong); - __Pyx_INCREF(__pyx_n_s_PayloadEncodingError); - __Pyx_GIVEREF(__pyx_n_s_PayloadEncodingError); - PyList_SET_ITEM(__pyx_t_2, 6, __pyx_n_s_PayloadEncodingError); - __Pyx_INCREF(__pyx_n_s_TransferEncodingError); - __Pyx_GIVEREF(__pyx_n_s_TransferEncodingError); - PyList_SET_ITEM(__pyx_t_2, 7, __pyx_n_s_TransferEncodingError); - - /* "aiohttp/_http_parser.pyx":24 - * from aiohttp import hdrs - * - * from .http_exceptions import ( # <<<<<<<<<<<<<< - * BadHttpMessage, - * BadStatusLine, - */ - __pyx_t_1 = __Pyx_Import(__pyx_n_s_http_exceptions, __pyx_t_2, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 24, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s_BadHttpMessage); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 24, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_BadHttpMessage, __pyx_t_2) < 0) __PYX_ERR(0, 25, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s_BadStatusLine); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 24, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_BadStatusLine, __pyx_t_2) < 0) __PYX_ERR(0, 26, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s_ContentLengthError); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 24, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_ContentLengthError, __pyx_t_2) < 0) __PYX_ERR(0, 27, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s_InvalidHeader); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 24, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_InvalidHeader, __pyx_t_2) < 0) __PYX_ERR(0, 28, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s_InvalidURLError); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 24, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_InvalidURLError, __pyx_t_2) < 0) __PYX_ERR(0, 29, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s_LineTooLong); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 24, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_LineTooLong, __pyx_t_2) < 0) __PYX_ERR(0, 30, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s_PayloadEncodingError); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 24, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_PayloadEncodingError, __pyx_t_2) < 0) __PYX_ERR(0, 31, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s_TransferEncodingError); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 24, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_TransferEncodingError, __pyx_t_2) < 0) __PYX_ERR(0, 32, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":34 - * TransferEncodingError, - * ) - * from .http_parser import DeflateBuffer as _DeflateBuffer # <<<<<<<<<<<<<< - * from .http_writer import ( - * HttpVersion as _HttpVersion, - */ - __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 34, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_s_DeflateBuffer); - __Pyx_GIVEREF(__pyx_n_s_DeflateBuffer); - PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_DeflateBuffer); - __pyx_t_2 = __Pyx_Import(__pyx_n_s_http_parser, __pyx_t_1, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 34, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_DeflateBuffer); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 34, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_DeflateBuffer_2, __pyx_t_1) < 0) __PYX_ERR(0, 34, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_http_parser.pyx":36 - * from .http_parser import DeflateBuffer as _DeflateBuffer - * from .http_writer import ( - * HttpVersion as _HttpVersion, # <<<<<<<<<<<<<< - * HttpVersion10 as _HttpVersion10, - * HttpVersion11 as _HttpVersion11, - */ - __pyx_t_2 = PyList_New(3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 36, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_n_s_HttpVersion); - __Pyx_GIVEREF(__pyx_n_s_HttpVersion); - PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_HttpVersion); - __Pyx_INCREF(__pyx_n_s_HttpVersion10); - __Pyx_GIVEREF(__pyx_n_s_HttpVersion10); - PyList_SET_ITEM(__pyx_t_2, 1, __pyx_n_s_HttpVersion10); - __Pyx_INCREF(__pyx_n_s_HttpVersion11); - __Pyx_GIVEREF(__pyx_n_s_HttpVersion11); - PyList_SET_ITEM(__pyx_t_2, 2, __pyx_n_s_HttpVersion11); - - /* "aiohttp/_http_parser.pyx":35 - * ) - * from .http_parser import DeflateBuffer as _DeflateBuffer - * from .http_writer import ( # <<<<<<<<<<<<<< - * HttpVersion as _HttpVersion, - * HttpVersion10 as _HttpVersion10, - */ - __pyx_t_1 = __Pyx_Import(__pyx_n_s_http_writer, __pyx_t_2, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 35, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s_HttpVersion); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 35, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_HttpVersion_2, __pyx_t_2) < 0) __PYX_ERR(0, 36, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s_HttpVersion10); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 35, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_HttpVersion10_2, __pyx_t_2) < 0) __PYX_ERR(0, 37, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s_HttpVersion11); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 35, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_HttpVersion11_2, __pyx_t_2) < 0) __PYX_ERR(0, 38, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":40 - * HttpVersion11 as _HttpVersion11, - * ) - * from .streams import EMPTY_PAYLOAD as _EMPTY_PAYLOAD, StreamReader as _StreamReader # <<<<<<<<<<<<<< - * - * cimport cython - */ - __pyx_t_1 = PyList_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 40, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_s_EMPTY_PAYLOAD); - __Pyx_GIVEREF(__pyx_n_s_EMPTY_PAYLOAD); - PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_EMPTY_PAYLOAD); - __Pyx_INCREF(__pyx_n_s_StreamReader); - __Pyx_GIVEREF(__pyx_n_s_StreamReader); - PyList_SET_ITEM(__pyx_t_1, 1, __pyx_n_s_StreamReader); - __pyx_t_2 = __Pyx_Import(__pyx_n_s_streams, __pyx_t_1, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 40, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_EMPTY_PAYLOAD); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 40, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_EMPTY_PAYLOAD_2, __pyx_t_1) < 0) __PYX_ERR(0, 40, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_StreamReader); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 40, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_StreamReader_2, __pyx_t_1) < 0) __PYX_ERR(0, 40, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_headers.pxi":4 - * # Run ./tools/gen.py to update it after the origin changing. - * - * from . import hdrs # <<<<<<<<<<<<<< - * cdef tuple headers = ( - * hdrs.ACCEPT, - */ - __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(5, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_n_s_hdrs); - __Pyx_GIVEREF(__pyx_n_s_hdrs); - PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_hdrs); - __pyx_t_1 = __Pyx_Import(__pyx_n_s__4, __pyx_t_2, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_2)) __PYX_ERR(5, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_hdrs, __pyx_t_2) < 0) __PYX_ERR(5, 4, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":6 - * from . import hdrs - * cdef tuple headers = ( - * hdrs.ACCEPT, # <<<<<<<<<<<<<< - * hdrs.ACCEPT_CHARSET, - * hdrs.ACCEPT_ENCODING, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_ACCEPT); if (unlikely(!__pyx_t_2)) __PYX_ERR(5, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":7 - * cdef tuple headers = ( - * hdrs.ACCEPT, - * hdrs.ACCEPT_CHARSET, # <<<<<<<<<<<<<< - * hdrs.ACCEPT_ENCODING, - * hdrs.ACCEPT_LANGUAGE, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 7, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_ACCEPT_CHARSET); if (unlikely(!__pyx_t_3)) __PYX_ERR(5, 7, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":8 - * hdrs.ACCEPT, - * hdrs.ACCEPT_CHARSET, - * hdrs.ACCEPT_ENCODING, # <<<<<<<<<<<<<< - * hdrs.ACCEPT_LANGUAGE, - * hdrs.ACCEPT_RANGES, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 8, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_ACCEPT_ENCODING); if (unlikely(!__pyx_t_4)) __PYX_ERR(5, 8, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":9 - * hdrs.ACCEPT_CHARSET, - * hdrs.ACCEPT_ENCODING, - * hdrs.ACCEPT_LANGUAGE, # <<<<<<<<<<<<<< - * hdrs.ACCEPT_RANGES, - * hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 9, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_ACCEPT_LANGUAGE); if (unlikely(!__pyx_t_5)) __PYX_ERR(5, 9, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":10 - * hdrs.ACCEPT_ENCODING, - * hdrs.ACCEPT_LANGUAGE, - * hdrs.ACCEPT_RANGES, # <<<<<<<<<<<<<< - * hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, - * hdrs.ACCESS_CONTROL_ALLOW_HEADERS, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 10, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_ACCEPT_RANGES); if (unlikely(!__pyx_t_6)) __PYX_ERR(5, 10, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":11 - * hdrs.ACCEPT_LANGUAGE, - * hdrs.ACCEPT_RANGES, - * hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, # <<<<<<<<<<<<<< - * hdrs.ACCESS_CONTROL_ALLOW_HEADERS, - * hdrs.ACCESS_CONTROL_ALLOW_METHODS, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 11, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_ACCESS_CONTROL_ALLOW_CREDENTIALS); if (unlikely(!__pyx_t_7)) __PYX_ERR(5, 11, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":12 - * hdrs.ACCEPT_RANGES, - * hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, - * hdrs.ACCESS_CONTROL_ALLOW_HEADERS, # <<<<<<<<<<<<<< - * hdrs.ACCESS_CONTROL_ALLOW_METHODS, - * hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_ACCESS_CONTROL_ALLOW_HEADERS); if (unlikely(!__pyx_t_8)) __PYX_ERR(5, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":13 - * hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, - * hdrs.ACCESS_CONTROL_ALLOW_HEADERS, - * hdrs.ACCESS_CONTROL_ALLOW_METHODS, # <<<<<<<<<<<<<< - * hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, - * hdrs.ACCESS_CONTROL_EXPOSE_HEADERS, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_ACCESS_CONTROL_ALLOW_METHODS); if (unlikely(!__pyx_t_9)) __PYX_ERR(5, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":14 - * hdrs.ACCESS_CONTROL_ALLOW_HEADERS, - * hdrs.ACCESS_CONTROL_ALLOW_METHODS, - * hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, # <<<<<<<<<<<<<< - * hdrs.ACCESS_CONTROL_EXPOSE_HEADERS, - * hdrs.ACCESS_CONTROL_MAX_AGE, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_10 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_ACCESS_CONTROL_ALLOW_ORIGIN); if (unlikely(!__pyx_t_10)) __PYX_ERR(5, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":15 - * hdrs.ACCESS_CONTROL_ALLOW_METHODS, - * hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, - * hdrs.ACCESS_CONTROL_EXPOSE_HEADERS, # <<<<<<<<<<<<<< - * hdrs.ACCESS_CONTROL_MAX_AGE, - * hdrs.ACCESS_CONTROL_REQUEST_HEADERS, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 15, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_11 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_ACCESS_CONTROL_EXPOSE_HEADERS); if (unlikely(!__pyx_t_11)) __PYX_ERR(5, 15, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":16 - * hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, - * hdrs.ACCESS_CONTROL_EXPOSE_HEADERS, - * hdrs.ACCESS_CONTROL_MAX_AGE, # <<<<<<<<<<<<<< - * hdrs.ACCESS_CONTROL_REQUEST_HEADERS, - * hdrs.ACCESS_CONTROL_REQUEST_METHOD, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 16, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_ACCESS_CONTROL_MAX_AGE); if (unlikely(!__pyx_t_12)) __PYX_ERR(5, 16, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_12); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":17 - * hdrs.ACCESS_CONTROL_EXPOSE_HEADERS, - * hdrs.ACCESS_CONTROL_MAX_AGE, - * hdrs.ACCESS_CONTROL_REQUEST_HEADERS, # <<<<<<<<<<<<<< - * hdrs.ACCESS_CONTROL_REQUEST_METHOD, - * hdrs.AGE, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 17, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_13 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_ACCESS_CONTROL_REQUEST_HEADERS); if (unlikely(!__pyx_t_13)) __PYX_ERR(5, 17, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_13); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":18 - * hdrs.ACCESS_CONTROL_MAX_AGE, - * hdrs.ACCESS_CONTROL_REQUEST_HEADERS, - * hdrs.ACCESS_CONTROL_REQUEST_METHOD, # <<<<<<<<<<<<<< - * hdrs.AGE, - * hdrs.ALLOW, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 18, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_14 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_ACCESS_CONTROL_REQUEST_METHOD); if (unlikely(!__pyx_t_14)) __PYX_ERR(5, 18, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_14); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":19 - * hdrs.ACCESS_CONTROL_REQUEST_HEADERS, - * hdrs.ACCESS_CONTROL_REQUEST_METHOD, - * hdrs.AGE, # <<<<<<<<<<<<<< - * hdrs.ALLOW, - * hdrs.AUTHORIZATION, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 19, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_15 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_AGE); if (unlikely(!__pyx_t_15)) __PYX_ERR(5, 19, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_15); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":20 - * hdrs.ACCESS_CONTROL_REQUEST_METHOD, - * hdrs.AGE, - * hdrs.ALLOW, # <<<<<<<<<<<<<< - * hdrs.AUTHORIZATION, - * hdrs.CACHE_CONTROL, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 20, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_16 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_ALLOW); if (unlikely(!__pyx_t_16)) __PYX_ERR(5, 20, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_16); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":21 - * hdrs.AGE, - * hdrs.ALLOW, - * hdrs.AUTHORIZATION, # <<<<<<<<<<<<<< - * hdrs.CACHE_CONTROL, - * hdrs.CONNECTION, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 21, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_17 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_AUTHORIZATION); if (unlikely(!__pyx_t_17)) __PYX_ERR(5, 21, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_17); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":22 - * hdrs.ALLOW, - * hdrs.AUTHORIZATION, - * hdrs.CACHE_CONTROL, # <<<<<<<<<<<<<< - * hdrs.CONNECTION, - * hdrs.CONTENT_DISPOSITION, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 22, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_18 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_CACHE_CONTROL); if (unlikely(!__pyx_t_18)) __PYX_ERR(5, 22, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_18); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":23 - * hdrs.AUTHORIZATION, - * hdrs.CACHE_CONTROL, - * hdrs.CONNECTION, # <<<<<<<<<<<<<< - * hdrs.CONTENT_DISPOSITION, - * hdrs.CONTENT_ENCODING, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 23, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_19 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_CONNECTION); if (unlikely(!__pyx_t_19)) __PYX_ERR(5, 23, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_19); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":24 - * hdrs.CACHE_CONTROL, - * hdrs.CONNECTION, - * hdrs.CONTENT_DISPOSITION, # <<<<<<<<<<<<<< - * hdrs.CONTENT_ENCODING, - * hdrs.CONTENT_LANGUAGE, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 24, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_20 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_CONTENT_DISPOSITION); if (unlikely(!__pyx_t_20)) __PYX_ERR(5, 24, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_20); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":25 - * hdrs.CONNECTION, - * hdrs.CONTENT_DISPOSITION, - * hdrs.CONTENT_ENCODING, # <<<<<<<<<<<<<< - * hdrs.CONTENT_LANGUAGE, - * hdrs.CONTENT_LENGTH, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 25, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_21 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_CONTENT_ENCODING); if (unlikely(!__pyx_t_21)) __PYX_ERR(5, 25, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_21); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":26 - * hdrs.CONTENT_DISPOSITION, - * hdrs.CONTENT_ENCODING, - * hdrs.CONTENT_LANGUAGE, # <<<<<<<<<<<<<< - * hdrs.CONTENT_LENGTH, - * hdrs.CONTENT_LOCATION, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 26, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_22 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_CONTENT_LANGUAGE); if (unlikely(!__pyx_t_22)) __PYX_ERR(5, 26, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_22); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":27 - * hdrs.CONTENT_ENCODING, - * hdrs.CONTENT_LANGUAGE, - * hdrs.CONTENT_LENGTH, # <<<<<<<<<<<<<< - * hdrs.CONTENT_LOCATION, - * hdrs.CONTENT_MD5, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 27, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_23 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_CONTENT_LENGTH); if (unlikely(!__pyx_t_23)) __PYX_ERR(5, 27, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_23); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":28 - * hdrs.CONTENT_LANGUAGE, - * hdrs.CONTENT_LENGTH, - * hdrs.CONTENT_LOCATION, # <<<<<<<<<<<<<< - * hdrs.CONTENT_MD5, - * hdrs.CONTENT_RANGE, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 28, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_24 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_CONTENT_LOCATION); if (unlikely(!__pyx_t_24)) __PYX_ERR(5, 28, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_24); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":29 - * hdrs.CONTENT_LENGTH, - * hdrs.CONTENT_LOCATION, - * hdrs.CONTENT_MD5, # <<<<<<<<<<<<<< - * hdrs.CONTENT_RANGE, - * hdrs.CONTENT_TRANSFER_ENCODING, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 29, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_25 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_CONTENT_MD5); if (unlikely(!__pyx_t_25)) __PYX_ERR(5, 29, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_25); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":30 - * hdrs.CONTENT_LOCATION, - * hdrs.CONTENT_MD5, - * hdrs.CONTENT_RANGE, # <<<<<<<<<<<<<< - * hdrs.CONTENT_TRANSFER_ENCODING, - * hdrs.CONTENT_TYPE, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 30, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_26 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_CONTENT_RANGE); if (unlikely(!__pyx_t_26)) __PYX_ERR(5, 30, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_26); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":31 - * hdrs.CONTENT_MD5, - * hdrs.CONTENT_RANGE, - * hdrs.CONTENT_TRANSFER_ENCODING, # <<<<<<<<<<<<<< - * hdrs.CONTENT_TYPE, - * hdrs.COOKIE, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 31, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_27 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_CONTENT_TRANSFER_ENCODING); if (unlikely(!__pyx_t_27)) __PYX_ERR(5, 31, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_27); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":32 - * hdrs.CONTENT_RANGE, - * hdrs.CONTENT_TRANSFER_ENCODING, - * hdrs.CONTENT_TYPE, # <<<<<<<<<<<<<< - * hdrs.COOKIE, - * hdrs.DATE, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 32, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_28 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_CONTENT_TYPE); if (unlikely(!__pyx_t_28)) __PYX_ERR(5, 32, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_28); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":33 - * hdrs.CONTENT_TRANSFER_ENCODING, - * hdrs.CONTENT_TYPE, - * hdrs.COOKIE, # <<<<<<<<<<<<<< - * hdrs.DATE, - * hdrs.DESTINATION, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 33, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_29 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_COOKIE); if (unlikely(!__pyx_t_29)) __PYX_ERR(5, 33, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_29); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":34 - * hdrs.CONTENT_TYPE, - * hdrs.COOKIE, - * hdrs.DATE, # <<<<<<<<<<<<<< - * hdrs.DESTINATION, - * hdrs.DIGEST, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 34, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_30 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_DATE); if (unlikely(!__pyx_t_30)) __PYX_ERR(5, 34, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_30); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":35 - * hdrs.COOKIE, - * hdrs.DATE, - * hdrs.DESTINATION, # <<<<<<<<<<<<<< - * hdrs.DIGEST, - * hdrs.ETAG, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 35, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_31 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_DESTINATION); if (unlikely(!__pyx_t_31)) __PYX_ERR(5, 35, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_31); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":36 - * hdrs.DATE, - * hdrs.DESTINATION, - * hdrs.DIGEST, # <<<<<<<<<<<<<< - * hdrs.ETAG, - * hdrs.EXPECT, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 36, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_32 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_DIGEST); if (unlikely(!__pyx_t_32)) __PYX_ERR(5, 36, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_32); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":37 - * hdrs.DESTINATION, - * hdrs.DIGEST, - * hdrs.ETAG, # <<<<<<<<<<<<<< - * hdrs.EXPECT, - * hdrs.EXPIRES, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 37, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_33 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_ETAG); if (unlikely(!__pyx_t_33)) __PYX_ERR(5, 37, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_33); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":38 - * hdrs.DIGEST, - * hdrs.ETAG, - * hdrs.EXPECT, # <<<<<<<<<<<<<< - * hdrs.EXPIRES, - * hdrs.FORWARDED, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 38, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_34 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_EXPECT); if (unlikely(!__pyx_t_34)) __PYX_ERR(5, 38, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_34); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":39 - * hdrs.ETAG, - * hdrs.EXPECT, - * hdrs.EXPIRES, # <<<<<<<<<<<<<< - * hdrs.FORWARDED, - * hdrs.FROM, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 39, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_35 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_EXPIRES); if (unlikely(!__pyx_t_35)) __PYX_ERR(5, 39, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_35); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":40 - * hdrs.EXPECT, - * hdrs.EXPIRES, - * hdrs.FORWARDED, # <<<<<<<<<<<<<< - * hdrs.FROM, - * hdrs.HOST, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 40, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_36 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_FORWARDED); if (unlikely(!__pyx_t_36)) __PYX_ERR(5, 40, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_36); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":41 - * hdrs.EXPIRES, - * hdrs.FORWARDED, - * hdrs.FROM, # <<<<<<<<<<<<<< - * hdrs.HOST, - * hdrs.IF_MATCH, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 41, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_37 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_FROM); if (unlikely(!__pyx_t_37)) __PYX_ERR(5, 41, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_37); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":42 - * hdrs.FORWARDED, - * hdrs.FROM, - * hdrs.HOST, # <<<<<<<<<<<<<< - * hdrs.IF_MATCH, - * hdrs.IF_MODIFIED_SINCE, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 42, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_38 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_HOST); if (unlikely(!__pyx_t_38)) __PYX_ERR(5, 42, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_38); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":43 - * hdrs.FROM, - * hdrs.HOST, - * hdrs.IF_MATCH, # <<<<<<<<<<<<<< - * hdrs.IF_MODIFIED_SINCE, - * hdrs.IF_NONE_MATCH, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 43, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_39 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_IF_MATCH); if (unlikely(!__pyx_t_39)) __PYX_ERR(5, 43, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_39); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":44 - * hdrs.HOST, - * hdrs.IF_MATCH, - * hdrs.IF_MODIFIED_SINCE, # <<<<<<<<<<<<<< - * hdrs.IF_NONE_MATCH, - * hdrs.IF_RANGE, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 44, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_40 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_IF_MODIFIED_SINCE); if (unlikely(!__pyx_t_40)) __PYX_ERR(5, 44, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_40); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":45 - * hdrs.IF_MATCH, - * hdrs.IF_MODIFIED_SINCE, - * hdrs.IF_NONE_MATCH, # <<<<<<<<<<<<<< - * hdrs.IF_RANGE, - * hdrs.IF_UNMODIFIED_SINCE, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 45, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_41 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_IF_NONE_MATCH); if (unlikely(!__pyx_t_41)) __PYX_ERR(5, 45, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_41); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":46 - * hdrs.IF_MODIFIED_SINCE, - * hdrs.IF_NONE_MATCH, - * hdrs.IF_RANGE, # <<<<<<<<<<<<<< - * hdrs.IF_UNMODIFIED_SINCE, - * hdrs.KEEP_ALIVE, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 46, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_42 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_IF_RANGE); if (unlikely(!__pyx_t_42)) __PYX_ERR(5, 46, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_42); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":47 - * hdrs.IF_NONE_MATCH, - * hdrs.IF_RANGE, - * hdrs.IF_UNMODIFIED_SINCE, # <<<<<<<<<<<<<< - * hdrs.KEEP_ALIVE, - * hdrs.LAST_EVENT_ID, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 47, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_43 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_IF_UNMODIFIED_SINCE); if (unlikely(!__pyx_t_43)) __PYX_ERR(5, 47, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_43); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":48 - * hdrs.IF_RANGE, - * hdrs.IF_UNMODIFIED_SINCE, - * hdrs.KEEP_ALIVE, # <<<<<<<<<<<<<< - * hdrs.LAST_EVENT_ID, - * hdrs.LAST_MODIFIED, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 48, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_44 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_KEEP_ALIVE); if (unlikely(!__pyx_t_44)) __PYX_ERR(5, 48, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_44); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":49 - * hdrs.IF_UNMODIFIED_SINCE, - * hdrs.KEEP_ALIVE, - * hdrs.LAST_EVENT_ID, # <<<<<<<<<<<<<< - * hdrs.LAST_MODIFIED, - * hdrs.LINK, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 49, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_45 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_LAST_EVENT_ID); if (unlikely(!__pyx_t_45)) __PYX_ERR(5, 49, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_45); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":50 - * hdrs.KEEP_ALIVE, - * hdrs.LAST_EVENT_ID, - * hdrs.LAST_MODIFIED, # <<<<<<<<<<<<<< - * hdrs.LINK, - * hdrs.LOCATION, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 50, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_46 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_LAST_MODIFIED); if (unlikely(!__pyx_t_46)) __PYX_ERR(5, 50, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_46); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":51 - * hdrs.LAST_EVENT_ID, - * hdrs.LAST_MODIFIED, - * hdrs.LINK, # <<<<<<<<<<<<<< - * hdrs.LOCATION, - * hdrs.MAX_FORWARDS, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 51, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_47 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_LINK); if (unlikely(!__pyx_t_47)) __PYX_ERR(5, 51, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_47); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":52 - * hdrs.LAST_MODIFIED, - * hdrs.LINK, - * hdrs.LOCATION, # <<<<<<<<<<<<<< - * hdrs.MAX_FORWARDS, - * hdrs.ORIGIN, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 52, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_48 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_LOCATION); if (unlikely(!__pyx_t_48)) __PYX_ERR(5, 52, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_48); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":53 - * hdrs.LINK, - * hdrs.LOCATION, - * hdrs.MAX_FORWARDS, # <<<<<<<<<<<<<< - * hdrs.ORIGIN, - * hdrs.PRAGMA, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 53, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_49 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_MAX_FORWARDS); if (unlikely(!__pyx_t_49)) __PYX_ERR(5, 53, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_49); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":54 - * hdrs.LOCATION, - * hdrs.MAX_FORWARDS, - * hdrs.ORIGIN, # <<<<<<<<<<<<<< - * hdrs.PRAGMA, - * hdrs.PROXY_AUTHENTICATE, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 54, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_50 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_ORIGIN); if (unlikely(!__pyx_t_50)) __PYX_ERR(5, 54, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_50); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":55 - * hdrs.MAX_FORWARDS, - * hdrs.ORIGIN, - * hdrs.PRAGMA, # <<<<<<<<<<<<<< - * hdrs.PROXY_AUTHENTICATE, - * hdrs.PROXY_AUTHORIZATION, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 55, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_51 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_PRAGMA); if (unlikely(!__pyx_t_51)) __PYX_ERR(5, 55, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_51); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":56 - * hdrs.ORIGIN, - * hdrs.PRAGMA, - * hdrs.PROXY_AUTHENTICATE, # <<<<<<<<<<<<<< - * hdrs.PROXY_AUTHORIZATION, - * hdrs.RANGE, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 56, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_52 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_PROXY_AUTHENTICATE); if (unlikely(!__pyx_t_52)) __PYX_ERR(5, 56, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_52); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":57 - * hdrs.PRAGMA, - * hdrs.PROXY_AUTHENTICATE, - * hdrs.PROXY_AUTHORIZATION, # <<<<<<<<<<<<<< - * hdrs.RANGE, - * hdrs.REFERER, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 57, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_53 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_PROXY_AUTHORIZATION); if (unlikely(!__pyx_t_53)) __PYX_ERR(5, 57, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_53); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":58 - * hdrs.PROXY_AUTHENTICATE, - * hdrs.PROXY_AUTHORIZATION, - * hdrs.RANGE, # <<<<<<<<<<<<<< - * hdrs.REFERER, - * hdrs.RETRY_AFTER, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 58, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_54 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_RANGE); if (unlikely(!__pyx_t_54)) __PYX_ERR(5, 58, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_54); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":59 - * hdrs.PROXY_AUTHORIZATION, - * hdrs.RANGE, - * hdrs.REFERER, # <<<<<<<<<<<<<< - * hdrs.RETRY_AFTER, - * hdrs.SEC_WEBSOCKET_ACCEPT, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 59, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_55 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_REFERER); if (unlikely(!__pyx_t_55)) __PYX_ERR(5, 59, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_55); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":60 - * hdrs.RANGE, - * hdrs.REFERER, - * hdrs.RETRY_AFTER, # <<<<<<<<<<<<<< - * hdrs.SEC_WEBSOCKET_ACCEPT, - * hdrs.SEC_WEBSOCKET_EXTENSIONS, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 60, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_56 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_RETRY_AFTER); if (unlikely(!__pyx_t_56)) __PYX_ERR(5, 60, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_56); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":61 - * hdrs.REFERER, - * hdrs.RETRY_AFTER, - * hdrs.SEC_WEBSOCKET_ACCEPT, # <<<<<<<<<<<<<< - * hdrs.SEC_WEBSOCKET_EXTENSIONS, - * hdrs.SEC_WEBSOCKET_KEY, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 61, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_57 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_SEC_WEBSOCKET_ACCEPT); if (unlikely(!__pyx_t_57)) __PYX_ERR(5, 61, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_57); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":62 - * hdrs.RETRY_AFTER, - * hdrs.SEC_WEBSOCKET_ACCEPT, - * hdrs.SEC_WEBSOCKET_EXTENSIONS, # <<<<<<<<<<<<<< - * hdrs.SEC_WEBSOCKET_KEY, - * hdrs.SEC_WEBSOCKET_KEY1, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 62, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_58 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_SEC_WEBSOCKET_EXTENSIONS); if (unlikely(!__pyx_t_58)) __PYX_ERR(5, 62, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_58); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":63 - * hdrs.SEC_WEBSOCKET_ACCEPT, - * hdrs.SEC_WEBSOCKET_EXTENSIONS, - * hdrs.SEC_WEBSOCKET_KEY, # <<<<<<<<<<<<<< - * hdrs.SEC_WEBSOCKET_KEY1, - * hdrs.SEC_WEBSOCKET_PROTOCOL, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 63, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_59 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_SEC_WEBSOCKET_KEY); if (unlikely(!__pyx_t_59)) __PYX_ERR(5, 63, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_59); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":64 - * hdrs.SEC_WEBSOCKET_EXTENSIONS, - * hdrs.SEC_WEBSOCKET_KEY, - * hdrs.SEC_WEBSOCKET_KEY1, # <<<<<<<<<<<<<< - * hdrs.SEC_WEBSOCKET_PROTOCOL, - * hdrs.SEC_WEBSOCKET_VERSION, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 64, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_60 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_SEC_WEBSOCKET_KEY1); if (unlikely(!__pyx_t_60)) __PYX_ERR(5, 64, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_60); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":65 - * hdrs.SEC_WEBSOCKET_KEY, - * hdrs.SEC_WEBSOCKET_KEY1, - * hdrs.SEC_WEBSOCKET_PROTOCOL, # <<<<<<<<<<<<<< - * hdrs.SEC_WEBSOCKET_VERSION, - * hdrs.SERVER, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 65, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_61 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_SEC_WEBSOCKET_PROTOCOL); if (unlikely(!__pyx_t_61)) __PYX_ERR(5, 65, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_61); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":66 - * hdrs.SEC_WEBSOCKET_KEY1, - * hdrs.SEC_WEBSOCKET_PROTOCOL, - * hdrs.SEC_WEBSOCKET_VERSION, # <<<<<<<<<<<<<< - * hdrs.SERVER, - * hdrs.SET_COOKIE, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 66, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_62 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_SEC_WEBSOCKET_VERSION); if (unlikely(!__pyx_t_62)) __PYX_ERR(5, 66, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_62); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":67 - * hdrs.SEC_WEBSOCKET_PROTOCOL, - * hdrs.SEC_WEBSOCKET_VERSION, - * hdrs.SERVER, # <<<<<<<<<<<<<< - * hdrs.SET_COOKIE, - * hdrs.TE, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 67, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_63 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_SERVER); if (unlikely(!__pyx_t_63)) __PYX_ERR(5, 67, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_63); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":68 - * hdrs.SEC_WEBSOCKET_VERSION, - * hdrs.SERVER, - * hdrs.SET_COOKIE, # <<<<<<<<<<<<<< - * hdrs.TE, - * hdrs.TRAILER, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 68, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_64 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_SET_COOKIE); if (unlikely(!__pyx_t_64)) __PYX_ERR(5, 68, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_64); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":69 - * hdrs.SERVER, - * hdrs.SET_COOKIE, - * hdrs.TE, # <<<<<<<<<<<<<< - * hdrs.TRAILER, - * hdrs.TRANSFER_ENCODING, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 69, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_65 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_TE); if (unlikely(!__pyx_t_65)) __PYX_ERR(5, 69, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_65); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":70 - * hdrs.SET_COOKIE, - * hdrs.TE, - * hdrs.TRAILER, # <<<<<<<<<<<<<< - * hdrs.TRANSFER_ENCODING, - * hdrs.URI, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 70, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_66 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_TRAILER); if (unlikely(!__pyx_t_66)) __PYX_ERR(5, 70, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_66); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":71 - * hdrs.TE, - * hdrs.TRAILER, - * hdrs.TRANSFER_ENCODING, # <<<<<<<<<<<<<< - * hdrs.URI, - * hdrs.UPGRADE, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 71, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_67 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_TRANSFER_ENCODING); if (unlikely(!__pyx_t_67)) __PYX_ERR(5, 71, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_67); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":72 - * hdrs.TRAILER, - * hdrs.TRANSFER_ENCODING, - * hdrs.URI, # <<<<<<<<<<<<<< - * hdrs.UPGRADE, - * hdrs.USER_AGENT, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 72, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_68 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_URI); if (unlikely(!__pyx_t_68)) __PYX_ERR(5, 72, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_68); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":73 - * hdrs.TRANSFER_ENCODING, - * hdrs.URI, - * hdrs.UPGRADE, # <<<<<<<<<<<<<< - * hdrs.USER_AGENT, - * hdrs.VARY, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 73, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_69 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_UPGRADE); if (unlikely(!__pyx_t_69)) __PYX_ERR(5, 73, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_69); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":74 - * hdrs.URI, - * hdrs.UPGRADE, - * hdrs.USER_AGENT, # <<<<<<<<<<<<<< - * hdrs.VARY, - * hdrs.VIA, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 74, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_70 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_USER_AGENT); if (unlikely(!__pyx_t_70)) __PYX_ERR(5, 74, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_70); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":75 - * hdrs.UPGRADE, - * hdrs.USER_AGENT, - * hdrs.VARY, # <<<<<<<<<<<<<< - * hdrs.VIA, - * hdrs.WWW_AUTHENTICATE, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 75, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_71 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_VARY); if (unlikely(!__pyx_t_71)) __PYX_ERR(5, 75, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_71); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":76 - * hdrs.USER_AGENT, - * hdrs.VARY, - * hdrs.VIA, # <<<<<<<<<<<<<< - * hdrs.WWW_AUTHENTICATE, - * hdrs.WANT_DIGEST, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 76, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_72 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_VIA); if (unlikely(!__pyx_t_72)) __PYX_ERR(5, 76, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_72); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":77 - * hdrs.VARY, - * hdrs.VIA, - * hdrs.WWW_AUTHENTICATE, # <<<<<<<<<<<<<< - * hdrs.WANT_DIGEST, - * hdrs.WARNING, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 77, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_73 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_WWW_AUTHENTICATE); if (unlikely(!__pyx_t_73)) __PYX_ERR(5, 77, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_73); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":78 - * hdrs.VIA, - * hdrs.WWW_AUTHENTICATE, - * hdrs.WANT_DIGEST, # <<<<<<<<<<<<<< - * hdrs.WARNING, - * hdrs.X_FORWARDED_FOR, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 78, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_74 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_WANT_DIGEST); if (unlikely(!__pyx_t_74)) __PYX_ERR(5, 78, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_74); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":79 - * hdrs.WWW_AUTHENTICATE, - * hdrs.WANT_DIGEST, - * hdrs.WARNING, # <<<<<<<<<<<<<< - * hdrs.X_FORWARDED_FOR, - * hdrs.X_FORWARDED_HOST, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 79, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_75 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_WARNING); if (unlikely(!__pyx_t_75)) __PYX_ERR(5, 79, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_75); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":80 - * hdrs.WANT_DIGEST, - * hdrs.WARNING, - * hdrs.X_FORWARDED_FOR, # <<<<<<<<<<<<<< - * hdrs.X_FORWARDED_HOST, - * hdrs.X_FORWARDED_PROTO, - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 80, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_76 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_X_FORWARDED_FOR); if (unlikely(!__pyx_t_76)) __PYX_ERR(5, 80, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_76); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":81 - * hdrs.WARNING, - * hdrs.X_FORWARDED_FOR, - * hdrs.X_FORWARDED_HOST, # <<<<<<<<<<<<<< - * hdrs.X_FORWARDED_PROTO, - * ) - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 81, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_77 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_X_FORWARDED_HOST); if (unlikely(!__pyx_t_77)) __PYX_ERR(5, 81, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_77); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":82 - * hdrs.X_FORWARDED_FOR, - * hdrs.X_FORWARDED_HOST, - * hdrs.X_FORWARDED_PROTO, # <<<<<<<<<<<<<< - * ) - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 82, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_78 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_X_FORWARDED_PROTO); if (unlikely(!__pyx_t_78)) __PYX_ERR(5, 82, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_78); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_headers.pxi":6 - * from . import hdrs - * cdef tuple headers = ( - * hdrs.ACCEPT, # <<<<<<<<<<<<<< - * hdrs.ACCEPT_CHARSET, - * hdrs.ACCEPT_ENCODING, - */ - __pyx_t_1 = PyTuple_New(77); if (unlikely(!__pyx_t_1)) __PYX_ERR(5, 6, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_1, 3, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_1, 4, __pyx_t_6); - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_1, 5, __pyx_t_7); - __Pyx_GIVEREF(__pyx_t_8); - PyTuple_SET_ITEM(__pyx_t_1, 6, __pyx_t_8); - __Pyx_GIVEREF(__pyx_t_9); - PyTuple_SET_ITEM(__pyx_t_1, 7, __pyx_t_9); - __Pyx_GIVEREF(__pyx_t_10); - PyTuple_SET_ITEM(__pyx_t_1, 8, __pyx_t_10); - __Pyx_GIVEREF(__pyx_t_11); - PyTuple_SET_ITEM(__pyx_t_1, 9, __pyx_t_11); - __Pyx_GIVEREF(__pyx_t_12); - PyTuple_SET_ITEM(__pyx_t_1, 10, __pyx_t_12); - __Pyx_GIVEREF(__pyx_t_13); - PyTuple_SET_ITEM(__pyx_t_1, 11, __pyx_t_13); - __Pyx_GIVEREF(__pyx_t_14); - PyTuple_SET_ITEM(__pyx_t_1, 12, __pyx_t_14); - __Pyx_GIVEREF(__pyx_t_15); - PyTuple_SET_ITEM(__pyx_t_1, 13, __pyx_t_15); - __Pyx_GIVEREF(__pyx_t_16); - PyTuple_SET_ITEM(__pyx_t_1, 14, __pyx_t_16); - __Pyx_GIVEREF(__pyx_t_17); - PyTuple_SET_ITEM(__pyx_t_1, 15, __pyx_t_17); - __Pyx_GIVEREF(__pyx_t_18); - PyTuple_SET_ITEM(__pyx_t_1, 16, __pyx_t_18); - __Pyx_GIVEREF(__pyx_t_19); - PyTuple_SET_ITEM(__pyx_t_1, 17, __pyx_t_19); - __Pyx_GIVEREF(__pyx_t_20); - PyTuple_SET_ITEM(__pyx_t_1, 18, __pyx_t_20); - __Pyx_GIVEREF(__pyx_t_21); - PyTuple_SET_ITEM(__pyx_t_1, 19, __pyx_t_21); - __Pyx_GIVEREF(__pyx_t_22); - PyTuple_SET_ITEM(__pyx_t_1, 20, __pyx_t_22); - __Pyx_GIVEREF(__pyx_t_23); - PyTuple_SET_ITEM(__pyx_t_1, 21, __pyx_t_23); - __Pyx_GIVEREF(__pyx_t_24); - PyTuple_SET_ITEM(__pyx_t_1, 22, __pyx_t_24); - __Pyx_GIVEREF(__pyx_t_25); - PyTuple_SET_ITEM(__pyx_t_1, 23, __pyx_t_25); - __Pyx_GIVEREF(__pyx_t_26); - PyTuple_SET_ITEM(__pyx_t_1, 24, __pyx_t_26); - __Pyx_GIVEREF(__pyx_t_27); - PyTuple_SET_ITEM(__pyx_t_1, 25, __pyx_t_27); - __Pyx_GIVEREF(__pyx_t_28); - PyTuple_SET_ITEM(__pyx_t_1, 26, __pyx_t_28); - __Pyx_GIVEREF(__pyx_t_29); - PyTuple_SET_ITEM(__pyx_t_1, 27, __pyx_t_29); - __Pyx_GIVEREF(__pyx_t_30); - PyTuple_SET_ITEM(__pyx_t_1, 28, __pyx_t_30); - __Pyx_GIVEREF(__pyx_t_31); - PyTuple_SET_ITEM(__pyx_t_1, 29, __pyx_t_31); - __Pyx_GIVEREF(__pyx_t_32); - PyTuple_SET_ITEM(__pyx_t_1, 30, __pyx_t_32); - __Pyx_GIVEREF(__pyx_t_33); - PyTuple_SET_ITEM(__pyx_t_1, 31, __pyx_t_33); - __Pyx_GIVEREF(__pyx_t_34); - PyTuple_SET_ITEM(__pyx_t_1, 32, __pyx_t_34); - __Pyx_GIVEREF(__pyx_t_35); - PyTuple_SET_ITEM(__pyx_t_1, 33, __pyx_t_35); - __Pyx_GIVEREF(__pyx_t_36); - PyTuple_SET_ITEM(__pyx_t_1, 34, __pyx_t_36); - __Pyx_GIVEREF(__pyx_t_37); - PyTuple_SET_ITEM(__pyx_t_1, 35, __pyx_t_37); - __Pyx_GIVEREF(__pyx_t_38); - PyTuple_SET_ITEM(__pyx_t_1, 36, __pyx_t_38); - __Pyx_GIVEREF(__pyx_t_39); - PyTuple_SET_ITEM(__pyx_t_1, 37, __pyx_t_39); - __Pyx_GIVEREF(__pyx_t_40); - PyTuple_SET_ITEM(__pyx_t_1, 38, __pyx_t_40); - __Pyx_GIVEREF(__pyx_t_41); - PyTuple_SET_ITEM(__pyx_t_1, 39, __pyx_t_41); - __Pyx_GIVEREF(__pyx_t_42); - PyTuple_SET_ITEM(__pyx_t_1, 40, __pyx_t_42); - __Pyx_GIVEREF(__pyx_t_43); - PyTuple_SET_ITEM(__pyx_t_1, 41, __pyx_t_43); - __Pyx_GIVEREF(__pyx_t_44); - PyTuple_SET_ITEM(__pyx_t_1, 42, __pyx_t_44); - __Pyx_GIVEREF(__pyx_t_45); - PyTuple_SET_ITEM(__pyx_t_1, 43, __pyx_t_45); - __Pyx_GIVEREF(__pyx_t_46); - PyTuple_SET_ITEM(__pyx_t_1, 44, __pyx_t_46); - __Pyx_GIVEREF(__pyx_t_47); - PyTuple_SET_ITEM(__pyx_t_1, 45, __pyx_t_47); - __Pyx_GIVEREF(__pyx_t_48); - PyTuple_SET_ITEM(__pyx_t_1, 46, __pyx_t_48); - __Pyx_GIVEREF(__pyx_t_49); - PyTuple_SET_ITEM(__pyx_t_1, 47, __pyx_t_49); - __Pyx_GIVEREF(__pyx_t_50); - PyTuple_SET_ITEM(__pyx_t_1, 48, __pyx_t_50); - __Pyx_GIVEREF(__pyx_t_51); - PyTuple_SET_ITEM(__pyx_t_1, 49, __pyx_t_51); - __Pyx_GIVEREF(__pyx_t_52); - PyTuple_SET_ITEM(__pyx_t_1, 50, __pyx_t_52); - __Pyx_GIVEREF(__pyx_t_53); - PyTuple_SET_ITEM(__pyx_t_1, 51, __pyx_t_53); - __Pyx_GIVEREF(__pyx_t_54); - PyTuple_SET_ITEM(__pyx_t_1, 52, __pyx_t_54); - __Pyx_GIVEREF(__pyx_t_55); - PyTuple_SET_ITEM(__pyx_t_1, 53, __pyx_t_55); - __Pyx_GIVEREF(__pyx_t_56); - PyTuple_SET_ITEM(__pyx_t_1, 54, __pyx_t_56); - __Pyx_GIVEREF(__pyx_t_57); - PyTuple_SET_ITEM(__pyx_t_1, 55, __pyx_t_57); - __Pyx_GIVEREF(__pyx_t_58); - PyTuple_SET_ITEM(__pyx_t_1, 56, __pyx_t_58); - __Pyx_GIVEREF(__pyx_t_59); - PyTuple_SET_ITEM(__pyx_t_1, 57, __pyx_t_59); - __Pyx_GIVEREF(__pyx_t_60); - PyTuple_SET_ITEM(__pyx_t_1, 58, __pyx_t_60); - __Pyx_GIVEREF(__pyx_t_61); - PyTuple_SET_ITEM(__pyx_t_1, 59, __pyx_t_61); - __Pyx_GIVEREF(__pyx_t_62); - PyTuple_SET_ITEM(__pyx_t_1, 60, __pyx_t_62); - __Pyx_GIVEREF(__pyx_t_63); - PyTuple_SET_ITEM(__pyx_t_1, 61, __pyx_t_63); - __Pyx_GIVEREF(__pyx_t_64); - PyTuple_SET_ITEM(__pyx_t_1, 62, __pyx_t_64); - __Pyx_GIVEREF(__pyx_t_65); - PyTuple_SET_ITEM(__pyx_t_1, 63, __pyx_t_65); - __Pyx_GIVEREF(__pyx_t_66); - PyTuple_SET_ITEM(__pyx_t_1, 64, __pyx_t_66); - __Pyx_GIVEREF(__pyx_t_67); - PyTuple_SET_ITEM(__pyx_t_1, 65, __pyx_t_67); - __Pyx_GIVEREF(__pyx_t_68); - PyTuple_SET_ITEM(__pyx_t_1, 66, __pyx_t_68); - __Pyx_GIVEREF(__pyx_t_69); - PyTuple_SET_ITEM(__pyx_t_1, 67, __pyx_t_69); - __Pyx_GIVEREF(__pyx_t_70); - PyTuple_SET_ITEM(__pyx_t_1, 68, __pyx_t_70); - __Pyx_GIVEREF(__pyx_t_71); - PyTuple_SET_ITEM(__pyx_t_1, 69, __pyx_t_71); - __Pyx_GIVEREF(__pyx_t_72); - PyTuple_SET_ITEM(__pyx_t_1, 70, __pyx_t_72); - __Pyx_GIVEREF(__pyx_t_73); - PyTuple_SET_ITEM(__pyx_t_1, 71, __pyx_t_73); - __Pyx_GIVEREF(__pyx_t_74); - PyTuple_SET_ITEM(__pyx_t_1, 72, __pyx_t_74); - __Pyx_GIVEREF(__pyx_t_75); - PyTuple_SET_ITEM(__pyx_t_1, 73, __pyx_t_75); - __Pyx_GIVEREF(__pyx_t_76); - PyTuple_SET_ITEM(__pyx_t_1, 74, __pyx_t_76); - __Pyx_GIVEREF(__pyx_t_77); - PyTuple_SET_ITEM(__pyx_t_1, 75, __pyx_t_77); - __Pyx_GIVEREF(__pyx_t_78); - PyTuple_SET_ITEM(__pyx_t_1, 76, __pyx_t_78); - __pyx_t_2 = 0; - __pyx_t_3 = 0; - __pyx_t_4 = 0; - __pyx_t_5 = 0; - __pyx_t_6 = 0; - __pyx_t_7 = 0; - __pyx_t_8 = 0; - __pyx_t_9 = 0; - __pyx_t_10 = 0; - __pyx_t_11 = 0; - __pyx_t_12 = 0; - __pyx_t_13 = 0; - __pyx_t_14 = 0; - __pyx_t_15 = 0; - __pyx_t_16 = 0; - __pyx_t_17 = 0; - __pyx_t_18 = 0; - __pyx_t_19 = 0; - __pyx_t_20 = 0; - __pyx_t_21 = 0; - __pyx_t_22 = 0; - __pyx_t_23 = 0; - __pyx_t_24 = 0; - __pyx_t_25 = 0; - __pyx_t_26 = 0; - __pyx_t_27 = 0; - __pyx_t_28 = 0; - __pyx_t_29 = 0; - __pyx_t_30 = 0; - __pyx_t_31 = 0; - __pyx_t_32 = 0; - __pyx_t_33 = 0; - __pyx_t_34 = 0; - __pyx_t_35 = 0; - __pyx_t_36 = 0; - __pyx_t_37 = 0; - __pyx_t_38 = 0; - __pyx_t_39 = 0; - __pyx_t_40 = 0; - __pyx_t_41 = 0; - __pyx_t_42 = 0; - __pyx_t_43 = 0; - __pyx_t_44 = 0; - __pyx_t_45 = 0; - __pyx_t_46 = 0; - __pyx_t_47 = 0; - __pyx_t_48 = 0; - __pyx_t_49 = 0; - __pyx_t_50 = 0; - __pyx_t_51 = 0; - __pyx_t_52 = 0; - __pyx_t_53 = 0; - __pyx_t_54 = 0; - __pyx_t_55 = 0; - __pyx_t_56 = 0; - __pyx_t_57 = 0; - __pyx_t_58 = 0; - __pyx_t_59 = 0; - __pyx_t_60 = 0; - __pyx_t_61 = 0; - __pyx_t_62 = 0; - __pyx_t_63 = 0; - __pyx_t_64 = 0; - __pyx_t_65 = 0; - __pyx_t_66 = 0; - __pyx_t_67 = 0; - __pyx_t_68 = 0; - __pyx_t_69 = 0; - __pyx_t_70 = 0; - __pyx_t_71 = 0; - __pyx_t_72 = 0; - __pyx_t_73 = 0; - __pyx_t_74 = 0; - __pyx_t_75 = 0; - __pyx_t_76 = 0; - __pyx_t_77 = 0; - __pyx_t_78 = 0; - __Pyx_XGOTREF(__pyx_v_7aiohttp_12_http_parser_headers); - __Pyx_DECREF_SET(__pyx_v_7aiohttp_12_http_parser_headers, ((PyObject*)__pyx_t_1)); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":57 - * char* PyByteArray_AsString(object) - * - * __all__ = ('HttpRequestParser', 'HttpResponseParser', # <<<<<<<<<<<<<< - * 'RawRequestMessage', 'RawResponseMessage') - * - */ - if (PyDict_SetItem(__pyx_d, __pyx_n_s_all, __pyx_tuple__13) < 0) __PYX_ERR(0, 57, __pyx_L1_error) - - /* "aiohttp/_http_parser.pyx":60 - * 'RawRequestMessage', 'RawResponseMessage') - * - * cdef object URL = _URL # <<<<<<<<<<<<<< - * cdef object URL_build = URL.build - * cdef object CIMultiDict = _CIMultiDict - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_URL_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 60, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(__pyx_v_7aiohttp_12_http_parser_URL); - __Pyx_DECREF_SET(__pyx_v_7aiohttp_12_http_parser_URL, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":61 - * - * cdef object URL = _URL - * cdef object URL_build = URL.build # <<<<<<<<<<<<<< - * cdef object CIMultiDict = _CIMultiDict - * cdef object CIMultiDictProxy = _CIMultiDictProxy - */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_7aiohttp_12_http_parser_URL, __pyx_n_s_build); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 61, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(__pyx_v_7aiohttp_12_http_parser_URL_build); - __Pyx_DECREF_SET(__pyx_v_7aiohttp_12_http_parser_URL_build, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":62 - * cdef object URL = _URL - * cdef object URL_build = URL.build - * cdef object CIMultiDict = _CIMultiDict # <<<<<<<<<<<<<< - * cdef object CIMultiDictProxy = _CIMultiDictProxy - * cdef object HttpVersion = _HttpVersion - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_CIMultiDict_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 62, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(__pyx_v_7aiohttp_12_http_parser_CIMultiDict); - __Pyx_DECREF_SET(__pyx_v_7aiohttp_12_http_parser_CIMultiDict, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":63 - * cdef object URL_build = URL.build - * cdef object CIMultiDict = _CIMultiDict - * cdef object CIMultiDictProxy = _CIMultiDictProxy # <<<<<<<<<<<<<< - * cdef object HttpVersion = _HttpVersion - * cdef object HttpVersion10 = _HttpVersion10 - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_CIMultiDictProxy_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 63, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(__pyx_v_7aiohttp_12_http_parser_CIMultiDictProxy); - __Pyx_DECREF_SET(__pyx_v_7aiohttp_12_http_parser_CIMultiDictProxy, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":64 - * cdef object CIMultiDict = _CIMultiDict - * cdef object CIMultiDictProxy = _CIMultiDictProxy - * cdef object HttpVersion = _HttpVersion # <<<<<<<<<<<<<< - * cdef object HttpVersion10 = _HttpVersion10 - * cdef object HttpVersion11 = _HttpVersion11 - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_HttpVersion_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 64, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(__pyx_v_7aiohttp_12_http_parser_HttpVersion); - __Pyx_DECREF_SET(__pyx_v_7aiohttp_12_http_parser_HttpVersion, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":65 - * cdef object CIMultiDictProxy = _CIMultiDictProxy - * cdef object HttpVersion = _HttpVersion - * cdef object HttpVersion10 = _HttpVersion10 # <<<<<<<<<<<<<< - * cdef object HttpVersion11 = _HttpVersion11 - * cdef object SEC_WEBSOCKET_KEY1 = hdrs.SEC_WEBSOCKET_KEY1 - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_HttpVersion10_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 65, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(__pyx_v_7aiohttp_12_http_parser_HttpVersion10); - __Pyx_DECREF_SET(__pyx_v_7aiohttp_12_http_parser_HttpVersion10, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":66 - * cdef object HttpVersion = _HttpVersion - * cdef object HttpVersion10 = _HttpVersion10 - * cdef object HttpVersion11 = _HttpVersion11 # <<<<<<<<<<<<<< - * cdef object SEC_WEBSOCKET_KEY1 = hdrs.SEC_WEBSOCKET_KEY1 - * cdef object CONTENT_ENCODING = hdrs.CONTENT_ENCODING - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_HttpVersion11_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 66, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(__pyx_v_7aiohttp_12_http_parser_HttpVersion11); - __Pyx_DECREF_SET(__pyx_v_7aiohttp_12_http_parser_HttpVersion11, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":67 - * cdef object HttpVersion10 = _HttpVersion10 - * cdef object HttpVersion11 = _HttpVersion11 - * cdef object SEC_WEBSOCKET_KEY1 = hdrs.SEC_WEBSOCKET_KEY1 # <<<<<<<<<<<<<< - * cdef object CONTENT_ENCODING = hdrs.CONTENT_ENCODING - * cdef object EMPTY_PAYLOAD = _EMPTY_PAYLOAD - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 67, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_78 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_SEC_WEBSOCKET_KEY1); if (unlikely(!__pyx_t_78)) __PYX_ERR(0, 67, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_78); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XGOTREF(__pyx_v_7aiohttp_12_http_parser_SEC_WEBSOCKET_KEY1); - __Pyx_DECREF_SET(__pyx_v_7aiohttp_12_http_parser_SEC_WEBSOCKET_KEY1, __pyx_t_78); - __Pyx_GIVEREF(__pyx_t_78); - __pyx_t_78 = 0; - - /* "aiohttp/_http_parser.pyx":68 - * cdef object HttpVersion11 = _HttpVersion11 - * cdef object SEC_WEBSOCKET_KEY1 = hdrs.SEC_WEBSOCKET_KEY1 - * cdef object CONTENT_ENCODING = hdrs.CONTENT_ENCODING # <<<<<<<<<<<<<< - * cdef object EMPTY_PAYLOAD = _EMPTY_PAYLOAD - * cdef object StreamReader = _StreamReader - */ - __Pyx_GetModuleGlobalName(__pyx_t_78, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_78)) __PYX_ERR(0, 68, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_78); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_78, __pyx_n_s_CONTENT_ENCODING); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 68, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_78); __pyx_t_78 = 0; - __Pyx_XGOTREF(__pyx_v_7aiohttp_12_http_parser_CONTENT_ENCODING); - __Pyx_DECREF_SET(__pyx_v_7aiohttp_12_http_parser_CONTENT_ENCODING, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":69 - * cdef object SEC_WEBSOCKET_KEY1 = hdrs.SEC_WEBSOCKET_KEY1 - * cdef object CONTENT_ENCODING = hdrs.CONTENT_ENCODING - * cdef object EMPTY_PAYLOAD = _EMPTY_PAYLOAD # <<<<<<<<<<<<<< - * cdef object StreamReader = _StreamReader - * cdef object DeflateBuffer = _DeflateBuffer - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_EMPTY_PAYLOAD_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 69, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(__pyx_v_7aiohttp_12_http_parser_EMPTY_PAYLOAD); - __Pyx_DECREF_SET(__pyx_v_7aiohttp_12_http_parser_EMPTY_PAYLOAD, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":70 - * cdef object CONTENT_ENCODING = hdrs.CONTENT_ENCODING - * cdef object EMPTY_PAYLOAD = _EMPTY_PAYLOAD - * cdef object StreamReader = _StreamReader # <<<<<<<<<<<<<< - * cdef object DeflateBuffer = _DeflateBuffer - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_StreamReader_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 70, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(__pyx_v_7aiohttp_12_http_parser_StreamReader); - __Pyx_DECREF_SET(__pyx_v_7aiohttp_12_http_parser_StreamReader, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":71 - * cdef object EMPTY_PAYLOAD = _EMPTY_PAYLOAD - * cdef object StreamReader = _StreamReader - * cdef object DeflateBuffer = _DeflateBuffer # <<<<<<<<<<<<<< - * - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_DeflateBuffer_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 71, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(__pyx_v_7aiohttp_12_http_parser_DeflateBuffer); - __Pyx_DECREF_SET(__pyx_v_7aiohttp_12_http_parser_DeflateBuffer, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":85 - * DEF METHODS_COUNT = 46; - * - * cdef list _http_method = [] # <<<<<<<<<<<<<< - * - * for i in range(METHODS_COUNT): - */ - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 85, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_XGOTREF(__pyx_v_7aiohttp_12_http_parser__http_method); - __Pyx_DECREF_SET(__pyx_v_7aiohttp_12_http_parser__http_method, ((PyObject*)__pyx_t_1)); - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":87 - * cdef list _http_method = [] - * - * for i in range(METHODS_COUNT): # <<<<<<<<<<<<<< - * _http_method.append( - * cparser.llhttp_method_name( i).decode('ascii')) - */ - for (__pyx_t_79 = 0; __pyx_t_79 < 46; __pyx_t_79+=1) { - __pyx_t_1 = __Pyx_PyInt_From_long(__pyx_t_79); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 87, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_i, __pyx_t_1) < 0) __PYX_ERR(0, 87, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":88 - * - * for i in range(METHODS_COUNT): - * _http_method.append( # <<<<<<<<<<<<<< - * cparser.llhttp_method_name( i).decode('ascii')) - * - */ - if (unlikely(__pyx_v_7aiohttp_12_http_parser__http_method == Py_None)) { - PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "append"); - __PYX_ERR(0, 88, __pyx_L1_error) - } - - /* "aiohttp/_http_parser.pyx":89 - * for i in range(METHODS_COUNT): - * _http_method.append( - * cparser.llhttp_method_name( i).decode('ascii')) # <<<<<<<<<<<<<< - * - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_i); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 89, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_80 = ((enum llhttp_method)__Pyx_PyInt_As_enum__llhttp_method(__pyx_t_1)); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 89, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_81 = llhttp_method_name(((llhttp_method_t)__pyx_t_80)); - __pyx_t_1 = __Pyx_decode_c_string(__pyx_t_81, 0, strlen(__pyx_t_81), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 89, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - - /* "aiohttp/_http_parser.pyx":88 - * - * for i in range(METHODS_COUNT): - * _http_method.append( # <<<<<<<<<<<<<< - * cparser.llhttp_method_name( i).decode('ascii')) - * - */ - __pyx_t_82 = __Pyx_PyList_Append(__pyx_v_7aiohttp_12_http_parser__http_method, __pyx_t_1); if (unlikely(__pyx_t_82 == ((int)-1))) __PYX_ERR(0, 88, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } - - /* "(tree fragment)":1 - * def __pyx_unpickle_RawRequestMessage(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * cdef object __pyx_PickleError - * cdef object __pyx_result - */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7aiohttp_12_http_parser_1__pyx_unpickle_RawRequestMessage, NULL, __pyx_n_s_aiohttp__http_parser); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_pyx_unpickle_RawRequestMessage, __pyx_t_1) < 0) __PYX_ERR(1, 1, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "(tree fragment)":11 - * __pyx_unpickle_RawRequestMessage__set_state( __pyx_result, __pyx_state) - * return __pyx_result - * cdef __pyx_unpickle_RawRequestMessage__set_state(RawRequestMessage __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< - * __pyx_result.chunked = __pyx_state[0]; __pyx_result.compression = __pyx_state[1]; __pyx_result.headers = __pyx_state[2]; __pyx_result.method = __pyx_state[3]; __pyx_result.path = __pyx_state[4]; __pyx_result.raw_headers = __pyx_state[5]; __pyx_result.should_close = __pyx_state[6]; __pyx_result.upgrade = __pyx_state[7]; __pyx_result.url = __pyx_state[8]; __pyx_result.version = __pyx_state[9] - * if len(__pyx_state) > 10 and hasattr(__pyx_result, '__dict__'): - */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7aiohttp_12_http_parser_3__pyx_unpickle_RawResponseMessage, NULL, __pyx_n_s_aiohttp__http_parser); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_pyx_unpickle_RawResponseMessag, __pyx_t_1) < 0) __PYX_ERR(1, 1, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":1 - * #cython: language_level=3 # <<<<<<<<<<<<<< - * # - * # Based on https://github.com/MagicStack/httptools - */ - __pyx_t_1 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /*--- Wrapped vars code ---*/ - - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_XDECREF(__pyx_t_11); - __Pyx_XDECREF(__pyx_t_12); - __Pyx_XDECREF(__pyx_t_13); - __Pyx_XDECREF(__pyx_t_14); - __Pyx_XDECREF(__pyx_t_15); - __Pyx_XDECREF(__pyx_t_16); - __Pyx_XDECREF(__pyx_t_17); - __Pyx_XDECREF(__pyx_t_18); - __Pyx_XDECREF(__pyx_t_19); - __Pyx_XDECREF(__pyx_t_20); - __Pyx_XDECREF(__pyx_t_21); - __Pyx_XDECREF(__pyx_t_22); - __Pyx_XDECREF(__pyx_t_23); - __Pyx_XDECREF(__pyx_t_24); - __Pyx_XDECREF(__pyx_t_25); - __Pyx_XDECREF(__pyx_t_26); - __Pyx_XDECREF(__pyx_t_27); - __Pyx_XDECREF(__pyx_t_28); - __Pyx_XDECREF(__pyx_t_29); - __Pyx_XDECREF(__pyx_t_30); - __Pyx_XDECREF(__pyx_t_31); - __Pyx_XDECREF(__pyx_t_32); - __Pyx_XDECREF(__pyx_t_33); - __Pyx_XDECREF(__pyx_t_34); - __Pyx_XDECREF(__pyx_t_35); - __Pyx_XDECREF(__pyx_t_36); - __Pyx_XDECREF(__pyx_t_37); - __Pyx_XDECREF(__pyx_t_38); - __Pyx_XDECREF(__pyx_t_39); - __Pyx_XDECREF(__pyx_t_40); - __Pyx_XDECREF(__pyx_t_41); - __Pyx_XDECREF(__pyx_t_42); - __Pyx_XDECREF(__pyx_t_43); - __Pyx_XDECREF(__pyx_t_44); - __Pyx_XDECREF(__pyx_t_45); - __Pyx_XDECREF(__pyx_t_46); - __Pyx_XDECREF(__pyx_t_47); - __Pyx_XDECREF(__pyx_t_48); - __Pyx_XDECREF(__pyx_t_49); - __Pyx_XDECREF(__pyx_t_50); - __Pyx_XDECREF(__pyx_t_51); - __Pyx_XDECREF(__pyx_t_52); - __Pyx_XDECREF(__pyx_t_53); - __Pyx_XDECREF(__pyx_t_54); - __Pyx_XDECREF(__pyx_t_55); - __Pyx_XDECREF(__pyx_t_56); - __Pyx_XDECREF(__pyx_t_57); - __Pyx_XDECREF(__pyx_t_58); - __Pyx_XDECREF(__pyx_t_59); - __Pyx_XDECREF(__pyx_t_60); - __Pyx_XDECREF(__pyx_t_61); - __Pyx_XDECREF(__pyx_t_62); - __Pyx_XDECREF(__pyx_t_63); - __Pyx_XDECREF(__pyx_t_64); - __Pyx_XDECREF(__pyx_t_65); - __Pyx_XDECREF(__pyx_t_66); - __Pyx_XDECREF(__pyx_t_67); - __Pyx_XDECREF(__pyx_t_68); - __Pyx_XDECREF(__pyx_t_69); - __Pyx_XDECREF(__pyx_t_70); - __Pyx_XDECREF(__pyx_t_71); - __Pyx_XDECREF(__pyx_t_72); - __Pyx_XDECREF(__pyx_t_73); - __Pyx_XDECREF(__pyx_t_74); - __Pyx_XDECREF(__pyx_t_75); - __Pyx_XDECREF(__pyx_t_76); - __Pyx_XDECREF(__pyx_t_77); - __Pyx_XDECREF(__pyx_t_78); - if (__pyx_m) { - if (__pyx_d) { - __Pyx_AddTraceback("init aiohttp._http_parser", __pyx_clineno, __pyx_lineno, __pyx_filename); - } - Py_CLEAR(__pyx_m); - } else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_ImportError, "init aiohttp._http_parser"); - } - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - #if CYTHON_PEP489_MULTI_PHASE_INIT - return (__pyx_m != NULL) ? 0 : -1; - #elif PY_MAJOR_VERSION >= 3 - return __pyx_m; - #else - return; - #endif -} - -/* --- Runtime support code --- */ -/* Refnanny */ -#if CYTHON_REFNANNY -static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { - PyObject *m = NULL, *p = NULL; - void *r = NULL; - m = PyImport_ImportModule(modname); - if (!m) goto end; - p = PyObject_GetAttrString(m, "RefNannyAPI"); - if (!p) goto end; - r = PyLong_AsVoidPtr(p); -end: - Py_XDECREF(p); - Py_XDECREF(m); - return (__Pyx_RefNannyAPIStruct *)r; -} -#endif - -/* PyObjectGetAttrStr */ -#if CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { - PyTypeObject* tp = Py_TYPE(obj); - if (likely(tp->tp_getattro)) - return tp->tp_getattro(obj, attr_name); -#if PY_MAJOR_VERSION < 3 - if (likely(tp->tp_getattr)) - return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); -#endif - return PyObject_GetAttr(obj, attr_name); -} -#endif - -/* GetBuiltinName */ -static PyObject *__Pyx_GetBuiltinName(PyObject *name) { - PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); - if (unlikely(!result)) { - PyErr_Format(PyExc_NameError, -#if PY_MAJOR_VERSION >= 3 - "name '%U' is not defined", name); -#else - "name '%.200s' is not defined", PyString_AS_STRING(name)); -#endif - } - return result; -} - -/* GetItemInt */ -static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { - PyObject *r; - if (!j) return NULL; - r = PyObject_GetItem(o, j); - Py_DECREF(j); - return r; -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, - CYTHON_NCP_UNUSED int wraparound, - CYTHON_NCP_UNUSED int boundscheck) { -#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - Py_ssize_t wrapped_i = i; - if (wraparound & unlikely(i < 0)) { - wrapped_i += PyList_GET_SIZE(o); - } - if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyList_GET_SIZE(o)))) { - PyObject *r = PyList_GET_ITEM(o, wrapped_i); - Py_INCREF(r); - return r; - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -#else - return PySequence_GetItem(o, i); -#endif -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, - CYTHON_NCP_UNUSED int wraparound, - CYTHON_NCP_UNUSED int boundscheck) { -#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - Py_ssize_t wrapped_i = i; - if (wraparound & unlikely(i < 0)) { - wrapped_i += PyTuple_GET_SIZE(o); - } - if ((!boundscheck) || likely(__Pyx_is_valid_index(wrapped_i, PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, wrapped_i); - Py_INCREF(r); - return r; - } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -#else - return PySequence_GetItem(o, i); -#endif -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, - CYTHON_NCP_UNUSED int wraparound, - CYTHON_NCP_UNUSED int boundscheck) { -#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS && CYTHON_USE_TYPE_SLOTS - if (is_list || PyList_CheckExact(o)) { - Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); - if ((!boundscheck) || (likely(__Pyx_is_valid_index(n, PyList_GET_SIZE(o))))) { - PyObject *r = PyList_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } - else if (PyTuple_CheckExact(o)) { - Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); - if ((!boundscheck) || likely(__Pyx_is_valid_index(n, PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } else { - PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; - if (likely(m && m->sq_item)) { - if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { - Py_ssize_t l = m->sq_length(o); - if (likely(l >= 0)) { - i += l; - } else { - if (!PyErr_ExceptionMatches(PyExc_OverflowError)) - return NULL; - PyErr_Clear(); - } - } - return m->sq_item(o, i); - } - } -#else - if (is_list || PySequence_Check(o)) { - return PySequence_GetItem(o, i); - } -#endif - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -} - -/* decode_c_bytes */ -static CYTHON_INLINE PyObject* __Pyx_decode_c_bytes( - const char* cstring, Py_ssize_t length, Py_ssize_t start, Py_ssize_t stop, - const char* encoding, const char* errors, - PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { - if (unlikely((start < 0) | (stop < 0))) { - if (start < 0) { - start += length; - if (start < 0) - start = 0; - } - if (stop < 0) - stop += length; - } - if (stop > length) - stop = length; - if (unlikely(stop <= start)) - return __Pyx_NewRef(__pyx_empty_unicode); - length = stop - start; - cstring += start; - if (decode_func) { - return decode_func(cstring, length, errors); - } else { - return PyUnicode_Decode(cstring, length, encoding, errors); - } -} - -/* RaiseArgTupleInvalid */ -static void __Pyx_RaiseArgtupleInvalid( - const char* func_name, - int exact, - Py_ssize_t num_min, - Py_ssize_t num_max, - Py_ssize_t num_found) -{ - Py_ssize_t num_expected; - const char *more_or_less; - if (num_found < num_min) { - num_expected = num_min; - more_or_less = "at least"; - } else { - num_expected = num_max; - more_or_less = "at most"; - } - if (exact) { - more_or_less = "exactly"; - } - PyErr_Format(PyExc_TypeError, - "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", - func_name, more_or_less, num_expected, - (num_expected == 1) ? "" : "s", num_found); -} - -/* RaiseDoubleKeywords */ -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, - PyObject* kw_name) -{ - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION >= 3 - "%s() got multiple values for keyword argument '%U'", func_name, kw_name); - #else - "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AsString(kw_name)); - #endif -} - -/* ParseKeywords */ -static int __Pyx_ParseOptionalKeywords( - PyObject *kwds, - PyObject **argnames[], - PyObject *kwds2, - PyObject *values[], - Py_ssize_t num_pos_args, - const char* function_name) -{ - PyObject *key = 0, *value = 0; - Py_ssize_t pos = 0; - PyObject*** name; - PyObject*** first_kw_arg = argnames + num_pos_args; - while (PyDict_Next(kwds, &pos, &key, &value)) { - name = first_kw_arg; - while (*name && (**name != key)) name++; - if (*name) { - values[name-argnames] = value; - continue; - } - name = first_kw_arg; - #if PY_MAJOR_VERSION < 3 - if (likely(PyString_Check(key))) { - while (*name) { - if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) - && _PyString_Eq(**name, key)) { - values[name-argnames] = value; - break; - } - name++; - } - if (*name) continue; - else { - PyObject*** argname = argnames; - while (argname != first_kw_arg) { - if ((**argname == key) || ( - (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) - && _PyString_Eq(**argname, key))) { - goto arg_passed_twice; - } - argname++; - } - } - } else - #endif - if (likely(PyUnicode_Check(key))) { - while (*name) { - int cmp = (**name == key) ? 0 : - #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 - (__Pyx_PyUnicode_GET_LENGTH(**name) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : - #endif - PyUnicode_Compare(**name, key); - if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; - if (cmp == 0) { - values[name-argnames] = value; - break; - } - name++; - } - if (*name) continue; - else { - PyObject*** argname = argnames; - while (argname != first_kw_arg) { - int cmp = (**argname == key) ? 0 : - #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 - (__Pyx_PyUnicode_GET_LENGTH(**argname) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : - #endif - PyUnicode_Compare(**argname, key); - if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; - if (cmp == 0) goto arg_passed_twice; - argname++; - } - } - } else - goto invalid_keyword_type; - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; - } - } - return 0; -arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, key); - goto bad; -invalid_keyword_type: - PyErr_Format(PyExc_TypeError, - "%.200s() keywords must be strings", function_name); - goto bad; -invalid_keyword: - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION < 3 - "%.200s() got an unexpected keyword argument '%.200s'", - function_name, PyString_AsString(key)); - #else - "%s() got an unexpected keyword argument '%U'", - function_name, key); - #endif -bad: - return -1; -} - -/* None */ -static CYTHON_INLINE void __Pyx_RaiseClosureNameError(const char *varname) { - PyErr_Format(PyExc_NameError, "free variable '%s' referenced before assignment in enclosing scope", varname); -} - -/* RaiseTooManyValuesToUnpack */ -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { - PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); -} - -/* RaiseNeedMoreValuesToUnpack */ -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { - PyErr_Format(PyExc_ValueError, - "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", - index, (index == 1) ? "" : "s"); -} - -/* IterFinish */ -static CYTHON_INLINE int __Pyx_IterFinish(void) { -#if CYTHON_FAST_THREAD_STATE - PyThreadState *tstate = __Pyx_PyThreadState_Current; - PyObject* exc_type = tstate->curexc_type; - if (unlikely(exc_type)) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) { - PyObject *exc_value, *exc_tb; - exc_value = tstate->curexc_value; - exc_tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; - Py_DECREF(exc_type); - Py_XDECREF(exc_value); - Py_XDECREF(exc_tb); - return 0; - } else { - return -1; - } - } - return 0; -#else - if (unlikely(PyErr_Occurred())) { - if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { - PyErr_Clear(); - return 0; - } else { - return -1; - } - } - return 0; -#endif -} - -/* UnpackItemEndCheck */ -static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { - if (unlikely(retval)) { - Py_DECREF(retval); - __Pyx_RaiseTooManyValuesError(expected); - return -1; - } else { - return __Pyx_IterFinish(); - } - return 0; -} - -/* KeywordStringCheck */ -static int __Pyx_CheckKeywordStrings( - PyObject *kwdict, - const char* function_name, - int kw_allowed) -{ - PyObject* key = 0; - Py_ssize_t pos = 0; -#if CYTHON_COMPILING_IN_PYPY - if (!kw_allowed && PyDict_Next(kwdict, &pos, &key, 0)) - goto invalid_keyword; - return 1; -#else - while (PyDict_Next(kwdict, &pos, &key, 0)) { - #if PY_MAJOR_VERSION < 3 - if (unlikely(!PyString_Check(key))) - #endif - if (unlikely(!PyUnicode_Check(key))) - goto invalid_keyword_type; - } - if ((!kw_allowed) && unlikely(key)) - goto invalid_keyword; - return 1; -invalid_keyword_type: - PyErr_Format(PyExc_TypeError, - "%.200s() keywords must be strings", function_name); - return 0; -#endif -invalid_keyword: - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION < 3 - "%.200s() got an unexpected keyword argument '%.200s'", - function_name, PyString_AsString(key)); - #else - "%s() got an unexpected keyword argument '%U'", - function_name, key); - #endif - return 0; -} - -/* ExtTypeTest */ -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { - if (unlikely(!type)) { - PyErr_SetString(PyExc_SystemError, "Missing type object"); - return 0; - } - if (likely(__Pyx_TypeCheck(obj, type))) - return 1; - PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", - Py_TYPE(obj)->tp_name, type->tp_name); - return 0; -} - -/* DictGetItem */ -#if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY -static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) { - PyObject *value; - value = PyDict_GetItemWithError(d, key); - if (unlikely(!value)) { - if (!PyErr_Occurred()) { - if (unlikely(PyTuple_Check(key))) { - PyObject* args = PyTuple_Pack(1, key); - if (likely(args)) { - PyErr_SetObject(PyExc_KeyError, args); - Py_DECREF(args); - } - } else { - PyErr_SetObject(PyExc_KeyError, key); - } - } - return NULL; - } - Py_INCREF(value); - return value; -} -#endif - -/* PyErrExceptionMatches */ -#if CYTHON_FAST_THREAD_STATE -static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { - Py_ssize_t i, n; - n = PyTuple_GET_SIZE(tuple); -#if PY_MAJOR_VERSION >= 3 - for (i=0; icurexc_type; - if (exc_type == err) return 1; - if (unlikely(!exc_type)) return 0; - if (unlikely(PyTuple_Check(err))) - return __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); - return __Pyx_PyErr_GivenExceptionMatches(exc_type, err); -} -#endif - -/* PyErrFetchRestore */ -#if CYTHON_FAST_THREAD_STATE -static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - tmp_type = tstate->curexc_type; - tmp_value = tstate->curexc_value; - tmp_tb = tstate->curexc_traceback; - tstate->curexc_type = type; - tstate->curexc_value = value; - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -} -static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { - *type = tstate->curexc_type; - *value = tstate->curexc_value; - *tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; -} -#endif - -/* GetAttr */ -static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { -#if CYTHON_USE_TYPE_SLOTS -#if PY_MAJOR_VERSION >= 3 - if (likely(PyUnicode_Check(n))) -#else - if (likely(PyString_Check(n))) -#endif - return __Pyx_PyObject_GetAttrStr(o, n); -#endif - return PyObject_GetAttr(o, n); -} - -/* GetAttr3 */ -static PyObject *__Pyx_GetAttr3Default(PyObject *d) { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - if (unlikely(!__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) - return NULL; - __Pyx_PyErr_Clear(); - Py_INCREF(d); - return d; -} -static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) { - PyObject *r = __Pyx_GetAttr(o, n); - return (likely(r)) ? r : __Pyx_GetAttr3Default(d); -} - -/* PyDictVersioning */ -#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) { - PyObject *dict = Py_TYPE(obj)->tp_dict; - return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0; -} -static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) { - PyObject **dictptr = NULL; - Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset; - if (offset) { -#if CYTHON_COMPILING_IN_CPYTHON - dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj); -#else - dictptr = _PyObject_GetDictPtr(obj); -#endif - } - return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0; -} -static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) { - PyObject *dict = Py_TYPE(obj)->tp_dict; - if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict))) - return 0; - return obj_dict_version == __Pyx_get_object_dict_version(obj); -} -#endif - -/* GetModuleGlobalName */ -#if CYTHON_USE_DICT_VERSIONS -static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) -#else -static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) -#endif -{ - PyObject *result; -#if !CYTHON_AVOID_BORROWED_REFS -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 - result = _PyDict_GetItem_KnownHash(__pyx_d, name, ((PyASCIIObject *) name)->hash); - __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) - if (likely(result)) { - return __Pyx_NewRef(result); - } else if (unlikely(PyErr_Occurred())) { - return NULL; - } -#else - result = PyDict_GetItem(__pyx_d, name); - __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) - if (likely(result)) { - return __Pyx_NewRef(result); - } -#endif -#else - result = PyObject_GetItem(__pyx_d, name); - __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) - if (likely(result)) { - return __Pyx_NewRef(result); - } - PyErr_Clear(); -#endif - return __Pyx_GetBuiltinName(name); -} - -/* PyFunctionFastCall */ -#if CYTHON_FAST_PYCALL -static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na, - PyObject *globals) { - PyFrameObject *f; - PyThreadState *tstate = __Pyx_PyThreadState_Current; - PyObject **fastlocals; - Py_ssize_t i; - PyObject *result; - assert(globals != NULL); - /* XXX Perhaps we should create a specialized - PyFrame_New() that doesn't take locals, but does - take builtins without sanity checking them. - */ - assert(tstate != NULL); - f = PyFrame_New(tstate, co, globals, NULL); - if (f == NULL) { - return NULL; - } - fastlocals = __Pyx_PyFrame_GetLocalsplus(f); - for (i = 0; i < na; i++) { - Py_INCREF(*args); - fastlocals[i] = *args++; - } - result = PyEval_EvalFrameEx(f,0); - ++tstate->recursion_depth; - Py_DECREF(f); - --tstate->recursion_depth; - return result; -} -#if 1 || PY_VERSION_HEX < 0x030600B1 -static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) { - PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); - PyObject *globals = PyFunction_GET_GLOBALS(func); - PyObject *argdefs = PyFunction_GET_DEFAULTS(func); - PyObject *closure; -#if PY_MAJOR_VERSION >= 3 - PyObject *kwdefs; -#endif - PyObject *kwtuple, **k; - PyObject **d; - Py_ssize_t nd; - Py_ssize_t nk; - PyObject *result; - assert(kwargs == NULL || PyDict_Check(kwargs)); - nk = kwargs ? PyDict_Size(kwargs) : 0; - if (Py_EnterRecursiveCall((char*)" while calling a Python object")) { - return NULL; - } - if ( -#if PY_MAJOR_VERSION >= 3 - co->co_kwonlyargcount == 0 && -#endif - likely(kwargs == NULL || nk == 0) && - co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { - if (argdefs == NULL && co->co_argcount == nargs) { - result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals); - goto done; - } - else if (nargs == 0 && argdefs != NULL - && co->co_argcount == Py_SIZE(argdefs)) { - /* function called with no arguments, but all parameters have - a default value: use default values as arguments .*/ - args = &PyTuple_GET_ITEM(argdefs, 0); - result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals); - goto done; - } - } - if (kwargs != NULL) { - Py_ssize_t pos, i; - kwtuple = PyTuple_New(2 * nk); - if (kwtuple == NULL) { - result = NULL; - goto done; - } - k = &PyTuple_GET_ITEM(kwtuple, 0); - pos = i = 0; - while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) { - Py_INCREF(k[i]); - Py_INCREF(k[i+1]); - i += 2; - } - nk = i / 2; - } - else { - kwtuple = NULL; - k = NULL; - } - closure = PyFunction_GET_CLOSURE(func); -#if PY_MAJOR_VERSION >= 3 - kwdefs = PyFunction_GET_KW_DEFAULTS(func); -#endif - if (argdefs != NULL) { - d = &PyTuple_GET_ITEM(argdefs, 0); - nd = Py_SIZE(argdefs); - } - else { - d = NULL; - nd = 0; - } -#if PY_MAJOR_VERSION >= 3 - result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL, - args, (int)nargs, - k, (int)nk, - d, (int)nd, kwdefs, closure); -#else - result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL, - args, (int)nargs, - k, (int)nk, - d, (int)nd, closure); -#endif - Py_XDECREF(kwtuple); -done: - Py_LeaveRecursiveCall(); - return result; -} -#endif -#endif - -/* PyObjectCall */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { - PyObject *result; - ternaryfunc call = Py_TYPE(func)->tp_call; - if (unlikely(!call)) - return PyObject_Call(func, arg, kw); - if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) - return NULL; - result = (*call)(func, arg, kw); - Py_LeaveRecursiveCall(); - if (unlikely(!result) && unlikely(!PyErr_Occurred())) { - PyErr_SetString( - PyExc_SystemError, - "NULL result without error in PyObject_Call"); - } - return result; -} -#endif - -/* PyObjectCallMethO */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { - PyObject *self, *result; - PyCFunction cfunc; - cfunc = PyCFunction_GET_FUNCTION(func); - self = PyCFunction_GET_SELF(func); - if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) - return NULL; - result = cfunc(self, arg); - Py_LeaveRecursiveCall(); - if (unlikely(!result) && unlikely(!PyErr_Occurred())) { - PyErr_SetString( - PyExc_SystemError, - "NULL result without error in PyObject_Call"); - } - return result; -} -#endif - -/* PyObjectCallNoArg */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { -#if CYTHON_FAST_PYCALL - if (PyFunction_Check(func)) { - return __Pyx_PyFunction_FastCall(func, NULL, 0); - } -#endif -#ifdef __Pyx_CyFunction_USED - if (likely(PyCFunction_Check(func) || __Pyx_CyFunction_Check(func))) -#else - if (likely(PyCFunction_Check(func))) -#endif - { - if (likely(PyCFunction_GET_FLAGS(func) & METH_NOARGS)) { - return __Pyx_PyObject_CallMethO(func, NULL); - } - } - return __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL); -} -#endif - -/* PyCFunctionFastCall */ -#if CYTHON_FAST_PYCCALL -static CYTHON_INLINE PyObject * __Pyx_PyCFunction_FastCall(PyObject *func_obj, PyObject **args, Py_ssize_t nargs) { - PyCFunctionObject *func = (PyCFunctionObject*)func_obj; - PyCFunction meth = PyCFunction_GET_FUNCTION(func); - PyObject *self = PyCFunction_GET_SELF(func); - int flags = PyCFunction_GET_FLAGS(func); - assert(PyCFunction_Check(func)); - assert(METH_FASTCALL == (flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))); - assert(nargs >= 0); - assert(nargs == 0 || args != NULL); - /* _PyCFunction_FastCallDict() must not be called with an exception set, - because it may clear it (directly or indirectly) and so the - caller loses its exception */ - assert(!PyErr_Occurred()); - if ((PY_VERSION_HEX < 0x030700A0) || unlikely(flags & METH_KEYWORDS)) { - return (*((__Pyx_PyCFunctionFastWithKeywords)(void*)meth)) (self, args, nargs, NULL); - } else { - return (*((__Pyx_PyCFunctionFast)(void*)meth)) (self, args, nargs); - } -} -#endif - -/* PyObjectCallOneArg */ -#if CYTHON_COMPILING_IN_CPYTHON -static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { - PyObject *result; - PyObject *args = PyTuple_New(1); - if (unlikely(!args)) return NULL; - Py_INCREF(arg); - PyTuple_SET_ITEM(args, 0, arg); - result = __Pyx_PyObject_Call(func, args, NULL); - Py_DECREF(args); - return result; -} -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { -#if CYTHON_FAST_PYCALL - if (PyFunction_Check(func)) { - return __Pyx_PyFunction_FastCall(func, &arg, 1); - } -#endif - if (likely(PyCFunction_Check(func))) { - if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { - return __Pyx_PyObject_CallMethO(func, arg); -#if CYTHON_FAST_PYCCALL - } else if (__Pyx_PyFastCFunction_Check(func)) { - return __Pyx_PyCFunction_FastCall(func, &arg, 1); -#endif - } - } - return __Pyx__PyObject_CallOneArg(func, arg); -} -#else -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { - PyObject *result; - PyObject *args = PyTuple_Pack(1, arg); - if (unlikely(!args)) return NULL; - result = __Pyx_PyObject_Call(func, args, NULL); - Py_DECREF(args); - return result; -} -#endif - -/* PyObjectCall2Args */ -static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2) { - PyObject *args, *result = NULL; - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(function)) { - PyObject *args[2] = {arg1, arg2}; - return __Pyx_PyFunction_FastCall(function, args, 2); - } - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(function)) { - PyObject *args[2] = {arg1, arg2}; - return __Pyx_PyCFunction_FastCall(function, args, 2); - } - #endif - args = PyTuple_New(2); - if (unlikely(!args)) goto done; - Py_INCREF(arg1); - PyTuple_SET_ITEM(args, 0, arg1); - Py_INCREF(arg2); - PyTuple_SET_ITEM(args, 1, arg2); - Py_INCREF(function); - result = __Pyx_PyObject_Call(function, args, NULL); - Py_DECREF(args); - Py_DECREF(function); -done: - return result; -} - -/* RaiseException */ -#if PY_MAJOR_VERSION < 3 -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, - CYTHON_UNUSED PyObject *cause) { - __Pyx_PyThreadState_declare - Py_XINCREF(type); - if (!value || value == Py_None) - value = NULL; - else - Py_INCREF(value); - if (!tb || tb == Py_None) - tb = NULL; - else { - Py_INCREF(tb); - if (!PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - } - if (PyType_Check(type)) { -#if CYTHON_COMPILING_IN_PYPY - if (!value) { - Py_INCREF(Py_None); - value = Py_None; - } -#endif - PyErr_NormalizeException(&type, &value, &tb); - } else { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto raise_error; - } - value = type; - type = (PyObject*) Py_TYPE(type); - Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; - } - } - __Pyx_PyThreadState_assign - __Pyx_ErrRestore(type, value, tb); - return; -raise_error: - Py_XDECREF(value); - Py_XDECREF(type); - Py_XDECREF(tb); - return; -} -#else -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - PyObject* owned_instance = NULL; - if (tb == Py_None) { - tb = 0; - } else if (tb && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto bad; - } - if (value == Py_None) - value = 0; - if (PyExceptionInstance_Check(type)) { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto bad; - } - value = type; - type = (PyObject*) Py_TYPE(value); - } else if (PyExceptionClass_Check(type)) { - PyObject *instance_class = NULL; - if (value && PyExceptionInstance_Check(value)) { - instance_class = (PyObject*) Py_TYPE(value); - if (instance_class != type) { - int is_subclass = PyObject_IsSubclass(instance_class, type); - if (!is_subclass) { - instance_class = NULL; - } else if (unlikely(is_subclass == -1)) { - goto bad; - } else { - type = instance_class; - } - } - } - if (!instance_class) { - PyObject *args; - if (!value) - args = PyTuple_New(0); - else if (PyTuple_Check(value)) { - Py_INCREF(value); - args = value; - } else - args = PyTuple_Pack(1, value); - if (!args) - goto bad; - owned_instance = PyObject_Call(type, args, NULL); - Py_DECREF(args); - if (!owned_instance) - goto bad; - value = owned_instance; - if (!PyExceptionInstance_Check(value)) { - PyErr_Format(PyExc_TypeError, - "calling %R should have returned an instance of " - "BaseException, not %R", - type, Py_TYPE(value)); - goto bad; - } - } - } else { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto bad; - } - if (cause) { - PyObject *fixed_cause; - if (cause == Py_None) { - fixed_cause = NULL; - } else if (PyExceptionClass_Check(cause)) { - fixed_cause = PyObject_CallObject(cause, NULL); - if (fixed_cause == NULL) - goto bad; - } else if (PyExceptionInstance_Check(cause)) { - fixed_cause = cause; - Py_INCREF(fixed_cause); - } else { - PyErr_SetString(PyExc_TypeError, - "exception causes must derive from " - "BaseException"); - goto bad; - } - PyException_SetCause(value, fixed_cause); - } - PyErr_SetObject(type, value); - if (tb) { -#if CYTHON_COMPILING_IN_PYPY - PyObject *tmp_type, *tmp_value, *tmp_tb; - PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); - Py_INCREF(tb); - PyErr_Restore(tmp_type, tmp_value, tb); - Py_XDECREF(tmp_tb); -#else - PyThreadState *tstate = __Pyx_PyThreadState_Current; - PyObject* tmp_tb = tstate->curexc_traceback; - if (tb != tmp_tb) { - Py_INCREF(tb); - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_tb); - } -#endif - } -bad: - Py_XDECREF(owned_instance); - return; -} -#endif - -/* BytesEquals */ -static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { -#if CYTHON_COMPILING_IN_PYPY - return PyObject_RichCompareBool(s1, s2, equals); -#else - if (s1 == s2) { - return (equals == Py_EQ); - } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { - const char *ps1, *ps2; - Py_ssize_t length = PyBytes_GET_SIZE(s1); - if (length != PyBytes_GET_SIZE(s2)) - return (equals == Py_NE); - ps1 = PyBytes_AS_STRING(s1); - ps2 = PyBytes_AS_STRING(s2); - if (ps1[0] != ps2[0]) { - return (equals == Py_NE); - } else if (length == 1) { - return (equals == Py_EQ); - } else { - int result; -#if CYTHON_USE_UNICODE_INTERNALS - Py_hash_t hash1, hash2; - hash1 = ((PyBytesObject*)s1)->ob_shash; - hash2 = ((PyBytesObject*)s2)->ob_shash; - if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { - return (equals == Py_NE); - } -#endif - result = memcmp(ps1, ps2, (size_t)length); - return (equals == Py_EQ) ? (result == 0) : (result != 0); - } - } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { - return (equals == Py_NE); - } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { - return (equals == Py_NE); - } else { - int result; - PyObject* py_result = PyObject_RichCompare(s1, s2, equals); - if (!py_result) - return -1; - result = __Pyx_PyObject_IsTrue(py_result); - Py_DECREF(py_result); - return result; - } -#endif -} - -/* UnicodeEquals */ -static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { -#if CYTHON_COMPILING_IN_PYPY - return PyObject_RichCompareBool(s1, s2, equals); -#else -#if PY_MAJOR_VERSION < 3 - PyObject* owned_ref = NULL; -#endif - int s1_is_unicode, s2_is_unicode; - if (s1 == s2) { - goto return_eq; - } - s1_is_unicode = PyUnicode_CheckExact(s1); - s2_is_unicode = PyUnicode_CheckExact(s2); -#if PY_MAJOR_VERSION < 3 - if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) { - owned_ref = PyUnicode_FromObject(s2); - if (unlikely(!owned_ref)) - return -1; - s2 = owned_ref; - s2_is_unicode = 1; - } else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) { - owned_ref = PyUnicode_FromObject(s1); - if (unlikely(!owned_ref)) - return -1; - s1 = owned_ref; - s1_is_unicode = 1; - } else if (((!s2_is_unicode) & (!s1_is_unicode))) { - return __Pyx_PyBytes_Equals(s1, s2, equals); - } -#endif - if (s1_is_unicode & s2_is_unicode) { - Py_ssize_t length; - int kind; - void *data1, *data2; - if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) - return -1; - length = __Pyx_PyUnicode_GET_LENGTH(s1); - if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) { - goto return_ne; - } -#if CYTHON_USE_UNICODE_INTERNALS - { - Py_hash_t hash1, hash2; - #if CYTHON_PEP393_ENABLED - hash1 = ((PyASCIIObject*)s1)->hash; - hash2 = ((PyASCIIObject*)s2)->hash; - #else - hash1 = ((PyUnicodeObject*)s1)->hash; - hash2 = ((PyUnicodeObject*)s2)->hash; - #endif - if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { - goto return_ne; - } - } -#endif - kind = __Pyx_PyUnicode_KIND(s1); - if (kind != __Pyx_PyUnicode_KIND(s2)) { - goto return_ne; - } - data1 = __Pyx_PyUnicode_DATA(s1); - data2 = __Pyx_PyUnicode_DATA(s2); - if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { - goto return_ne; - } else if (length == 1) { - goto return_eq; - } else { - int result = memcmp(data1, data2, (size_t)(length * kind)); - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(owned_ref); - #endif - return (equals == Py_EQ) ? (result == 0) : (result != 0); - } - } else if ((s1 == Py_None) & s2_is_unicode) { - goto return_ne; - } else if ((s2 == Py_None) & s1_is_unicode) { - goto return_ne; - } else { - int result; - PyObject* py_result = PyObject_RichCompare(s1, s2, equals); - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(owned_ref); - #endif - if (!py_result) - return -1; - result = __Pyx_PyObject_IsTrue(py_result); - Py_DECREF(py_result); - return result; - } -return_eq: - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(owned_ref); - #endif - return (equals == Py_EQ); -return_ne: - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(owned_ref); - #endif - return (equals == Py_NE); -#endif -} - -/* SliceObject */ -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice(PyObject* obj, - Py_ssize_t cstart, Py_ssize_t cstop, - PyObject** _py_start, PyObject** _py_stop, PyObject** _py_slice, - int has_cstart, int has_cstop, CYTHON_UNUSED int wraparound) { -#if CYTHON_USE_TYPE_SLOTS - PyMappingMethods* mp; -#if PY_MAJOR_VERSION < 3 - PySequenceMethods* ms = Py_TYPE(obj)->tp_as_sequence; - if (likely(ms && ms->sq_slice)) { - if (!has_cstart) { - if (_py_start && (*_py_start != Py_None)) { - cstart = __Pyx_PyIndex_AsSsize_t(*_py_start); - if ((cstart == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; - } else - cstart = 0; - } - if (!has_cstop) { - if (_py_stop && (*_py_stop != Py_None)) { - cstop = __Pyx_PyIndex_AsSsize_t(*_py_stop); - if ((cstop == (Py_ssize_t)-1) && PyErr_Occurred()) goto bad; - } else - cstop = PY_SSIZE_T_MAX; - } - if (wraparound && unlikely((cstart < 0) | (cstop < 0)) && likely(ms->sq_length)) { - Py_ssize_t l = ms->sq_length(obj); - if (likely(l >= 0)) { - if (cstop < 0) { - cstop += l; - if (cstop < 0) cstop = 0; - } - if (cstart < 0) { - cstart += l; - if (cstart < 0) cstart = 0; - } - } else { - if (!PyErr_ExceptionMatches(PyExc_OverflowError)) - goto bad; - PyErr_Clear(); - } - } - return ms->sq_slice(obj, cstart, cstop); - } -#endif - mp = Py_TYPE(obj)->tp_as_mapping; - if (likely(mp && mp->mp_subscript)) -#endif - { - PyObject* result; - PyObject *py_slice, *py_start, *py_stop; - if (_py_slice) { - py_slice = *_py_slice; - } else { - PyObject* owned_start = NULL; - PyObject* owned_stop = NULL; - if (_py_start) { - py_start = *_py_start; - } else { - if (has_cstart) { - owned_start = py_start = PyInt_FromSsize_t(cstart); - if (unlikely(!py_start)) goto bad; - } else - py_start = Py_None; - } - if (_py_stop) { - py_stop = *_py_stop; - } else { - if (has_cstop) { - owned_stop = py_stop = PyInt_FromSsize_t(cstop); - if (unlikely(!py_stop)) { - Py_XDECREF(owned_start); - goto bad; - } - } else - py_stop = Py_None; - } - py_slice = PySlice_New(py_start, py_stop, Py_None); - Py_XDECREF(owned_start); - Py_XDECREF(owned_stop); - if (unlikely(!py_slice)) goto bad; - } -#if CYTHON_USE_TYPE_SLOTS - result = mp->mp_subscript(obj, py_slice); -#else - result = PyObject_GetItem(obj, py_slice); -#endif - if (!_py_slice) { - Py_DECREF(py_slice); - } - return result; - } - PyErr_Format(PyExc_TypeError, - "'%.200s' object is unsliceable", Py_TYPE(obj)->tp_name); -bad: - return NULL; -} - -/* PyUnicode_Substring */ -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_Substring( - PyObject* text, Py_ssize_t start, Py_ssize_t stop) { - Py_ssize_t length; - if (unlikely(__Pyx_PyUnicode_READY(text) == -1)) return NULL; - length = __Pyx_PyUnicode_GET_LENGTH(text); - if (start < 0) { - start += length; - if (start < 0) - start = 0; - } - if (stop < 0) - stop += length; - else if (stop > length) - stop = length; - if (stop <= start) - return __Pyx_NewRef(__pyx_empty_unicode); -#if CYTHON_PEP393_ENABLED - return PyUnicode_FromKindAndData(PyUnicode_KIND(text), - PyUnicode_1BYTE_DATA(text) + start*PyUnicode_KIND(text), stop-start); -#else - return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(text)+start, stop-start); -#endif -} - -/* GetException */ -#if CYTHON_FAST_THREAD_STATE -static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) -#else -static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) -#endif -{ - PyObject *local_type, *local_value, *local_tb; -#if CYTHON_FAST_THREAD_STATE - PyObject *tmp_type, *tmp_value, *tmp_tb; - local_type = tstate->curexc_type; - local_value = tstate->curexc_value; - local_tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; -#else - PyErr_Fetch(&local_type, &local_value, &local_tb); -#endif - PyErr_NormalizeException(&local_type, &local_value, &local_tb); -#if CYTHON_FAST_THREAD_STATE - if (unlikely(tstate->curexc_type)) -#else - if (unlikely(PyErr_Occurred())) -#endif - goto bad; - #if PY_MAJOR_VERSION >= 3 - if (local_tb) { - if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) - goto bad; - } - #endif - Py_XINCREF(local_tb); - Py_XINCREF(local_type); - Py_XINCREF(local_value); - *type = local_type; - *value = local_value; - *tb = local_tb; -#if CYTHON_FAST_THREAD_STATE - #if CYTHON_USE_EXC_INFO_STACK - { - _PyErr_StackItem *exc_info = tstate->exc_info; - tmp_type = exc_info->exc_type; - tmp_value = exc_info->exc_value; - tmp_tb = exc_info->exc_traceback; - exc_info->exc_type = local_type; - exc_info->exc_value = local_value; - exc_info->exc_traceback = local_tb; - } - #else - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - tstate->exc_type = local_type; - tstate->exc_value = local_value; - tstate->exc_traceback = local_tb; - #endif - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -#else - PyErr_SetExcInfo(local_type, local_value, local_tb); -#endif - return 0; -bad: - *type = 0; - *value = 0; - *tb = 0; - Py_XDECREF(local_type); - Py_XDECREF(local_value); - Py_XDECREF(local_tb); - return -1; -} - -/* SwapException */ -#if CYTHON_FAST_THREAD_STATE -static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - #if CYTHON_USE_EXC_INFO_STACK - _PyErr_StackItem *exc_info = tstate->exc_info; - tmp_type = exc_info->exc_type; - tmp_value = exc_info->exc_value; - tmp_tb = exc_info->exc_traceback; - exc_info->exc_type = *type; - exc_info->exc_value = *value; - exc_info->exc_traceback = *tb; - #else - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - tstate->exc_type = *type; - tstate->exc_value = *value; - tstate->exc_traceback = *tb; - #endif - *type = tmp_type; - *value = tmp_value; - *tb = tmp_tb; -} -#else -static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); - PyErr_SetExcInfo(*type, *value, *tb); - *type = tmp_type; - *value = tmp_value; - *tb = tmp_tb; -} -#endif - -/* GetTopmostException */ -#if CYTHON_USE_EXC_INFO_STACK -static _PyErr_StackItem * -__Pyx_PyErr_GetTopmostException(PyThreadState *tstate) -{ - _PyErr_StackItem *exc_info = tstate->exc_info; - while ((exc_info->exc_type == NULL || exc_info->exc_type == Py_None) && - exc_info->previous_item != NULL) - { - exc_info = exc_info->previous_item; - } - return exc_info; -} -#endif - -/* SaveResetException */ -#if CYTHON_FAST_THREAD_STATE -static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { - #if CYTHON_USE_EXC_INFO_STACK - _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); - *type = exc_info->exc_type; - *value = exc_info->exc_value; - *tb = exc_info->exc_traceback; - #else - *type = tstate->exc_type; - *value = tstate->exc_value; - *tb = tstate->exc_traceback; - #endif - Py_XINCREF(*type); - Py_XINCREF(*value); - Py_XINCREF(*tb); -} -static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - #if CYTHON_USE_EXC_INFO_STACK - _PyErr_StackItem *exc_info = tstate->exc_info; - tmp_type = exc_info->exc_type; - tmp_value = exc_info->exc_value; - tmp_tb = exc_info->exc_traceback; - exc_info->exc_type = type; - exc_info->exc_value = value; - exc_info->exc_traceback = tb; - #else - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - tstate->exc_type = type; - tstate->exc_value = value; - tstate->exc_traceback = tb; - #endif - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -} -#endif - -/* Import */ -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { - PyObject *empty_list = 0; - PyObject *module = 0; - PyObject *global_dict = 0; - PyObject *empty_dict = 0; - PyObject *list; - #if PY_MAJOR_VERSION < 3 - PyObject *py_import; - py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); - if (!py_import) - goto bad; - #endif - if (from_list) - list = from_list; - else { - empty_list = PyList_New(0); - if (!empty_list) - goto bad; - list = empty_list; - } - global_dict = PyModule_GetDict(__pyx_m); - if (!global_dict) - goto bad; - empty_dict = PyDict_New(); - if (!empty_dict) - goto bad; - { - #if PY_MAJOR_VERSION >= 3 - if (level == -1) { - if ((1) && (strchr(__Pyx_MODULE_NAME, '.'))) { - module = PyImport_ImportModuleLevelObject( - name, global_dict, empty_dict, list, 1); - if (!module) { - if (!PyErr_ExceptionMatches(PyExc_ImportError)) - goto bad; - PyErr_Clear(); - } - } - level = 0; - } - #endif - if (!module) { - #if PY_MAJOR_VERSION < 3 - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, (PyObject *)NULL); - Py_DECREF(py_level); - #else - module = PyImport_ImportModuleLevelObject( - name, global_dict, empty_dict, list, level); - #endif - } - } -bad: - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(py_import); - #endif - Py_XDECREF(empty_list); - Py_XDECREF(empty_dict); - return module; -} - -/* ImportFrom */ -static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { - PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); - if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Format(PyExc_ImportError, - #if PY_MAJOR_VERSION < 3 - "cannot import name %.230s", PyString_AS_STRING(name)); - #else - "cannot import name %S", name); - #endif - } - return value; -} - -/* HasAttr */ -static CYTHON_INLINE int __Pyx_HasAttr(PyObject *o, PyObject *n) { - PyObject *r; - if (unlikely(!__Pyx_PyBaseString_Check(n))) { - PyErr_SetString(PyExc_TypeError, - "hasattr(): attribute name must be string"); - return -1; - } - r = __Pyx_GetAttr(o, n); - if (unlikely(!r)) { - PyErr_Clear(); - return 0; - } else { - Py_DECREF(r); - return 1; - } -} - -/* PyObject_GenericGetAttrNoDict */ -#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 -static PyObject *__Pyx_RaiseGenericGetAttributeError(PyTypeObject *tp, PyObject *attr_name) { - PyErr_Format(PyExc_AttributeError, -#if PY_MAJOR_VERSION >= 3 - "'%.50s' object has no attribute '%U'", - tp->tp_name, attr_name); -#else - "'%.50s' object has no attribute '%.400s'", - tp->tp_name, PyString_AS_STRING(attr_name)); -#endif - return NULL; -} -static CYTHON_INLINE PyObject* __Pyx_PyObject_GenericGetAttrNoDict(PyObject* obj, PyObject* attr_name) { - PyObject *descr; - PyTypeObject *tp = Py_TYPE(obj); - if (unlikely(!PyString_Check(attr_name))) { - return PyObject_GenericGetAttr(obj, attr_name); - } - assert(!tp->tp_dictoffset); - descr = _PyType_Lookup(tp, attr_name); - if (unlikely(!descr)) { - return __Pyx_RaiseGenericGetAttributeError(tp, attr_name); - } - Py_INCREF(descr); - #if PY_MAJOR_VERSION < 3 - if (likely(PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_HAVE_CLASS))) - #endif - { - descrgetfunc f = Py_TYPE(descr)->tp_descr_get; - if (unlikely(f)) { - PyObject *res = f(descr, obj, (PyObject *)tp); - Py_DECREF(descr); - return res; - } - } - return descr; -} -#endif - -/* PyObject_GenericGetAttr */ -#if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 -static PyObject* __Pyx_PyObject_GenericGetAttr(PyObject* obj, PyObject* attr_name) { - if (unlikely(Py_TYPE(obj)->tp_dictoffset)) { - return PyObject_GenericGetAttr(obj, attr_name); - } - return __Pyx_PyObject_GenericGetAttrNoDict(obj, attr_name); -} -#endif - -/* PyObjectGetAttrStrNoError */ -static void __Pyx_PyObject_GetAttrStr_ClearAttributeError(void) { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - if (likely(__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) - __Pyx_PyErr_Clear(); -} -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStrNoError(PyObject* obj, PyObject* attr_name) { - PyObject *result; -#if CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_TYPE_SLOTS && PY_VERSION_HEX >= 0x030700B1 - PyTypeObject* tp = Py_TYPE(obj); - if (likely(tp->tp_getattro == PyObject_GenericGetAttr)) { - return _PyObject_GenericGetAttrWithDict(obj, attr_name, NULL, 1); - } -#endif - result = __Pyx_PyObject_GetAttrStr(obj, attr_name); - if (unlikely(!result)) { - __Pyx_PyObject_GetAttrStr_ClearAttributeError(); - } - return result; -} - -/* SetupReduce */ -static int __Pyx_setup_reduce_is_named(PyObject* meth, PyObject* name) { - int ret; - PyObject *name_attr; - name_attr = __Pyx_PyObject_GetAttrStr(meth, __pyx_n_s_name); - if (likely(name_attr)) { - ret = PyObject_RichCompareBool(name_attr, name, Py_EQ); - } else { - ret = -1; - } - if (unlikely(ret < 0)) { - PyErr_Clear(); - ret = 0; - } - Py_XDECREF(name_attr); - return ret; -} -static int __Pyx_setup_reduce(PyObject* type_obj) { - int ret = 0; - PyObject *object_reduce = NULL; - PyObject *object_reduce_ex = NULL; - PyObject *reduce = NULL; - PyObject *reduce_ex = NULL; - PyObject *reduce_cython = NULL; - PyObject *setstate = NULL; - PyObject *setstate_cython = NULL; -#if CYTHON_USE_PYTYPE_LOOKUP - if (_PyType_Lookup((PyTypeObject*)type_obj, __pyx_n_s_getstate)) goto __PYX_GOOD; -#else - if (PyObject_HasAttr(type_obj, __pyx_n_s_getstate)) goto __PYX_GOOD; -#endif -#if CYTHON_USE_PYTYPE_LOOKUP - object_reduce_ex = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; -#else - object_reduce_ex = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto __PYX_BAD; -#endif - reduce_ex = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce_ex); if (unlikely(!reduce_ex)) goto __PYX_BAD; - if (reduce_ex == object_reduce_ex) { -#if CYTHON_USE_PYTYPE_LOOKUP - object_reduce = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_reduce); if (!object_reduce) goto __PYX_BAD; -#else - object_reduce = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce); if (!object_reduce) goto __PYX_BAD; -#endif - reduce = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce); if (unlikely(!reduce)) goto __PYX_BAD; - if (reduce == object_reduce || __Pyx_setup_reduce_is_named(reduce, __pyx_n_s_reduce_cython)) { - reduce_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_n_s_reduce_cython); - if (likely(reduce_cython)) { - ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce, reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; - ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce_cython); if (unlikely(ret < 0)) goto __PYX_BAD; - } else if (reduce == object_reduce || PyErr_Occurred()) { - goto __PYX_BAD; - } - setstate = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_setstate); - if (!setstate) PyErr_Clear(); - if (!setstate || __Pyx_setup_reduce_is_named(setstate, __pyx_n_s_setstate_cython)) { - setstate_cython = __Pyx_PyObject_GetAttrStrNoError(type_obj, __pyx_n_s_setstate_cython); - if (likely(setstate_cython)) { - ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate, setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; - ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate_cython); if (unlikely(ret < 0)) goto __PYX_BAD; - } else if (!setstate || PyErr_Occurred()) { - goto __PYX_BAD; - } - } - PyType_Modified((PyTypeObject*)type_obj); - } - } - goto __PYX_GOOD; -__PYX_BAD: - if (!PyErr_Occurred()) - PyErr_Format(PyExc_RuntimeError, "Unable to initialize pickling for %s", ((PyTypeObject*)type_obj)->tp_name); - ret = -1; -__PYX_GOOD: -#if !CYTHON_USE_PYTYPE_LOOKUP - Py_XDECREF(object_reduce); - Py_XDECREF(object_reduce_ex); -#endif - Py_XDECREF(reduce); - Py_XDECREF(reduce_ex); - Py_XDECREF(reduce_cython); - Py_XDECREF(setstate); - Py_XDECREF(setstate_cython); - return ret; -} - -/* SetVTable */ -static int __Pyx_SetVtable(PyObject *dict, void *vtable) { -#if PY_VERSION_HEX >= 0x02070000 - PyObject *ob = PyCapsule_New(vtable, 0, 0); -#else - PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); -#endif - if (!ob) - goto bad; - if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0) - goto bad; - Py_DECREF(ob); - return 0; -bad: - Py_XDECREF(ob); - return -1; -} - -/* TypeImport */ -#ifndef __PYX_HAVE_RT_ImportType -#define __PYX_HAVE_RT_ImportType -static PyTypeObject *__Pyx_ImportType(PyObject *module, const char *module_name, const char *class_name, - size_t size, enum __Pyx_ImportType_CheckSize check_size) -{ - PyObject *result = 0; - char warning[200]; - Py_ssize_t basicsize; -#ifdef Py_LIMITED_API - PyObject *py_basicsize; -#endif - result = PyObject_GetAttrString(module, class_name); - if (!result) - goto bad; - if (!PyType_Check(result)) { - PyErr_Format(PyExc_TypeError, - "%.200s.%.200s is not a type object", - module_name, class_name); - goto bad; - } -#ifndef Py_LIMITED_API - basicsize = ((PyTypeObject *)result)->tp_basicsize; -#else - py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); - if (!py_basicsize) - goto bad; - basicsize = PyLong_AsSsize_t(py_basicsize); - Py_DECREF(py_basicsize); - py_basicsize = 0; - if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) - goto bad; -#endif - if ((size_t)basicsize < size) { - PyErr_Format(PyExc_ValueError, - "%.200s.%.200s size changed, may indicate binary incompatibility. " - "Expected %zd from C header, got %zd from PyObject", - module_name, class_name, size, basicsize); - goto bad; - } - if (check_size == __Pyx_ImportType_CheckSize_Error && (size_t)basicsize != size) { - PyErr_Format(PyExc_ValueError, - "%.200s.%.200s size changed, may indicate binary incompatibility. " - "Expected %zd from C header, got %zd from PyObject", - module_name, class_name, size, basicsize); - goto bad; - } - else if (check_size == __Pyx_ImportType_CheckSize_Warn && (size_t)basicsize > size) { - PyOS_snprintf(warning, sizeof(warning), - "%s.%s size changed, may indicate binary incompatibility. " - "Expected %zd from C header, got %zd from PyObject", - module_name, class_name, size, basicsize); - if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; - } - return (PyTypeObject *)result; -bad: - Py_XDECREF(result); - return NULL; -} -#endif - -/* decode_c_string */ -static CYTHON_INLINE PyObject* __Pyx_decode_c_string( - const char* cstring, Py_ssize_t start, Py_ssize_t stop, - const char* encoding, const char* errors, - PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { - Py_ssize_t length; - if (unlikely((start < 0) | (stop < 0))) { - size_t slen = strlen(cstring); - if (unlikely(slen > (size_t) PY_SSIZE_T_MAX)) { - PyErr_SetString(PyExc_OverflowError, - "c-string too long to convert to Python"); - return NULL; - } - length = (Py_ssize_t) slen; - if (start < 0) { - start += length; - if (start < 0) - start = 0; - } - if (stop < 0) - stop += length; - } - if (unlikely(stop <= start)) - return __Pyx_NewRef(__pyx_empty_unicode); - length = stop - start; - cstring += start; - if (decode_func) { - return decode_func(cstring, length, errors); - } else { - return PyUnicode_Decode(cstring, length, encoding, errors); - } -} - -/* CLineInTraceback */ -#ifndef CYTHON_CLINE_IN_TRACEBACK -static int __Pyx_CLineForTraceback(CYTHON_NCP_UNUSED PyThreadState *tstate, int c_line) { - PyObject *use_cline; - PyObject *ptype, *pvalue, *ptraceback; -#if CYTHON_COMPILING_IN_CPYTHON - PyObject **cython_runtime_dict; -#endif - if (unlikely(!__pyx_cython_runtime)) { - return c_line; - } - __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); -#if CYTHON_COMPILING_IN_CPYTHON - cython_runtime_dict = _PyObject_GetDictPtr(__pyx_cython_runtime); - if (likely(cython_runtime_dict)) { - __PYX_PY_DICT_LOOKUP_IF_MODIFIED( - use_cline, *cython_runtime_dict, - __Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_n_s_cline_in_traceback)) - } else -#endif - { - PyObject *use_cline_obj = __Pyx_PyObject_GetAttrStr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback); - if (use_cline_obj) { - use_cline = PyObject_Not(use_cline_obj) ? Py_False : Py_True; - Py_DECREF(use_cline_obj); - } else { - PyErr_Clear(); - use_cline = NULL; - } - } - if (!use_cline) { - c_line = 0; - PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False); - } - else if (use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { - c_line = 0; - } - __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); - return c_line; -} -#endif - -/* CodeObjectCache */ -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { - int start = 0, mid = 0, end = count - 1; - if (end >= 0 && code_line > entries[end].code_line) { - return count; - } - while (start < end) { - mid = start + (end - start) / 2; - if (code_line < entries[mid].code_line) { - end = mid; - } else if (code_line > entries[mid].code_line) { - start = mid + 1; - } else { - return mid; - } - } - if (code_line <= entries[mid].code_line) { - return mid; - } else { - return mid + 1; - } -} -static PyCodeObject *__pyx_find_code_object(int code_line) { - PyCodeObject* code_object; - int pos; - if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { - return NULL; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { - return NULL; - } - code_object = __pyx_code_cache.entries[pos].code_object; - Py_INCREF(code_object); - return code_object; -} -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { - int pos, i; - __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; - if (unlikely(!code_line)) { - return; - } - if (unlikely(!entries)) { - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); - if (likely(entries)) { - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = 64; - __pyx_code_cache.count = 1; - entries[0].code_line = code_line; - entries[0].code_object = code_object; - Py_INCREF(code_object); - } - return; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { - PyCodeObject* tmp = entries[pos].code_object; - entries[pos].code_object = code_object; - Py_DECREF(tmp); - return; - } - if (__pyx_code_cache.count == __pyx_code_cache.max_count) { - int new_max = __pyx_code_cache.max_count + 64; - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( - __pyx_code_cache.entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry)); - if (unlikely(!entries)) { - return; - } - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = new_max; - } - for (i=__pyx_code_cache.count; i>pos; i--) { - entries[i] = entries[i-1]; - } - entries[pos].code_line = code_line; - entries[pos].code_object = code_object; - __pyx_code_cache.count++; - Py_INCREF(code_object); -} - -/* AddTraceback */ -#include "compile.h" -#include "frameobject.h" -#include "traceback.h" -static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( - const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyObject *py_srcfile = 0; - PyObject *py_funcname = 0; - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(filename); - #else - py_srcfile = PyUnicode_FromString(filename); - #endif - if (!py_srcfile) goto bad; - if (c_line) { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #endif - } - else { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromString(funcname); - #else - py_funcname = PyUnicode_FromString(funcname); - #endif - } - if (!py_funcname) goto bad; - py_code = __Pyx_PyCode_New( - 0, - 0, - 0, - 0, - 0, - __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ - py_srcfile, /*PyObject *filename,*/ - py_funcname, /*PyObject *name,*/ - py_line, - __pyx_empty_bytes /*PyObject *lnotab*/ - ); - Py_DECREF(py_srcfile); - Py_DECREF(py_funcname); - return py_code; -bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); - return NULL; -} -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - PyThreadState *tstate = __Pyx_PyThreadState_Current; - if (c_line) { - c_line = __Pyx_CLineForTraceback(tstate, c_line); - } - py_code = __pyx_find_code_object(c_line ? -c_line : py_line); - if (!py_code) { - py_code = __Pyx_CreateCodeObjectForTraceback( - funcname, c_line, py_line, filename); - if (!py_code) goto bad; - __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); - } - py_frame = PyFrame_New( - tstate, /*PyThreadState *tstate,*/ - py_code, /*PyCodeObject *code,*/ - __pyx_d, /*PyObject *globals,*/ - 0 /*PyObject *locals*/ - ); - if (!py_frame) goto bad; - __Pyx_PyFrame_SetLineNumber(py_frame, py_line); - PyTraceBack_Here(py_frame); -bad: - Py_XDECREF(py_code); - Py_XDECREF(py_frame); -} - -/* CIntFromPyVerify */ -#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ - __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) -#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ - __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) -#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ - {\ - func_type value = func_value;\ - if (sizeof(target_type) < sizeof(func_type)) {\ - if (unlikely(value != (func_type) (target_type) value)) {\ - func_type zero = 0;\ - if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ - return (target_type) -1;\ - if (is_unsigned && unlikely(value < zero))\ - goto raise_neg_overflow;\ - else\ - goto raise_overflow;\ - }\ - }\ - return (target_type) value;\ - } - -/* CIntToPy */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - const int neg_one = (int) -1, const_zero = (int) 0; -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic pop -#endif - const int is_unsigned = neg_one > const_zero; - if (is_unsigned) { - if (sizeof(int) < sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof(int) <= sizeof(unsigned long)) { - return PyLong_FromUnsignedLong((unsigned long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); -#endif - } - } else { - if (sizeof(int) <= sizeof(long)) { - return PyInt_FromLong((long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { - return PyLong_FromLongLong((PY_LONG_LONG) value); -#endif - } - } - { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&value; - return _PyLong_FromByteArray(bytes, sizeof(int), - little, !is_unsigned); - } -} - -/* CIntFromPy */ -static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - const int neg_one = (int) -1, const_zero = (int) 0; -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic pop -#endif - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - if (sizeof(int) < sizeof(long)) { - __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) - } else { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - goto raise_neg_overflow; - } - return (int) val; - } - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (int) 0; - case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0]) - case 2: - if (8 * sizeof(int) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) { - return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - case 3: - if (8 * sizeof(int) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) { - return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - case 4: - if (8 * sizeof(int) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) { - return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - } -#endif -#if CYTHON_COMPILING_IN_CPYTHON - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } -#else - { - int result = PyObject_RichCompareBool(x, Py_False, Py_LT); - if (unlikely(result < 0)) - return (int) -1; - if (unlikely(result == 1)) - goto raise_neg_overflow; - } -#endif - if (sizeof(int) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) -#endif - } - } else { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (int) 0; - case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0])) - case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0]) - case -2: - if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 2: - if (8 * sizeof(int) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case -3: - if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 3: - if (8 * sizeof(int) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case -4: - if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 4: - if (8 * sizeof(int) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { - return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - } -#endif - if (sizeof(int) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) -#endif - } - } - { -#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); -#else - int val; - PyObject *v = __Pyx_PyNumber_IntOrLong(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } -#endif - return (int) -1; - } - } else { - int val; - PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); - if (!tmp) return (int) -1; - val = __Pyx_PyInt_As_int(tmp); - Py_DECREF(tmp); - return val; - } -raise_overflow: - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to int"); - return (int) -1; -raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to int"); - return (int) -1; -} - -/* CIntFromPy */ -static CYTHON_INLINE enum llhttp_method __Pyx_PyInt_As_enum__llhttp_method(PyObject *x) { -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - const enum llhttp_method neg_one = (enum llhttp_method) -1, const_zero = (enum llhttp_method) 0; -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic pop -#endif - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - if (sizeof(enum llhttp_method) < sizeof(long)) { - __PYX_VERIFY_RETURN_INT(enum llhttp_method, long, PyInt_AS_LONG(x)) - } else { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - goto raise_neg_overflow; - } - return (enum llhttp_method) val; - } - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (enum llhttp_method) 0; - case 1: __PYX_VERIFY_RETURN_INT(enum llhttp_method, digit, digits[0]) - case 2: - if (8 * sizeof(enum llhttp_method) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(enum llhttp_method, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(enum llhttp_method) >= 2 * PyLong_SHIFT) { - return (enum llhttp_method) (((((enum llhttp_method)digits[1]) << PyLong_SHIFT) | (enum llhttp_method)digits[0])); - } - } - break; - case 3: - if (8 * sizeof(enum llhttp_method) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(enum llhttp_method, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(enum llhttp_method) >= 3 * PyLong_SHIFT) { - return (enum llhttp_method) (((((((enum llhttp_method)digits[2]) << PyLong_SHIFT) | (enum llhttp_method)digits[1]) << PyLong_SHIFT) | (enum llhttp_method)digits[0])); - } - } - break; - case 4: - if (8 * sizeof(enum llhttp_method) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(enum llhttp_method, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(enum llhttp_method) >= 4 * PyLong_SHIFT) { - return (enum llhttp_method) (((((((((enum llhttp_method)digits[3]) << PyLong_SHIFT) | (enum llhttp_method)digits[2]) << PyLong_SHIFT) | (enum llhttp_method)digits[1]) << PyLong_SHIFT) | (enum llhttp_method)digits[0])); - } - } - break; - } -#endif -#if CYTHON_COMPILING_IN_CPYTHON - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } -#else - { - int result = PyObject_RichCompareBool(x, Py_False, Py_LT); - if (unlikely(result < 0)) - return (enum llhttp_method) -1; - if (unlikely(result == 1)) - goto raise_neg_overflow; - } -#endif - if (sizeof(enum llhttp_method) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT_EXC(enum llhttp_method, unsigned long, PyLong_AsUnsignedLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(enum llhttp_method) <= sizeof(unsigned PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(enum llhttp_method, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) -#endif - } - } else { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (enum llhttp_method) 0; - case -1: __PYX_VERIFY_RETURN_INT(enum llhttp_method, sdigit, (sdigit) (-(sdigit)digits[0])) - case 1: __PYX_VERIFY_RETURN_INT(enum llhttp_method, digit, +digits[0]) - case -2: - if (8 * sizeof(enum llhttp_method) - 1 > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(enum llhttp_method, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(enum llhttp_method) - 1 > 2 * PyLong_SHIFT) { - return (enum llhttp_method) (((enum llhttp_method)-1)*(((((enum llhttp_method)digits[1]) << PyLong_SHIFT) | (enum llhttp_method)digits[0]))); - } - } - break; - case 2: - if (8 * sizeof(enum llhttp_method) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(enum llhttp_method, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(enum llhttp_method) - 1 > 2 * PyLong_SHIFT) { - return (enum llhttp_method) ((((((enum llhttp_method)digits[1]) << PyLong_SHIFT) | (enum llhttp_method)digits[0]))); - } - } - break; - case -3: - if (8 * sizeof(enum llhttp_method) - 1 > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(enum llhttp_method, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(enum llhttp_method) - 1 > 3 * PyLong_SHIFT) { - return (enum llhttp_method) (((enum llhttp_method)-1)*(((((((enum llhttp_method)digits[2]) << PyLong_SHIFT) | (enum llhttp_method)digits[1]) << PyLong_SHIFT) | (enum llhttp_method)digits[0]))); - } - } - break; - case 3: - if (8 * sizeof(enum llhttp_method) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(enum llhttp_method, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(enum llhttp_method) - 1 > 3 * PyLong_SHIFT) { - return (enum llhttp_method) ((((((((enum llhttp_method)digits[2]) << PyLong_SHIFT) | (enum llhttp_method)digits[1]) << PyLong_SHIFT) | (enum llhttp_method)digits[0]))); - } - } - break; - case -4: - if (8 * sizeof(enum llhttp_method) - 1 > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(enum llhttp_method, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(enum llhttp_method) - 1 > 4 * PyLong_SHIFT) { - return (enum llhttp_method) (((enum llhttp_method)-1)*(((((((((enum llhttp_method)digits[3]) << PyLong_SHIFT) | (enum llhttp_method)digits[2]) << PyLong_SHIFT) | (enum llhttp_method)digits[1]) << PyLong_SHIFT) | (enum llhttp_method)digits[0]))); - } - } - break; - case 4: - if (8 * sizeof(enum llhttp_method) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(enum llhttp_method, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(enum llhttp_method) - 1 > 4 * PyLong_SHIFT) { - return (enum llhttp_method) ((((((((((enum llhttp_method)digits[3]) << PyLong_SHIFT) | (enum llhttp_method)digits[2]) << PyLong_SHIFT) | (enum llhttp_method)digits[1]) << PyLong_SHIFT) | (enum llhttp_method)digits[0]))); - } - } - break; - } -#endif - if (sizeof(enum llhttp_method) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT_EXC(enum llhttp_method, long, PyLong_AsLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(enum llhttp_method) <= sizeof(PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(enum llhttp_method, PY_LONG_LONG, PyLong_AsLongLong(x)) -#endif - } - } - { -#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); -#else - enum llhttp_method val; - PyObject *v = __Pyx_PyNumber_IntOrLong(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } -#endif - return (enum llhttp_method) -1; - } - } else { - enum llhttp_method val; - PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); - if (!tmp) return (enum llhttp_method) -1; - val = __Pyx_PyInt_As_enum__llhttp_method(tmp); - Py_DECREF(tmp); - return val; - } -raise_overflow: - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to enum llhttp_method"); - return (enum llhttp_method) -1; -raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to enum llhttp_method"); - return (enum llhttp_method) -1; -} - -/* CIntFromPy */ -static CYTHON_INLINE size_t __Pyx_PyInt_As_size_t(PyObject *x) { -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - const size_t neg_one = (size_t) -1, const_zero = (size_t) 0; -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic pop -#endif - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - if (sizeof(size_t) < sizeof(long)) { - __PYX_VERIFY_RETURN_INT(size_t, long, PyInt_AS_LONG(x)) - } else { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - goto raise_neg_overflow; - } - return (size_t) val; - } - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (size_t) 0; - case 1: __PYX_VERIFY_RETURN_INT(size_t, digit, digits[0]) - case 2: - if (8 * sizeof(size_t) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(size_t) >= 2 * PyLong_SHIFT) { - return (size_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - } - break; - case 3: - if (8 * sizeof(size_t) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(size_t) >= 3 * PyLong_SHIFT) { - return (size_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - } - break; - case 4: - if (8 * sizeof(size_t) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(size_t) >= 4 * PyLong_SHIFT) { - return (size_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - } - break; - } -#endif -#if CYTHON_COMPILING_IN_CPYTHON - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } -#else - { - int result = PyObject_RichCompareBool(x, Py_False, Py_LT); - if (unlikely(result < 0)) - return (size_t) -1; - if (unlikely(result == 1)) - goto raise_neg_overflow; - } -#endif - if (sizeof(size_t) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT_EXC(size_t, unsigned long, PyLong_AsUnsignedLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(size_t) <= sizeof(unsigned PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(size_t, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) -#endif - } - } else { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (size_t) 0; - case -1: __PYX_VERIFY_RETURN_INT(size_t, sdigit, (sdigit) (-(sdigit)digits[0])) - case 1: __PYX_VERIFY_RETURN_INT(size_t, digit, +digits[0]) - case -2: - if (8 * sizeof(size_t) - 1 > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(size_t, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(size_t) - 1 > 2 * PyLong_SHIFT) { - return (size_t) (((size_t)-1)*(((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); - } - } - break; - case 2: - if (8 * sizeof(size_t) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(size_t) - 1 > 2 * PyLong_SHIFT) { - return (size_t) ((((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); - } - } - break; - case -3: - if (8 * sizeof(size_t) - 1 > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(size_t, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(size_t) - 1 > 3 * PyLong_SHIFT) { - return (size_t) (((size_t)-1)*(((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); - } - } - break; - case 3: - if (8 * sizeof(size_t) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(size_t) - 1 > 3 * PyLong_SHIFT) { - return (size_t) ((((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); - } - } - break; - case -4: - if (8 * sizeof(size_t) - 1 > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(size_t, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(size_t) - 1 > 4 * PyLong_SHIFT) { - return (size_t) (((size_t)-1)*(((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); - } - } - break; - case 4: - if (8 * sizeof(size_t) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(size_t, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(size_t) - 1 > 4 * PyLong_SHIFT) { - return (size_t) ((((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0]))); - } - } - break; - } -#endif - if (sizeof(size_t) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT_EXC(size_t, long, PyLong_AsLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(size_t) <= sizeof(PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(size_t, PY_LONG_LONG, PyLong_AsLongLong(x)) -#endif - } - } - { -#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); -#else - size_t val; - PyObject *v = __Pyx_PyNumber_IntOrLong(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } -#endif - return (size_t) -1; - } - } else { - size_t val; - PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); - if (!tmp) return (size_t) -1; - val = __Pyx_PyInt_As_size_t(tmp); - Py_DECREF(tmp); - return val; - } -raise_overflow: - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to size_t"); - return (size_t) -1; -raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to size_t"); - return (size_t) -1; -} - -/* CIntFromPy */ -static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - const long neg_one = (long) -1, const_zero = (long) 0; -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic pop -#endif - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - if (sizeof(long) < sizeof(long)) { - __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) - } else { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - goto raise_neg_overflow; - } - return (long) val; - } - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (long) 0; - case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0]) - case 2: - if (8 * sizeof(long) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) { - return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - case 3: - if (8 * sizeof(long) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) { - return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - case 4: - if (8 * sizeof(long) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) { - return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - } -#endif -#if CYTHON_COMPILING_IN_CPYTHON - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } -#else - { - int result = PyObject_RichCompareBool(x, Py_False, Py_LT); - if (unlikely(result < 0)) - return (long) -1; - if (unlikely(result == 1)) - goto raise_neg_overflow; - } -#endif - if (sizeof(long) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) -#endif - } - } else { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (long) 0; - case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0])) - case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0]) - case -2: - if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 2: - if (8 * sizeof(long) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case -3: - if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 3: - if (8 * sizeof(long) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case -4: - if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 4: - if (8 * sizeof(long) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - } -#endif - if (sizeof(long) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) -#endif - } - } - { -#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); -#else - long val; - PyObject *v = __Pyx_PyNumber_IntOrLong(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } -#endif - return (long) -1; - } - } else { - long val; - PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); - if (!tmp) return (long) -1; - val = __Pyx_PyInt_As_long(tmp); - Py_DECREF(tmp); - return val; - } -raise_overflow: - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to long"); - return (long) -1; -raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long) -1; -} - -/* CIntToPy */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_uint8_t(uint8_t value) { -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - const uint8_t neg_one = (uint8_t) -1, const_zero = (uint8_t) 0; -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic pop -#endif - const int is_unsigned = neg_one > const_zero; - if (is_unsigned) { - if (sizeof(uint8_t) < sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof(uint8_t) <= sizeof(unsigned long)) { - return PyLong_FromUnsignedLong((unsigned long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(uint8_t) <= sizeof(unsigned PY_LONG_LONG)) { - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); -#endif - } - } else { - if (sizeof(uint8_t) <= sizeof(long)) { - return PyInt_FromLong((long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(uint8_t) <= sizeof(PY_LONG_LONG)) { - return PyLong_FromLongLong((PY_LONG_LONG) value); -#endif - } - } - { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&value; - return _PyLong_FromByteArray(bytes, sizeof(uint8_t), - little, !is_unsigned); - } -} - -/* CIntToPy */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - const long neg_one = (long) -1, const_zero = (long) 0; -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic pop -#endif - const int is_unsigned = neg_one > const_zero; - if (is_unsigned) { - if (sizeof(long) < sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof(long) <= sizeof(unsigned long)) { - return PyLong_FromUnsignedLong((unsigned long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); -#endif - } - } else { - if (sizeof(long) <= sizeof(long)) { - return PyInt_FromLong((long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { - return PyLong_FromLongLong((PY_LONG_LONG) value); -#endif - } - } - { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&value; - return _PyLong_FromByteArray(bytes, sizeof(long), - little, !is_unsigned); - } -} - -/* FastTypeChecks */ -#if CYTHON_COMPILING_IN_CPYTHON -static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { - while (a) { - a = a->tp_base; - if (a == b) - return 1; - } - return b == &PyBaseObject_Type; -} -static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { - PyObject *mro; - if (a == b) return 1; - mro = a->tp_mro; - if (likely(mro)) { - Py_ssize_t i, n; - n = PyTuple_GET_SIZE(mro); - for (i = 0; i < n; i++) { - if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) - return 1; - } - return 0; - } - return __Pyx_InBases(a, b); -} -#if PY_MAJOR_VERSION == 2 -static int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject* exc_type2) { - PyObject *exception, *value, *tb; - int res; - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ErrFetch(&exception, &value, &tb); - res = exc_type1 ? PyObject_IsSubclass(err, exc_type1) : 0; - if (unlikely(res == -1)) { - PyErr_WriteUnraisable(err); - res = 0; - } - if (!res) { - res = PyObject_IsSubclass(err, exc_type2); - if (unlikely(res == -1)) { - PyErr_WriteUnraisable(err); - res = 0; - } - } - __Pyx_ErrRestore(exception, value, tb); - return res; -} -#else -static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { - int res = exc_type1 ? __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type1) : 0; - if (!res) { - res = __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); - } - return res; -} -#endif -static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { - Py_ssize_t i, n; - assert(PyExceptionClass_Check(exc_type)); - n = PyTuple_GET_SIZE(tuple); -#if PY_MAJOR_VERSION >= 3 - for (i=0; itp_name); - if (cached_type) { - if (!PyType_Check((PyObject*)cached_type)) { - PyErr_Format(PyExc_TypeError, - "Shared Cython type %.200s is not a type object", - type->tp_name); - goto bad; - } - if (cached_type->tp_basicsize != type->tp_basicsize) { - PyErr_Format(PyExc_TypeError, - "Shared Cython type %.200s has the wrong size, try recompiling", - type->tp_name); - goto bad; - } - } else { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto bad; - PyErr_Clear(); - if (PyType_Ready(type) < 0) goto bad; - if (PyObject_SetAttrString(fake_module, type->tp_name, (PyObject*) type) < 0) - goto bad; - Py_INCREF(type); - cached_type = type; - } -done: - Py_DECREF(fake_module); - return cached_type; -bad: - Py_XDECREF(cached_type); - cached_type = NULL; - goto done; -} - -/* PyObjectGetMethod */ -static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method) { - PyObject *attr; -#if CYTHON_UNPACK_METHODS && CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_PYTYPE_LOOKUP - PyTypeObject *tp = Py_TYPE(obj); - PyObject *descr; - descrgetfunc f = NULL; - PyObject **dictptr, *dict; - int meth_found = 0; - assert (*method == NULL); - if (unlikely(tp->tp_getattro != PyObject_GenericGetAttr)) { - attr = __Pyx_PyObject_GetAttrStr(obj, name); - goto try_unpack; - } - if (unlikely(tp->tp_dict == NULL) && unlikely(PyType_Ready(tp) < 0)) { - return 0; - } - descr = _PyType_Lookup(tp, name); - if (likely(descr != NULL)) { - Py_INCREF(descr); -#if PY_MAJOR_VERSION >= 3 - #ifdef __Pyx_CyFunction_USED - if (likely(PyFunction_Check(descr) || (Py_TYPE(descr) == &PyMethodDescr_Type) || __Pyx_CyFunction_Check(descr))) - #else - if (likely(PyFunction_Check(descr) || (Py_TYPE(descr) == &PyMethodDescr_Type))) - #endif -#else - #ifdef __Pyx_CyFunction_USED - if (likely(PyFunction_Check(descr) || __Pyx_CyFunction_Check(descr))) - #else - if (likely(PyFunction_Check(descr))) - #endif -#endif - { - meth_found = 1; - } else { - f = Py_TYPE(descr)->tp_descr_get; - if (f != NULL && PyDescr_IsData(descr)) { - attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); - Py_DECREF(descr); - goto try_unpack; - } - } - } - dictptr = _PyObject_GetDictPtr(obj); - if (dictptr != NULL && (dict = *dictptr) != NULL) { - Py_INCREF(dict); - attr = __Pyx_PyDict_GetItemStr(dict, name); - if (attr != NULL) { - Py_INCREF(attr); - Py_DECREF(dict); - Py_XDECREF(descr); - goto try_unpack; - } - Py_DECREF(dict); - } - if (meth_found) { - *method = descr; - return 1; - } - if (f != NULL) { - attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); - Py_DECREF(descr); - goto try_unpack; - } - if (descr != NULL) { - *method = descr; - return 0; - } - PyErr_Format(PyExc_AttributeError, -#if PY_MAJOR_VERSION >= 3 - "'%.50s' object has no attribute '%U'", - tp->tp_name, name); -#else - "'%.50s' object has no attribute '%.400s'", - tp->tp_name, PyString_AS_STRING(name)); -#endif - return 0; -#else - attr = __Pyx_PyObject_GetAttrStr(obj, name); - goto try_unpack; -#endif -try_unpack: -#if CYTHON_UNPACK_METHODS - if (likely(attr) && PyMethod_Check(attr) && likely(PyMethod_GET_SELF(attr) == obj)) { - PyObject *function = PyMethod_GET_FUNCTION(attr); - Py_INCREF(function); - Py_DECREF(attr); - *method = function; - return 1; - } -#endif - *method = attr; - return 0; -} - -/* PyObjectCallMethod1 */ -static PyObject* __Pyx__PyObject_CallMethod1(PyObject* method, PyObject* arg) { - PyObject *result = __Pyx_PyObject_CallOneArg(method, arg); - Py_DECREF(method); - return result; -} -static PyObject* __Pyx_PyObject_CallMethod1(PyObject* obj, PyObject* method_name, PyObject* arg) { - PyObject *method = NULL, *result; - int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); - if (likely(is_method)) { - result = __Pyx_PyObject_Call2Args(method, obj, arg); - Py_DECREF(method); - return result; - } - if (unlikely(!method)) return NULL; - return __Pyx__PyObject_CallMethod1(method, arg); -} - -/* CoroutineBase */ -#include -#include -#define __Pyx_Coroutine_Undelegate(gen) Py_CLEAR((gen)->yieldfrom) -static int __Pyx_PyGen__FetchStopIterationValue(CYTHON_UNUSED PyThreadState *__pyx_tstate, PyObject **pvalue) { - PyObject *et, *ev, *tb; - PyObject *value = NULL; - __Pyx_ErrFetch(&et, &ev, &tb); - if (!et) { - Py_XDECREF(tb); - Py_XDECREF(ev); - Py_INCREF(Py_None); - *pvalue = Py_None; - return 0; - } - if (likely(et == PyExc_StopIteration)) { - if (!ev) { - Py_INCREF(Py_None); - value = Py_None; - } -#if PY_VERSION_HEX >= 0x030300A0 - else if (Py_TYPE(ev) == (PyTypeObject*)PyExc_StopIteration) { - value = ((PyStopIterationObject *)ev)->value; - Py_INCREF(value); - Py_DECREF(ev); - } -#endif - else if (unlikely(PyTuple_Check(ev))) { - if (PyTuple_GET_SIZE(ev) >= 1) { -#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS - value = PyTuple_GET_ITEM(ev, 0); - Py_INCREF(value); -#else - value = PySequence_ITEM(ev, 0); -#endif - } else { - Py_INCREF(Py_None); - value = Py_None; - } - Py_DECREF(ev); - } - else if (!__Pyx_TypeCheck(ev, (PyTypeObject*)PyExc_StopIteration)) { - value = ev; - } - if (likely(value)) { - Py_XDECREF(tb); - Py_DECREF(et); - *pvalue = value; - return 0; - } - } else if (!__Pyx_PyErr_GivenExceptionMatches(et, PyExc_StopIteration)) { - __Pyx_ErrRestore(et, ev, tb); - return -1; - } - PyErr_NormalizeException(&et, &ev, &tb); - if (unlikely(!PyObject_TypeCheck(ev, (PyTypeObject*)PyExc_StopIteration))) { - __Pyx_ErrRestore(et, ev, tb); - return -1; - } - Py_XDECREF(tb); - Py_DECREF(et); -#if PY_VERSION_HEX >= 0x030300A0 - value = ((PyStopIterationObject *)ev)->value; - Py_INCREF(value); - Py_DECREF(ev); -#else - { - PyObject* args = __Pyx_PyObject_GetAttrStr(ev, __pyx_n_s_args); - Py_DECREF(ev); - if (likely(args)) { - value = PySequence_GetItem(args, 0); - Py_DECREF(args); - } - if (unlikely(!value)) { - __Pyx_ErrRestore(NULL, NULL, NULL); - Py_INCREF(Py_None); - value = Py_None; - } - } -#endif - *pvalue = value; - return 0; -} -static CYTHON_INLINE -void __Pyx_Coroutine_ExceptionClear(__Pyx_ExcInfoStruct *exc_state) { - PyObject *t, *v, *tb; - t = exc_state->exc_type; - v = exc_state->exc_value; - tb = exc_state->exc_traceback; - exc_state->exc_type = NULL; - exc_state->exc_value = NULL; - exc_state->exc_traceback = NULL; - Py_XDECREF(t); - Py_XDECREF(v); - Py_XDECREF(tb); -} -#define __Pyx_Coroutine_AlreadyRunningError(gen) (__Pyx__Coroutine_AlreadyRunningError(gen), (PyObject*)NULL) -static void __Pyx__Coroutine_AlreadyRunningError(CYTHON_UNUSED __pyx_CoroutineObject *gen) { - const char *msg; - if ((0)) { - #ifdef __Pyx_Coroutine_USED - } else if (__Pyx_Coroutine_Check((PyObject*)gen)) { - msg = "coroutine already executing"; - #endif - #ifdef __Pyx_AsyncGen_USED - } else if (__Pyx_AsyncGen_CheckExact((PyObject*)gen)) { - msg = "async generator already executing"; - #endif - } else { - msg = "generator already executing"; - } - PyErr_SetString(PyExc_ValueError, msg); -} -#define __Pyx_Coroutine_NotStartedError(gen) (__Pyx__Coroutine_NotStartedError(gen), (PyObject*)NULL) -static void __Pyx__Coroutine_NotStartedError(CYTHON_UNUSED PyObject *gen) { - const char *msg; - if ((0)) { - #ifdef __Pyx_Coroutine_USED - } else if (__Pyx_Coroutine_Check(gen)) { - msg = "can't send non-None value to a just-started coroutine"; - #endif - #ifdef __Pyx_AsyncGen_USED - } else if (__Pyx_AsyncGen_CheckExact(gen)) { - msg = "can't send non-None value to a just-started async generator"; - #endif - } else { - msg = "can't send non-None value to a just-started generator"; - } - PyErr_SetString(PyExc_TypeError, msg); -} -#define __Pyx_Coroutine_AlreadyTerminatedError(gen, value, closing) (__Pyx__Coroutine_AlreadyTerminatedError(gen, value, closing), (PyObject*)NULL) -static void __Pyx__Coroutine_AlreadyTerminatedError(CYTHON_UNUSED PyObject *gen, PyObject *value, CYTHON_UNUSED int closing) { - #ifdef __Pyx_Coroutine_USED - if (!closing && __Pyx_Coroutine_Check(gen)) { - PyErr_SetString(PyExc_RuntimeError, "cannot reuse already awaited coroutine"); - } else - #endif - if (value) { - #ifdef __Pyx_AsyncGen_USED - if (__Pyx_AsyncGen_CheckExact(gen)) - PyErr_SetNone(__Pyx_PyExc_StopAsyncIteration); - else - #endif - PyErr_SetNone(PyExc_StopIteration); - } -} -static -PyObject *__Pyx_Coroutine_SendEx(__pyx_CoroutineObject *self, PyObject *value, int closing) { - __Pyx_PyThreadState_declare - PyThreadState *tstate; - __Pyx_ExcInfoStruct *exc_state; - PyObject *retval; - assert(!self->is_running); - if (unlikely(self->resume_label == 0)) { - if (unlikely(value && value != Py_None)) { - return __Pyx_Coroutine_NotStartedError((PyObject*)self); - } - } - if (unlikely(self->resume_label == -1)) { - return __Pyx_Coroutine_AlreadyTerminatedError((PyObject*)self, value, closing); - } -#if CYTHON_FAST_THREAD_STATE - __Pyx_PyThreadState_assign - tstate = __pyx_tstate; -#else - tstate = __Pyx_PyThreadState_Current; -#endif - exc_state = &self->gi_exc_state; - if (exc_state->exc_type) { - #if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_PYSTON - #else - if (exc_state->exc_traceback) { - PyTracebackObject *tb = (PyTracebackObject *) exc_state->exc_traceback; - PyFrameObject *f = tb->tb_frame; - Py_XINCREF(tstate->frame); - assert(f->f_back == NULL); - f->f_back = tstate->frame; - } - #endif - } -#if CYTHON_USE_EXC_INFO_STACK - exc_state->previous_item = tstate->exc_info; - tstate->exc_info = exc_state; -#else - if (exc_state->exc_type) { - __Pyx_ExceptionSwap(&exc_state->exc_type, &exc_state->exc_value, &exc_state->exc_traceback); - } else { - __Pyx_Coroutine_ExceptionClear(exc_state); - __Pyx_ExceptionSave(&exc_state->exc_type, &exc_state->exc_value, &exc_state->exc_traceback); - } -#endif - self->is_running = 1; - retval = self->body((PyObject *) self, tstate, value); - self->is_running = 0; -#if CYTHON_USE_EXC_INFO_STACK - exc_state = &self->gi_exc_state; - tstate->exc_info = exc_state->previous_item; - exc_state->previous_item = NULL; - __Pyx_Coroutine_ResetFrameBackpointer(exc_state); -#endif - return retval; -} -static CYTHON_INLINE void __Pyx_Coroutine_ResetFrameBackpointer(__Pyx_ExcInfoStruct *exc_state) { - PyObject *exc_tb = exc_state->exc_traceback; - if (likely(exc_tb)) { -#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_PYSTON -#else - PyTracebackObject *tb = (PyTracebackObject *) exc_tb; - PyFrameObject *f = tb->tb_frame; - Py_CLEAR(f->f_back); -#endif - } -} -static CYTHON_INLINE -PyObject *__Pyx_Coroutine_MethodReturn(CYTHON_UNUSED PyObject* gen, PyObject *retval) { - if (unlikely(!retval)) { - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - if (!__Pyx_PyErr_Occurred()) { - PyObject *exc = PyExc_StopIteration; - #ifdef __Pyx_AsyncGen_USED - if (__Pyx_AsyncGen_CheckExact(gen)) - exc = __Pyx_PyExc_StopAsyncIteration; - #endif - __Pyx_PyErr_SetNone(exc); - } - } - return retval; -} -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03030000 && (defined(__linux__) || PY_VERSION_HEX >= 0x030600B3) -static CYTHON_INLINE -PyObject *__Pyx_PyGen_Send(PyGenObject *gen, PyObject *arg) { -#if PY_VERSION_HEX <= 0x030A00A1 - return _PyGen_Send(gen, arg); -#else - PyObject *result; - if (PyIter_Send((PyObject*)gen, arg ? arg : Py_None, &result) == PYGEN_RETURN) { - if (PyAsyncGen_CheckExact(gen)) { - assert(result == Py_None); - PyErr_SetNone(PyExc_StopAsyncIteration); - } - else if (result == Py_None) { - PyErr_SetNone(PyExc_StopIteration); - } - else { - _PyGen_SetStopIterationValue(result); - } - Py_CLEAR(result); - } - return result; -#endif -} -#endif -static CYTHON_INLINE -PyObject *__Pyx_Coroutine_FinishDelegation(__pyx_CoroutineObject *gen) { - PyObject *ret; - PyObject *val = NULL; - __Pyx_Coroutine_Undelegate(gen); - __Pyx_PyGen__FetchStopIterationValue(__Pyx_PyThreadState_Current, &val); - ret = __Pyx_Coroutine_SendEx(gen, val, 0); - Py_XDECREF(val); - return ret; -} -static PyObject *__Pyx_Coroutine_Send(PyObject *self, PyObject *value) { - PyObject *retval; - __pyx_CoroutineObject *gen = (__pyx_CoroutineObject*) self; - PyObject *yf = gen->yieldfrom; - if (unlikely(gen->is_running)) - return __Pyx_Coroutine_AlreadyRunningError(gen); - if (yf) { - PyObject *ret; - gen->is_running = 1; - #ifdef __Pyx_Generator_USED - if (__Pyx_Generator_CheckExact(yf)) { - ret = __Pyx_Coroutine_Send(yf, value); - } else - #endif - #ifdef __Pyx_Coroutine_USED - if (__Pyx_Coroutine_Check(yf)) { - ret = __Pyx_Coroutine_Send(yf, value); - } else - #endif - #ifdef __Pyx_AsyncGen_USED - if (__pyx_PyAsyncGenASend_CheckExact(yf)) { - ret = __Pyx_async_gen_asend_send(yf, value); - } else - #endif - #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03030000 && (defined(__linux__) || PY_VERSION_HEX >= 0x030600B3) - if (PyGen_CheckExact(yf)) { - ret = __Pyx_PyGen_Send((PyGenObject*)yf, value == Py_None ? NULL : value); - } else - #endif - #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03050000 && defined(PyCoro_CheckExact) && (defined(__linux__) || PY_VERSION_HEX >= 0x030600B3) - if (PyCoro_CheckExact(yf)) { - ret = __Pyx_PyGen_Send((PyGenObject*)yf, value == Py_None ? NULL : value); - } else - #endif - { - if (value == Py_None) - ret = Py_TYPE(yf)->tp_iternext(yf); - else - ret = __Pyx_PyObject_CallMethod1(yf, __pyx_n_s_send, value); - } - gen->is_running = 0; - if (likely(ret)) { - return ret; - } - retval = __Pyx_Coroutine_FinishDelegation(gen); - } else { - retval = __Pyx_Coroutine_SendEx(gen, value, 0); - } - return __Pyx_Coroutine_MethodReturn(self, retval); -} -static int __Pyx_Coroutine_CloseIter(__pyx_CoroutineObject *gen, PyObject *yf) { - PyObject *retval = NULL; - int err = 0; - #ifdef __Pyx_Generator_USED - if (__Pyx_Generator_CheckExact(yf)) { - retval = __Pyx_Coroutine_Close(yf); - if (!retval) - return -1; - } else - #endif - #ifdef __Pyx_Coroutine_USED - if (__Pyx_Coroutine_Check(yf)) { - retval = __Pyx_Coroutine_Close(yf); - if (!retval) - return -1; - } else - if (__Pyx_CoroutineAwait_CheckExact(yf)) { - retval = __Pyx_CoroutineAwait_Close((__pyx_CoroutineAwaitObject*)yf, NULL); - if (!retval) - return -1; - } else - #endif - #ifdef __Pyx_AsyncGen_USED - if (__pyx_PyAsyncGenASend_CheckExact(yf)) { - retval = __Pyx_async_gen_asend_close(yf, NULL); - } else - if (__pyx_PyAsyncGenAThrow_CheckExact(yf)) { - retval = __Pyx_async_gen_athrow_close(yf, NULL); - } else - #endif - { - PyObject *meth; - gen->is_running = 1; - meth = __Pyx_PyObject_GetAttrStr(yf, __pyx_n_s_close); - if (unlikely(!meth)) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_WriteUnraisable(yf); - } - PyErr_Clear(); - } else { - retval = PyObject_CallFunction(meth, NULL); - Py_DECREF(meth); - if (!retval) - err = -1; - } - gen->is_running = 0; - } - Py_XDECREF(retval); - return err; -} -static PyObject *__Pyx_Generator_Next(PyObject *self) { - __pyx_CoroutineObject *gen = (__pyx_CoroutineObject*) self; - PyObject *yf = gen->yieldfrom; - if (unlikely(gen->is_running)) - return __Pyx_Coroutine_AlreadyRunningError(gen); - if (yf) { - PyObject *ret; - gen->is_running = 1; - #ifdef __Pyx_Generator_USED - if (__Pyx_Generator_CheckExact(yf)) { - ret = __Pyx_Generator_Next(yf); - } else - #endif - #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03030000 && (defined(__linux__) || PY_VERSION_HEX >= 0x030600B3) - if (PyGen_CheckExact(yf)) { - ret = __Pyx_PyGen_Send((PyGenObject*)yf, NULL); - } else - #endif - #ifdef __Pyx_Coroutine_USED - if (__Pyx_Coroutine_Check(yf)) { - ret = __Pyx_Coroutine_Send(yf, Py_None); - } else - #endif - ret = Py_TYPE(yf)->tp_iternext(yf); - gen->is_running = 0; - if (likely(ret)) { - return ret; - } - return __Pyx_Coroutine_FinishDelegation(gen); - } - return __Pyx_Coroutine_SendEx(gen, Py_None, 0); -} -static PyObject *__Pyx_Coroutine_Close_Method(PyObject *self, CYTHON_UNUSED PyObject *arg) { - return __Pyx_Coroutine_Close(self); -} -static PyObject *__Pyx_Coroutine_Close(PyObject *self) { - __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; - PyObject *retval, *raised_exception; - PyObject *yf = gen->yieldfrom; - int err = 0; - if (unlikely(gen->is_running)) - return __Pyx_Coroutine_AlreadyRunningError(gen); - if (yf) { - Py_INCREF(yf); - err = __Pyx_Coroutine_CloseIter(gen, yf); - __Pyx_Coroutine_Undelegate(gen); - Py_DECREF(yf); - } - if (err == 0) - PyErr_SetNone(PyExc_GeneratorExit); - retval = __Pyx_Coroutine_SendEx(gen, NULL, 1); - if (unlikely(retval)) { - const char *msg; - Py_DECREF(retval); - if ((0)) { - #ifdef __Pyx_Coroutine_USED - } else if (__Pyx_Coroutine_Check(self)) { - msg = "coroutine ignored GeneratorExit"; - #endif - #ifdef __Pyx_AsyncGen_USED - } else if (__Pyx_AsyncGen_CheckExact(self)) { -#if PY_VERSION_HEX < 0x03060000 - msg = "async generator ignored GeneratorExit - might require Python 3.6+ finalisation (PEP 525)"; -#else - msg = "async generator ignored GeneratorExit"; -#endif - #endif - } else { - msg = "generator ignored GeneratorExit"; - } - PyErr_SetString(PyExc_RuntimeError, msg); - return NULL; - } - raised_exception = PyErr_Occurred(); - if (likely(!raised_exception || __Pyx_PyErr_GivenExceptionMatches2(raised_exception, PyExc_GeneratorExit, PyExc_StopIteration))) { - if (raised_exception) PyErr_Clear(); - Py_INCREF(Py_None); - return Py_None; - } - return NULL; -} -static PyObject *__Pyx__Coroutine_Throw(PyObject *self, PyObject *typ, PyObject *val, PyObject *tb, - PyObject *args, int close_on_genexit) { - __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; - PyObject *yf = gen->yieldfrom; - if (unlikely(gen->is_running)) - return __Pyx_Coroutine_AlreadyRunningError(gen); - if (yf) { - PyObject *ret; - Py_INCREF(yf); - if (__Pyx_PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) && close_on_genexit) { - int err = __Pyx_Coroutine_CloseIter(gen, yf); - Py_DECREF(yf); - __Pyx_Coroutine_Undelegate(gen); - if (err < 0) - return __Pyx_Coroutine_MethodReturn(self, __Pyx_Coroutine_SendEx(gen, NULL, 0)); - goto throw_here; - } - gen->is_running = 1; - if (0 - #ifdef __Pyx_Generator_USED - || __Pyx_Generator_CheckExact(yf) - #endif - #ifdef __Pyx_Coroutine_USED - || __Pyx_Coroutine_Check(yf) - #endif - ) { - ret = __Pyx__Coroutine_Throw(yf, typ, val, tb, args, close_on_genexit); - #ifdef __Pyx_Coroutine_USED - } else if (__Pyx_CoroutineAwait_CheckExact(yf)) { - ret = __Pyx__Coroutine_Throw(((__pyx_CoroutineAwaitObject*)yf)->coroutine, typ, val, tb, args, close_on_genexit); - #endif - } else { - PyObject *meth = __Pyx_PyObject_GetAttrStr(yf, __pyx_n_s_throw); - if (unlikely(!meth)) { - Py_DECREF(yf); - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) { - gen->is_running = 0; - return NULL; - } - PyErr_Clear(); - __Pyx_Coroutine_Undelegate(gen); - gen->is_running = 0; - goto throw_here; - } - if (likely(args)) { - ret = PyObject_CallObject(meth, args); - } else { - ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL); - } - Py_DECREF(meth); - } - gen->is_running = 0; - Py_DECREF(yf); - if (!ret) { - ret = __Pyx_Coroutine_FinishDelegation(gen); - } - return __Pyx_Coroutine_MethodReturn(self, ret); - } -throw_here: - __Pyx_Raise(typ, val, tb, NULL); - return __Pyx_Coroutine_MethodReturn(self, __Pyx_Coroutine_SendEx(gen, NULL, 0)); -} -static PyObject *__Pyx_Coroutine_Throw(PyObject *self, PyObject *args) { - PyObject *typ; - PyObject *val = NULL; - PyObject *tb = NULL; - if (!PyArg_UnpackTuple(args, (char *)"throw", 1, 3, &typ, &val, &tb)) - return NULL; - return __Pyx__Coroutine_Throw(self, typ, val, tb, args, 1); -} -static CYTHON_INLINE int __Pyx_Coroutine_traverse_excstate(__Pyx_ExcInfoStruct *exc_state, visitproc visit, void *arg) { - Py_VISIT(exc_state->exc_type); - Py_VISIT(exc_state->exc_value); - Py_VISIT(exc_state->exc_traceback); - return 0; -} -static int __Pyx_Coroutine_traverse(__pyx_CoroutineObject *gen, visitproc visit, void *arg) { - Py_VISIT(gen->closure); - Py_VISIT(gen->classobj); - Py_VISIT(gen->yieldfrom); - return __Pyx_Coroutine_traverse_excstate(&gen->gi_exc_state, visit, arg); -} -static int __Pyx_Coroutine_clear(PyObject *self) { - __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; - Py_CLEAR(gen->closure); - Py_CLEAR(gen->classobj); - Py_CLEAR(gen->yieldfrom); - __Pyx_Coroutine_ExceptionClear(&gen->gi_exc_state); -#ifdef __Pyx_AsyncGen_USED - if (__Pyx_AsyncGen_CheckExact(self)) { - Py_CLEAR(((__pyx_PyAsyncGenObject*)gen)->ag_finalizer); - } -#endif - Py_CLEAR(gen->gi_code); - Py_CLEAR(gen->gi_frame); - Py_CLEAR(gen->gi_name); - Py_CLEAR(gen->gi_qualname); - Py_CLEAR(gen->gi_modulename); - return 0; -} -static void __Pyx_Coroutine_dealloc(PyObject *self) { - __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; - PyObject_GC_UnTrack(gen); - if (gen->gi_weakreflist != NULL) - PyObject_ClearWeakRefs(self); - if (gen->resume_label >= 0) { - PyObject_GC_Track(self); -#if PY_VERSION_HEX >= 0x030400a1 && CYTHON_USE_TP_FINALIZE - if (PyObject_CallFinalizerFromDealloc(self)) -#else - Py_TYPE(gen)->tp_del(self); - if (Py_REFCNT(self) > 0) -#endif - { - return; - } - PyObject_GC_UnTrack(self); - } -#ifdef __Pyx_AsyncGen_USED - if (__Pyx_AsyncGen_CheckExact(self)) { - /* We have to handle this case for asynchronous generators - right here, because this code has to be between UNTRACK - and GC_Del. */ - Py_CLEAR(((__pyx_PyAsyncGenObject*)self)->ag_finalizer); - } -#endif - __Pyx_Coroutine_clear(self); - PyObject_GC_Del(gen); -} -static void __Pyx_Coroutine_del(PyObject *self) { - PyObject *error_type, *error_value, *error_traceback; - __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self; - __Pyx_PyThreadState_declare - if (gen->resume_label < 0) { - return; - } -#if !CYTHON_USE_TP_FINALIZE - assert(self->ob_refcnt == 0); - __Pyx_SET_REFCNT(self, 1); -#endif - __Pyx_PyThreadState_assign - __Pyx_ErrFetch(&error_type, &error_value, &error_traceback); -#ifdef __Pyx_AsyncGen_USED - if (__Pyx_AsyncGen_CheckExact(self)) { - __pyx_PyAsyncGenObject *agen = (__pyx_PyAsyncGenObject*)self; - PyObject *finalizer = agen->ag_finalizer; - if (finalizer && !agen->ag_closed) { - PyObject *res = __Pyx_PyObject_CallOneArg(finalizer, self); - if (unlikely(!res)) { - PyErr_WriteUnraisable(self); - } else { - Py_DECREF(res); - } - __Pyx_ErrRestore(error_type, error_value, error_traceback); - return; - } - } -#endif - if (unlikely(gen->resume_label == 0 && !error_value)) { -#ifdef __Pyx_Coroutine_USED -#ifdef __Pyx_Generator_USED - if (!__Pyx_Generator_CheckExact(self)) -#endif - { - PyObject_GC_UnTrack(self); -#if PY_MAJOR_VERSION >= 3 || defined(PyErr_WarnFormat) - if (unlikely(PyErr_WarnFormat(PyExc_RuntimeWarning, 1, "coroutine '%.50S' was never awaited", gen->gi_qualname) < 0)) - PyErr_WriteUnraisable(self); -#else - {PyObject *msg; - char *cmsg; - #if CYTHON_COMPILING_IN_PYPY - msg = NULL; - cmsg = (char*) "coroutine was never awaited"; - #else - char *cname; - PyObject *qualname; - qualname = gen->gi_qualname; - cname = PyString_AS_STRING(qualname); - msg = PyString_FromFormat("coroutine '%.50s' was never awaited", cname); - if (unlikely(!msg)) { - PyErr_Clear(); - cmsg = (char*) "coroutine was never awaited"; - } else { - cmsg = PyString_AS_STRING(msg); - } - #endif - if (unlikely(PyErr_WarnEx(PyExc_RuntimeWarning, cmsg, 1) < 0)) - PyErr_WriteUnraisable(self); - Py_XDECREF(msg);} -#endif - PyObject_GC_Track(self); - } -#endif - } else { - PyObject *res = __Pyx_Coroutine_Close(self); - if (unlikely(!res)) { - if (PyErr_Occurred()) - PyErr_WriteUnraisable(self); - } else { - Py_DECREF(res); - } - } - __Pyx_ErrRestore(error_type, error_value, error_traceback); -#if !CYTHON_USE_TP_FINALIZE - assert(Py_REFCNT(self) > 0); - if (--self->ob_refcnt == 0) { - return; - } - { - Py_ssize_t refcnt = Py_REFCNT(self); - _Py_NewReference(self); - __Pyx_SET_REFCNT(self, refcnt); - } -#if CYTHON_COMPILING_IN_CPYTHON - assert(PyType_IS_GC(Py_TYPE(self)) && - _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED); - _Py_DEC_REFTOTAL; -#endif -#ifdef COUNT_ALLOCS - --Py_TYPE(self)->tp_frees; - --Py_TYPE(self)->tp_allocs; -#endif -#endif -} -static PyObject * -__Pyx_Coroutine_get_name(__pyx_CoroutineObject *self, CYTHON_UNUSED void *context) -{ - PyObject *name = self->gi_name; - if (unlikely(!name)) name = Py_None; - Py_INCREF(name); - return name; -} -static int -__Pyx_Coroutine_set_name(__pyx_CoroutineObject *self, PyObject *value, CYTHON_UNUSED void *context) -{ - PyObject *tmp; -#if PY_MAJOR_VERSION >= 3 - if (unlikely(value == NULL || !PyUnicode_Check(value))) -#else - if (unlikely(value == NULL || !PyString_Check(value))) -#endif - { - PyErr_SetString(PyExc_TypeError, - "__name__ must be set to a string object"); - return -1; - } - tmp = self->gi_name; - Py_INCREF(value); - self->gi_name = value; - Py_XDECREF(tmp); - return 0; -} -static PyObject * -__Pyx_Coroutine_get_qualname(__pyx_CoroutineObject *self, CYTHON_UNUSED void *context) -{ - PyObject *name = self->gi_qualname; - if (unlikely(!name)) name = Py_None; - Py_INCREF(name); - return name; -} -static int -__Pyx_Coroutine_set_qualname(__pyx_CoroutineObject *self, PyObject *value, CYTHON_UNUSED void *context) -{ - PyObject *tmp; -#if PY_MAJOR_VERSION >= 3 - if (unlikely(value == NULL || !PyUnicode_Check(value))) -#else - if (unlikely(value == NULL || !PyString_Check(value))) -#endif - { - PyErr_SetString(PyExc_TypeError, - "__qualname__ must be set to a string object"); - return -1; - } - tmp = self->gi_qualname; - Py_INCREF(value); - self->gi_qualname = value; - Py_XDECREF(tmp); - return 0; -} -static PyObject * -__Pyx_Coroutine_get_frame(__pyx_CoroutineObject *self, CYTHON_UNUSED void *context) -{ - PyObject *frame = self->gi_frame; - if (!frame) { - if (unlikely(!self->gi_code)) { - Py_RETURN_NONE; - } - frame = (PyObject *) PyFrame_New( - PyThreadState_Get(), /*PyThreadState *tstate,*/ - (PyCodeObject*) self->gi_code, /*PyCodeObject *code,*/ - __pyx_d, /*PyObject *globals,*/ - 0 /*PyObject *locals*/ - ); - if (unlikely(!frame)) - return NULL; - self->gi_frame = frame; - } - Py_INCREF(frame); - return frame; -} -static __pyx_CoroutineObject *__Pyx__Coroutine_New( - PyTypeObject* type, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, - PyObject *name, PyObject *qualname, PyObject *module_name) { - __pyx_CoroutineObject *gen = PyObject_GC_New(__pyx_CoroutineObject, type); - if (unlikely(!gen)) - return NULL; - return __Pyx__Coroutine_NewInit(gen, body, code, closure, name, qualname, module_name); -} -static __pyx_CoroutineObject *__Pyx__Coroutine_NewInit( - __pyx_CoroutineObject *gen, __pyx_coroutine_body_t body, PyObject *code, PyObject *closure, - PyObject *name, PyObject *qualname, PyObject *module_name) { - gen->body = body; - gen->closure = closure; - Py_XINCREF(closure); - gen->is_running = 0; - gen->resume_label = 0; - gen->classobj = NULL; - gen->yieldfrom = NULL; - gen->gi_exc_state.exc_type = NULL; - gen->gi_exc_state.exc_value = NULL; - gen->gi_exc_state.exc_traceback = NULL; -#if CYTHON_USE_EXC_INFO_STACK - gen->gi_exc_state.previous_item = NULL; -#endif - gen->gi_weakreflist = NULL; - Py_XINCREF(qualname); - gen->gi_qualname = qualname; - Py_XINCREF(name); - gen->gi_name = name; - Py_XINCREF(module_name); - gen->gi_modulename = module_name; - Py_XINCREF(code); - gen->gi_code = code; - gen->gi_frame = NULL; - PyObject_GC_Track(gen); - return gen; -} - -/* PatchModuleWithCoroutine */ -static PyObject* __Pyx_Coroutine_patch_module(PyObject* module, const char* py_code) { -#if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) - int result; - PyObject *globals, *result_obj; - globals = PyDict_New(); if (unlikely(!globals)) goto ignore; - result = PyDict_SetItemString(globals, "_cython_coroutine_type", - #ifdef __Pyx_Coroutine_USED - (PyObject*)__pyx_CoroutineType); - #else - Py_None); - #endif - if (unlikely(result < 0)) goto ignore; - result = PyDict_SetItemString(globals, "_cython_generator_type", - #ifdef __Pyx_Generator_USED - (PyObject*)__pyx_GeneratorType); - #else - Py_None); - #endif - if (unlikely(result < 0)) goto ignore; - if (unlikely(PyDict_SetItemString(globals, "_module", module) < 0)) goto ignore; - if (unlikely(PyDict_SetItemString(globals, "__builtins__", __pyx_b) < 0)) goto ignore; - result_obj = PyRun_String(py_code, Py_file_input, globals, globals); - if (unlikely(!result_obj)) goto ignore; - Py_DECREF(result_obj); - Py_DECREF(globals); - return module; -ignore: - Py_XDECREF(globals); - PyErr_WriteUnraisable(module); - if (unlikely(PyErr_WarnEx(PyExc_RuntimeWarning, "Cython module failed to patch module with custom type", 1) < 0)) { - Py_DECREF(module); - module = NULL; - } -#else - py_code++; -#endif - return module; -} - -/* PatchGeneratorABC */ -#ifndef CYTHON_REGISTER_ABCS -#define CYTHON_REGISTER_ABCS 1 -#endif -#if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) -static PyObject* __Pyx_patch_abc_module(PyObject *module); -static PyObject* __Pyx_patch_abc_module(PyObject *module) { - module = __Pyx_Coroutine_patch_module( - module, "" -"if _cython_generator_type is not None:\n" -" try: Generator = _module.Generator\n" -" except AttributeError: pass\n" -" else: Generator.register(_cython_generator_type)\n" -"if _cython_coroutine_type is not None:\n" -" try: Coroutine = _module.Coroutine\n" -" except AttributeError: pass\n" -" else: Coroutine.register(_cython_coroutine_type)\n" - ); - return module; -} -#endif -static int __Pyx_patch_abc(void) { -#if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) - static int abc_patched = 0; - if (CYTHON_REGISTER_ABCS && !abc_patched) { - PyObject *module; - module = PyImport_ImportModule((PY_MAJOR_VERSION >= 3) ? "collections.abc" : "collections"); - if (!module) { - PyErr_WriteUnraisable(NULL); - if (unlikely(PyErr_WarnEx(PyExc_RuntimeWarning, - ((PY_MAJOR_VERSION >= 3) ? - "Cython module failed to register with collections.abc module" : - "Cython module failed to register with collections module"), 1) < 0)) { - return -1; - } - } else { - module = __Pyx_patch_abc_module(module); - abc_patched = 1; - if (unlikely(!module)) - return -1; - Py_DECREF(module); - } - module = PyImport_ImportModule("backports_abc"); - if (module) { - module = __Pyx_patch_abc_module(module); - Py_XDECREF(module); - } - if (!module) { - PyErr_Clear(); - } - } -#else - if ((0)) __Pyx_Coroutine_patch_module(NULL, NULL); -#endif - return 0; -} - -/* Generator */ -static PyMethodDef __pyx_Generator_methods[] = { - {"send", (PyCFunction) __Pyx_Coroutine_Send, METH_O, - (char*) PyDoc_STR("send(arg) -> send 'arg' into generator,\nreturn next yielded value or raise StopIteration.")}, - {"throw", (PyCFunction) __Pyx_Coroutine_Throw, METH_VARARGS, - (char*) PyDoc_STR("throw(typ[,val[,tb]]) -> raise exception in generator,\nreturn next yielded value or raise StopIteration.")}, - {"close", (PyCFunction) __Pyx_Coroutine_Close_Method, METH_NOARGS, - (char*) PyDoc_STR("close() -> raise GeneratorExit inside generator.")}, - {0, 0, 0, 0} -}; -static PyMemberDef __pyx_Generator_memberlist[] = { - {(char *) "gi_running", T_BOOL, offsetof(__pyx_CoroutineObject, is_running), READONLY, NULL}, - {(char*) "gi_yieldfrom", T_OBJECT, offsetof(__pyx_CoroutineObject, yieldfrom), READONLY, - (char*) PyDoc_STR("object being iterated by 'yield from', or None")}, - {(char*) "gi_code", T_OBJECT, offsetof(__pyx_CoroutineObject, gi_code), READONLY, NULL}, - {0, 0, 0, 0, 0} -}; -static PyGetSetDef __pyx_Generator_getsets[] = { - {(char *) "__name__", (getter)__Pyx_Coroutine_get_name, (setter)__Pyx_Coroutine_set_name, - (char*) PyDoc_STR("name of the generator"), 0}, - {(char *) "__qualname__", (getter)__Pyx_Coroutine_get_qualname, (setter)__Pyx_Coroutine_set_qualname, - (char*) PyDoc_STR("qualified name of the generator"), 0}, - {(char *) "gi_frame", (getter)__Pyx_Coroutine_get_frame, NULL, - (char*) PyDoc_STR("Frame of the generator"), 0}, - {0, 0, 0, 0, 0} -}; -static PyTypeObject __pyx_GeneratorType_type = { - PyVarObject_HEAD_INIT(0, 0) - "generator", - sizeof(__pyx_CoroutineObject), - 0, - (destructor) __Pyx_Coroutine_dealloc, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_FINALIZE, - 0, - (traverseproc) __Pyx_Coroutine_traverse, - 0, - 0, - offsetof(__pyx_CoroutineObject, gi_weakreflist), - 0, - (iternextfunc) __Pyx_Generator_Next, - __pyx_Generator_methods, - __pyx_Generator_memberlist, - __pyx_Generator_getsets, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, -#if CYTHON_USE_TP_FINALIZE - 0, -#else - __Pyx_Coroutine_del, -#endif - 0, -#if CYTHON_USE_TP_FINALIZE - __Pyx_Coroutine_del, -#elif PY_VERSION_HEX >= 0x030400a1 - 0, -#endif -#if PY_VERSION_HEX >= 0x030800b1 - 0, -#endif -#if PY_VERSION_HEX >= 0x030800b4 && PY_VERSION_HEX < 0x03090000 - 0, -#endif -}; -static int __pyx_Generator_init(void) { - __pyx_GeneratorType_type.tp_getattro = __Pyx_PyObject_GenericGetAttrNoDict; - __pyx_GeneratorType_type.tp_iter = PyObject_SelfIter; - __pyx_GeneratorType = __Pyx_FetchCommonType(&__pyx_GeneratorType_type); - if (unlikely(!__pyx_GeneratorType)) { - return -1; - } - return 0; -} - -/* CheckBinaryVersion */ -static int __Pyx_check_binary_version(void) { - char ctversion[4], rtversion[4]; - PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); - PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); - if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { - char message[200]; - PyOS_snprintf(message, sizeof(message), - "compiletime version %s of module '%.100s' " - "does not match runtime version %s", - ctversion, __Pyx_MODULE_NAME, rtversion); - return PyErr_WarnEx(NULL, message, 1); - } - return 0; -} - -/* InitStrings */ -static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { - while (t->p) { - #if PY_MAJOR_VERSION < 3 - if (t->is_unicode) { - *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); - } else if (t->intern) { - *t->p = PyString_InternFromString(t->s); - } else { - *t->p = PyString_FromStringAndSize(t->s, t->n - 1); - } - #else - if (t->is_unicode | t->is_str) { - if (t->intern) { - *t->p = PyUnicode_InternFromString(t->s); - } else if (t->encoding) { - *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); - } else { - *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); - } - } else { - *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); - } - #endif - if (!*t->p) - return -1; - if (PyObject_Hash(*t->p) == -1) - return -1; - ++t; - } - return 0; -} - -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { - return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); -} -static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { - Py_ssize_t ignore; - return __Pyx_PyObject_AsStringAndSize(o, &ignore); -} -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT -#if !CYTHON_PEP393_ENABLED -static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { - char* defenc_c; - PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); - if (!defenc) return NULL; - defenc_c = PyBytes_AS_STRING(defenc); -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - { - char* end = defenc_c + PyBytes_GET_SIZE(defenc); - char* c; - for (c = defenc_c; c < end; c++) { - if ((unsigned char) (*c) >= 128) { - PyUnicode_AsASCIIString(o); - return NULL; - } - } - } -#endif - *length = PyBytes_GET_SIZE(defenc); - return defenc_c; -} -#else -static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { - if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - if (likely(PyUnicode_IS_ASCII(o))) { - *length = PyUnicode_GET_LENGTH(o); - return PyUnicode_AsUTF8(o); - } else { - PyUnicode_AsASCIIString(o); - return NULL; - } -#else - return PyUnicode_AsUTF8AndSize(o, length); -#endif -} -#endif -#endif -static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT - if ( -#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - __Pyx_sys_getdefaultencoding_not_ascii && -#endif - PyUnicode_Check(o)) { - return __Pyx_PyUnicode_AsStringAndSize(o, length); - } else -#endif -#if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) - if (PyByteArray_Check(o)) { - *length = PyByteArray_GET_SIZE(o); - return PyByteArray_AS_STRING(o); - } else -#endif - { - char* result; - int r = PyBytes_AsStringAndSize(o, &result, length); - if (unlikely(r < 0)) { - return NULL; - } else { - return result; - } - } -} -static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { - int is_true = x == Py_True; - if (is_true | (x == Py_False) | (x == Py_None)) return is_true; - else return PyObject_IsTrue(x); -} -static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { - int retval; - if (unlikely(!x)) return -1; - retval = __Pyx_PyObject_IsTrue(x); - Py_DECREF(x); - return retval; -} -static PyObject* __Pyx_PyNumber_IntOrLongWrongResultType(PyObject* result, const char* type_name) { -#if PY_MAJOR_VERSION >= 3 - if (PyLong_Check(result)) { - if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, - "__int__ returned non-int (type %.200s). " - "The ability to return an instance of a strict subclass of int " - "is deprecated, and may be removed in a future version of Python.", - Py_TYPE(result)->tp_name)) { - Py_DECREF(result); - return NULL; - } - return result; - } -#endif - PyErr_Format(PyExc_TypeError, - "__%.4s__ returned non-%.4s (type %.200s)", - type_name, type_name, Py_TYPE(result)->tp_name); - Py_DECREF(result); - return NULL; -} -static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { -#if CYTHON_USE_TYPE_SLOTS - PyNumberMethods *m; -#endif - const char *name = NULL; - PyObject *res = NULL; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x) || PyLong_Check(x))) -#else - if (likely(PyLong_Check(x))) -#endif - return __Pyx_NewRef(x); -#if CYTHON_USE_TYPE_SLOTS - m = Py_TYPE(x)->tp_as_number; - #if PY_MAJOR_VERSION < 3 - if (m && m->nb_int) { - name = "int"; - res = m->nb_int(x); - } - else if (m && m->nb_long) { - name = "long"; - res = m->nb_long(x); - } - #else - if (likely(m && m->nb_int)) { - name = "int"; - res = m->nb_int(x); - } - #endif -#else - if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { - res = PyNumber_Int(x); - } -#endif - if (likely(res)) { -#if PY_MAJOR_VERSION < 3 - if (unlikely(!PyInt_Check(res) && !PyLong_Check(res))) { -#else - if (unlikely(!PyLong_CheckExact(res))) { -#endif - return __Pyx_PyNumber_IntOrLongWrongResultType(res, name); - } - } - else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, - "an integer is required"); - } - return res; -} -static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { - Py_ssize_t ival; - PyObject *x; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_CheckExact(b))) { - if (sizeof(Py_ssize_t) >= sizeof(long)) - return PyInt_AS_LONG(b); - else - return PyInt_AsSsize_t(b); - } -#endif - if (likely(PyLong_CheckExact(b))) { - #if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)b)->ob_digit; - const Py_ssize_t size = Py_SIZE(b); - if (likely(__Pyx_sst_abs(size) <= 1)) { - ival = likely(size) ? digits[0] : 0; - if (size == -1) ival = -ival; - return ival; - } else { - switch (size) { - case 2: - if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { - return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -2: - if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case 3: - if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { - return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -3: - if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case 4: - if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { - return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -4: - if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - } - } - #endif - return PyLong_AsSsize_t(b); - } - x = PyNumber_Index(b); - if (!x) return -1; - ival = PyInt_AsSsize_t(x); - Py_DECREF(x); - return ival; -} -static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { - return b ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False); -} -static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { - return PyInt_FromSize_t(ival); -} - - -#endif /* Py_PYTHON_H */ diff --git a/.venv/Lib/site-packages/aiohttp/_http_parser.cp38-win_amd64.pyd b/.venv/Lib/site-packages/aiohttp/_http_parser.cp38-win_amd64.pyd deleted file mode 100644 index 4224f72..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/_http_parser.cp38-win_amd64.pyd and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/_http_parser.pyx b/.venv/Lib/site-packages/aiohttp/_http_parser.pyx deleted file mode 100644 index b76d723..0000000 --- a/.venv/Lib/site-packages/aiohttp/_http_parser.pyx +++ /dev/null @@ -1,818 +0,0 @@ -#cython: language_level=3 -# -# Based on https://github.com/MagicStack/httptools -# -from __future__ import absolute_import, print_function - -from cpython cimport ( - Py_buffer, - PyBUF_SIMPLE, - PyBuffer_Release, - PyBytes_AsString, - PyBytes_AsStringAndSize, - PyObject_GetBuffer, -) -from cpython.mem cimport PyMem_Free, PyMem_Malloc -from libc.limits cimport ULLONG_MAX -from libc.string cimport memcpy - -from multidict import CIMultiDict as _CIMultiDict, CIMultiDictProxy as _CIMultiDictProxy -from yarl import URL as _URL - -from aiohttp import hdrs - -from .http_exceptions import ( - BadHttpMessage, - BadStatusLine, - ContentLengthError, - InvalidHeader, - InvalidURLError, - LineTooLong, - PayloadEncodingError, - TransferEncodingError, -) -from .http_parser import DeflateBuffer as _DeflateBuffer -from .http_writer import ( - HttpVersion as _HttpVersion, - HttpVersion10 as _HttpVersion10, - HttpVersion11 as _HttpVersion11, -) -from .streams import EMPTY_PAYLOAD as _EMPTY_PAYLOAD, StreamReader as _StreamReader - -cimport cython - -from aiohttp cimport _cparser as cparser - -include "_headers.pxi" - -from aiohttp cimport _find_header - -DEF DEFAULT_FREELIST_SIZE = 250 - -cdef extern from "Python.h": - int PyByteArray_Resize(object, Py_ssize_t) except -1 - Py_ssize_t PyByteArray_Size(object) except -1 - char* PyByteArray_AsString(object) - -__all__ = ('HttpRequestParser', 'HttpResponseParser', - 'RawRequestMessage', 'RawResponseMessage') - -cdef object URL = _URL -cdef object URL_build = URL.build -cdef object CIMultiDict = _CIMultiDict -cdef object CIMultiDictProxy = _CIMultiDictProxy -cdef object HttpVersion = _HttpVersion -cdef object HttpVersion10 = _HttpVersion10 -cdef object HttpVersion11 = _HttpVersion11 -cdef object SEC_WEBSOCKET_KEY1 = hdrs.SEC_WEBSOCKET_KEY1 -cdef object CONTENT_ENCODING = hdrs.CONTENT_ENCODING -cdef object EMPTY_PAYLOAD = _EMPTY_PAYLOAD -cdef object StreamReader = _StreamReader -cdef object DeflateBuffer = _DeflateBuffer - - -cdef inline object extend(object buf, const char* at, size_t length): - cdef Py_ssize_t s - cdef char* ptr - s = PyByteArray_Size(buf) - PyByteArray_Resize(buf, s + length) - ptr = PyByteArray_AsString(buf) - memcpy(ptr + s, at, length) - - -DEF METHODS_COUNT = 46; - -cdef list _http_method = [] - -for i in range(METHODS_COUNT): - _http_method.append( - cparser.llhttp_method_name( i).decode('ascii')) - - -cdef inline str http_method_str(int i): - if i < METHODS_COUNT: - return _http_method[i] - else: - return "" - -cdef inline object find_header(bytes raw_header): - cdef Py_ssize_t size - cdef char *buf - cdef int idx - PyBytes_AsStringAndSize(raw_header, &buf, &size) - idx = _find_header.find_header(buf, size) - if idx == -1: - return raw_header.decode('utf-8', 'surrogateescape') - return headers[idx] - - -@cython.freelist(DEFAULT_FREELIST_SIZE) -cdef class RawRequestMessage: - cdef readonly str method - cdef readonly str path - cdef readonly object version # HttpVersion - cdef readonly object headers # CIMultiDict - cdef readonly object raw_headers # tuple - cdef readonly object should_close - cdef readonly object compression - cdef readonly object upgrade - cdef readonly object chunked - cdef readonly object url # yarl.URL - - def __init__(self, method, path, version, headers, raw_headers, - should_close, compression, upgrade, chunked, url): - self.method = method - self.path = path - self.version = version - self.headers = headers - self.raw_headers = raw_headers - self.should_close = should_close - self.compression = compression - self.upgrade = upgrade - self.chunked = chunked - self.url = url - - def __repr__(self): - info = [] - info.append(("method", self.method)) - info.append(("path", self.path)) - info.append(("version", self.version)) - info.append(("headers", self.headers)) - info.append(("raw_headers", self.raw_headers)) - info.append(("should_close", self.should_close)) - info.append(("compression", self.compression)) - info.append(("upgrade", self.upgrade)) - info.append(("chunked", self.chunked)) - info.append(("url", self.url)) - sinfo = ', '.join(name + '=' + repr(val) for name, val in info) - return '' - - def _replace(self, **dct): - cdef RawRequestMessage ret - ret = _new_request_message(self.method, - self.path, - self.version, - self.headers, - self.raw_headers, - self.should_close, - self.compression, - self.upgrade, - self.chunked, - self.url) - if "method" in dct: - ret.method = dct["method"] - if "path" in dct: - ret.path = dct["path"] - if "version" in dct: - ret.version = dct["version"] - if "headers" in dct: - ret.headers = dct["headers"] - if "raw_headers" in dct: - ret.raw_headers = dct["raw_headers"] - if "should_close" in dct: - ret.should_close = dct["should_close"] - if "compression" in dct: - ret.compression = dct["compression"] - if "upgrade" in dct: - ret.upgrade = dct["upgrade"] - if "chunked" in dct: - ret.chunked = dct["chunked"] - if "url" in dct: - ret.url = dct["url"] - return ret - -cdef _new_request_message(str method, - str path, - object version, - object headers, - object raw_headers, - bint should_close, - object compression, - bint upgrade, - bint chunked, - object url): - cdef RawRequestMessage ret - ret = RawRequestMessage.__new__(RawRequestMessage) - ret.method = method - ret.path = path - ret.version = version - ret.headers = headers - ret.raw_headers = raw_headers - ret.should_close = should_close - ret.compression = compression - ret.upgrade = upgrade - ret.chunked = chunked - ret.url = url - return ret - - -@cython.freelist(DEFAULT_FREELIST_SIZE) -cdef class RawResponseMessage: - cdef readonly object version # HttpVersion - cdef readonly int code - cdef readonly str reason - cdef readonly object headers # CIMultiDict - cdef readonly object raw_headers # tuple - cdef readonly object should_close - cdef readonly object compression - cdef readonly object upgrade - cdef readonly object chunked - - def __init__(self, version, code, reason, headers, raw_headers, - should_close, compression, upgrade, chunked): - self.version = version - self.code = code - self.reason = reason - self.headers = headers - self.raw_headers = raw_headers - self.should_close = should_close - self.compression = compression - self.upgrade = upgrade - self.chunked = chunked - - def __repr__(self): - info = [] - info.append(("version", self.version)) - info.append(("code", self.code)) - info.append(("reason", self.reason)) - info.append(("headers", self.headers)) - info.append(("raw_headers", self.raw_headers)) - info.append(("should_close", self.should_close)) - info.append(("compression", self.compression)) - info.append(("upgrade", self.upgrade)) - info.append(("chunked", self.chunked)) - sinfo = ', '.join(name + '=' + repr(val) for name, val in info) - return '' - - -cdef _new_response_message(object version, - int code, - str reason, - object headers, - object raw_headers, - bint should_close, - object compression, - bint upgrade, - bint chunked): - cdef RawResponseMessage ret - ret = RawResponseMessage.__new__(RawResponseMessage) - ret.version = version - ret.code = code - ret.reason = reason - ret.headers = headers - ret.raw_headers = raw_headers - ret.should_close = should_close - ret.compression = compression - ret.upgrade = upgrade - ret.chunked = chunked - return ret - - -@cython.internal -cdef class HttpParser: - - cdef: - cparser.llhttp_t* _cparser - cparser.llhttp_settings_t* _csettings - - bytearray _raw_name - bytearray _raw_value - bint _has_value - - object _protocol - object _loop - object _timer - - size_t _max_line_size - size_t _max_field_size - size_t _max_headers - bint _response_with_body - bint _read_until_eof - - bint _started - object _url - bytearray _buf - str _path - str _reason - object _headers - list _raw_headers - bint _upgraded - list _messages - object _payload - bint _payload_error - object _payload_exception - object _last_error - bint _auto_decompress - int _limit - - str _content_encoding - - Py_buffer py_buf - - def __cinit__(self): - self._cparser = \ - PyMem_Malloc(sizeof(cparser.llhttp_t)) - if self._cparser is NULL: - raise MemoryError() - - self._csettings = \ - PyMem_Malloc(sizeof(cparser.llhttp_settings_t)) - if self._csettings is NULL: - raise MemoryError() - - def __dealloc__(self): - PyMem_Free(self._cparser) - PyMem_Free(self._csettings) - - cdef _init( - self, cparser.llhttp_type mode, - object protocol, object loop, int limit, - object timer=None, - size_t max_line_size=8190, size_t max_headers=32768, - size_t max_field_size=8190, payload_exception=None, - bint response_with_body=True, bint read_until_eof=False, - bint auto_decompress=True, - ): - cparser.llhttp_settings_init(self._csettings) - cparser.llhttp_init(self._cparser, mode, self._csettings) - self._cparser.data = self - self._cparser.content_length = 0 - - self._protocol = protocol - self._loop = loop - self._timer = timer - - self._buf = bytearray() - self._payload = None - self._payload_error = 0 - self._payload_exception = payload_exception - self._messages = [] - - self._raw_name = bytearray() - self._raw_value = bytearray() - self._has_value = False - - self._max_line_size = max_line_size - self._max_headers = max_headers - self._max_field_size = max_field_size - self._response_with_body = response_with_body - self._read_until_eof = read_until_eof - self._upgraded = False - self._auto_decompress = auto_decompress - self._content_encoding = None - - self._csettings.on_url = cb_on_url - self._csettings.on_status = cb_on_status - self._csettings.on_header_field = cb_on_header_field - self._csettings.on_header_value = cb_on_header_value - self._csettings.on_headers_complete = cb_on_headers_complete - self._csettings.on_body = cb_on_body - self._csettings.on_message_begin = cb_on_message_begin - self._csettings.on_message_complete = cb_on_message_complete - self._csettings.on_chunk_header = cb_on_chunk_header - self._csettings.on_chunk_complete = cb_on_chunk_complete - - self._last_error = None - self._limit = limit - - cdef _process_header(self): - if self._raw_name: - raw_name = bytes(self._raw_name) - raw_value = bytes(self._raw_value) - - name = find_header(raw_name) - value = raw_value.decode('utf-8', 'surrogateescape') - - self._headers.add(name, value) - - if name is CONTENT_ENCODING: - self._content_encoding = value - - PyByteArray_Resize(self._raw_name, 0) - PyByteArray_Resize(self._raw_value, 0) - self._has_value = False - self._raw_headers.append((raw_name, raw_value)) - - cdef _on_header_field(self, char* at, size_t length): - cdef Py_ssize_t size - cdef char *buf - if self._has_value: - self._process_header() - - size = PyByteArray_Size(self._raw_name) - PyByteArray_Resize(self._raw_name, size + length) - buf = PyByteArray_AsString(self._raw_name) - memcpy(buf + size, at, length) - - cdef _on_header_value(self, char* at, size_t length): - cdef Py_ssize_t size - cdef char *buf - - size = PyByteArray_Size(self._raw_value) - PyByteArray_Resize(self._raw_value, size + length) - buf = PyByteArray_AsString(self._raw_value) - memcpy(buf + size, at, length) - self._has_value = True - - cdef _on_headers_complete(self): - self._process_header() - - method = http_method_str(self._cparser.method) - should_close = not cparser.llhttp_should_keep_alive(self._cparser) - upgrade = self._cparser.upgrade - chunked = self._cparser.flags & cparser.F_CHUNKED - - raw_headers = tuple(self._raw_headers) - headers = CIMultiDictProxy(self._headers) - - if upgrade or self._cparser.method == 5: # cparser.CONNECT: - self._upgraded = True - - # do not support old websocket spec - if SEC_WEBSOCKET_KEY1 in headers: - raise InvalidHeader(SEC_WEBSOCKET_KEY1) - - encoding = None - enc = self._content_encoding - if enc is not None: - self._content_encoding = None - enc = enc.lower() - if enc in ('gzip', 'deflate', 'br'): - encoding = enc - - if self._cparser.type == cparser.HTTP_REQUEST: - msg = _new_request_message( - method, self._path, - self.http_version(), headers, raw_headers, - should_close, encoding, upgrade, chunked, self._url) - else: - msg = _new_response_message( - self.http_version(), self._cparser.status_code, self._reason, - headers, raw_headers, should_close, encoding, - upgrade, chunked) - - if ( - ULLONG_MAX > self._cparser.content_length > 0 or chunked or - self._cparser.method == 5 or # CONNECT: 5 - (self._cparser.status_code >= 199 and - self._cparser.content_length == 0 and - self._read_until_eof) - ): - payload = StreamReader( - self._protocol, timer=self._timer, loop=self._loop, - limit=self._limit) - else: - payload = EMPTY_PAYLOAD - - self._payload = payload - if encoding is not None and self._auto_decompress: - self._payload = DeflateBuffer(payload, encoding) - - if not self._response_with_body: - payload = EMPTY_PAYLOAD - - self._messages.append((msg, payload)) - - cdef _on_message_complete(self): - self._payload.feed_eof() - self._payload = None - - cdef _on_chunk_header(self): - self._payload.begin_http_chunk_receiving() - - cdef _on_chunk_complete(self): - self._payload.end_http_chunk_receiving() - - cdef object _on_status_complete(self): - pass - - cdef inline http_version(self): - cdef cparser.llhttp_t* parser = self._cparser - - if parser.http_major == 1: - if parser.http_minor == 0: - return HttpVersion10 - elif parser.http_minor == 1: - return HttpVersion11 - - return HttpVersion(parser.http_major, parser.http_minor) - - ### Public API ### - - def feed_eof(self): - cdef bytes desc - - if self._payload is not None: - if self._cparser.flags & cparser.F_CHUNKED: - raise TransferEncodingError( - "Not enough data for satisfy transfer length header.") - elif self._cparser.flags & cparser.F_CONTENT_LENGTH: - raise ContentLengthError( - "Not enough data for satisfy content length header.") - elif cparser.llhttp_get_errno(self._cparser) != cparser.HPE_OK: - desc = cparser.llhttp_get_error_reason(self._cparser) - raise PayloadEncodingError(desc.decode('latin-1')) - else: - self._payload.feed_eof() - elif self._started: - self._on_headers_complete() - if self._messages: - return self._messages[-1][0] - - def feed_data(self, data): - cdef: - size_t data_len - size_t nb - cdef cparser.llhttp_errno_t errno - - PyObject_GetBuffer(data, &self.py_buf, PyBUF_SIMPLE) - data_len = self.py_buf.len - - errno = cparser.llhttp_execute( - self._cparser, - self.py_buf.buf, - data_len) - - if errno is cparser.HPE_PAUSED_UPGRADE: - cparser.llhttp_resume_after_upgrade(self._cparser) - - nb = cparser.llhttp_get_error_pos(self._cparser) - self.py_buf.buf - - PyBuffer_Release(&self.py_buf) - - if errno not in (cparser.HPE_OK, cparser.HPE_PAUSED_UPGRADE): - if self._payload_error == 0: - if self._last_error is not None: - ex = self._last_error - self._last_error = None - else: - ex = parser_error_from_errno(self._cparser) - self._payload = None - raise ex - - if self._messages: - messages = self._messages - self._messages = [] - else: - messages = () - - if self._upgraded: - return messages, True, data[nb:] - else: - return messages, False, b'' - - def set_upgraded(self, val): - self._upgraded = val - - -cdef class HttpRequestParser(HttpParser): - - def __init__( - self, protocol, loop, int limit, timer=None, - size_t max_line_size=8190, size_t max_headers=32768, - size_t max_field_size=8190, payload_exception=None, - bint response_with_body=True, bint read_until_eof=False, - bint auto_decompress=True, - ): - self._init(cparser.HTTP_REQUEST, protocol, loop, limit, timer, - max_line_size, max_headers, max_field_size, - payload_exception, response_with_body, read_until_eof, - auto_decompress) - - cdef object _on_status_complete(self): - cdef int idx1, idx2 - if not self._buf: - return - self._path = self._buf.decode('utf-8', 'surrogateescape') - try: - idx3 = len(self._path) - idx1 = self._path.find("?") - if idx1 == -1: - query = "" - idx2 = self._path.find("#") - if idx2 == -1: - path = self._path - fragment = "" - else: - path = self._path[0: idx2] - fragment = self._path[idx2+1:] - - else: - path = self._path[0:idx1] - idx1 += 1 - idx2 = self._path.find("#", idx1+1) - if idx2 == -1: - query = self._path[idx1:] - fragment = "" - else: - query = self._path[idx1: idx2] - fragment = self._path[idx2+1:] - - self._url = URL.build( - path=path, - query_string=query, - fragment=fragment, - encoded=True, - ) - finally: - PyByteArray_Resize(self._buf, 0) - - -cdef class HttpResponseParser(HttpParser): - - def __init__( - self, protocol, loop, int limit, timer=None, - size_t max_line_size=8190, size_t max_headers=32768, - size_t max_field_size=8190, payload_exception=None, - bint response_with_body=True, bint read_until_eof=False, - bint auto_decompress=True - ): - self._init(cparser.HTTP_RESPONSE, protocol, loop, limit, timer, - max_line_size, max_headers, max_field_size, - payload_exception, response_with_body, read_until_eof, - auto_decompress) - - cdef object _on_status_complete(self): - if self._buf: - self._reason = self._buf.decode('utf-8', 'surrogateescape') - PyByteArray_Resize(self._buf, 0) - else: - self._reason = self._reason or '' - -cdef int cb_on_message_begin(cparser.llhttp_t* parser) except -1: - cdef HttpParser pyparser = parser.data - - pyparser._started = True - pyparser._headers = CIMultiDict() - pyparser._raw_headers = [] - PyByteArray_Resize(pyparser._buf, 0) - pyparser._path = None - pyparser._reason = None - return 0 - - -cdef int cb_on_url(cparser.llhttp_t* parser, - const char *at, size_t length) except -1: - cdef HttpParser pyparser = parser.data - try: - if length > pyparser._max_line_size: - raise LineTooLong( - 'Status line is too long', pyparser._max_line_size, length) - extend(pyparser._buf, at, length) - except BaseException as ex: - pyparser._last_error = ex - return -1 - else: - return 0 - - -cdef int cb_on_status(cparser.llhttp_t* parser, - const char *at, size_t length) except -1: - cdef HttpParser pyparser = parser.data - cdef str reason - try: - if length > pyparser._max_line_size: - raise LineTooLong( - 'Status line is too long', pyparser._max_line_size, length) - extend(pyparser._buf, at, length) - except BaseException as ex: - pyparser._last_error = ex - return -1 - else: - return 0 - - -cdef int cb_on_header_field(cparser.llhttp_t* parser, - const char *at, size_t length) except -1: - cdef HttpParser pyparser = parser.data - cdef Py_ssize_t size - try: - pyparser._on_status_complete() - size = len(pyparser._raw_name) + length - if size > pyparser._max_field_size: - raise LineTooLong( - 'Header name is too long', pyparser._max_field_size, size) - pyparser._on_header_field(at, length) - except BaseException as ex: - pyparser._last_error = ex - return -1 - else: - return 0 - - -cdef int cb_on_header_value(cparser.llhttp_t* parser, - const char *at, size_t length) except -1: - cdef HttpParser pyparser = parser.data - cdef Py_ssize_t size - try: - size = len(pyparser._raw_value) + length - if size > pyparser._max_field_size: - raise LineTooLong( - 'Header value is too long', pyparser._max_field_size, size) - pyparser._on_header_value(at, length) - except BaseException as ex: - pyparser._last_error = ex - return -1 - else: - return 0 - - -cdef int cb_on_headers_complete(cparser.llhttp_t* parser) except -1: - cdef HttpParser pyparser = parser.data - try: - pyparser._on_status_complete() - pyparser._on_headers_complete() - except BaseException as exc: - pyparser._last_error = exc - return -1 - else: - if pyparser._cparser.upgrade or pyparser._cparser.method == 5: # CONNECT - return 2 - else: - return 0 - - -cdef int cb_on_body(cparser.llhttp_t* parser, - const char *at, size_t length) except -1: - cdef HttpParser pyparser = parser.data - cdef bytes body = at[:length] - try: - pyparser._payload.feed_data(body, length) - except BaseException as exc: - if pyparser._payload_exception is not None: - pyparser._payload.set_exception(pyparser._payload_exception(str(exc))) - else: - pyparser._payload.set_exception(exc) - pyparser._payload_error = 1 - return -1 - else: - return 0 - - -cdef int cb_on_message_complete(cparser.llhttp_t* parser) except -1: - cdef HttpParser pyparser = parser.data - try: - pyparser._started = False - pyparser._on_message_complete() - except BaseException as exc: - pyparser._last_error = exc - return -1 - else: - return 0 - - -cdef int cb_on_chunk_header(cparser.llhttp_t* parser) except -1: - cdef HttpParser pyparser = parser.data - try: - pyparser._on_chunk_header() - except BaseException as exc: - pyparser._last_error = exc - return -1 - else: - return 0 - - -cdef int cb_on_chunk_complete(cparser.llhttp_t* parser) except -1: - cdef HttpParser pyparser = parser.data - try: - pyparser._on_chunk_complete() - except BaseException as exc: - pyparser._last_error = exc - return -1 - else: - return 0 - - -cdef parser_error_from_errno(cparser.llhttp_t* parser): - cdef cparser.llhttp_errno_t errno = cparser.llhttp_get_errno(parser) - cdef bytes desc = cparser.llhttp_get_error_reason(parser) - - if errno in (cparser.HPE_CB_MESSAGE_BEGIN, - cparser.HPE_CB_HEADERS_COMPLETE, - cparser.HPE_CB_MESSAGE_COMPLETE, - cparser.HPE_CB_CHUNK_HEADER, - cparser.HPE_CB_CHUNK_COMPLETE, - cparser.HPE_INVALID_CONSTANT, - cparser.HPE_INVALID_HEADER_TOKEN, - cparser.HPE_INVALID_CONTENT_LENGTH, - cparser.HPE_INVALID_CHUNK_SIZE, - cparser.HPE_INVALID_EOF_STATE, - cparser.HPE_INVALID_TRANSFER_ENCODING): - cls = BadHttpMessage - - elif errno == cparser.HPE_INVALID_STATUS: - cls = BadStatusLine - - elif errno == cparser.HPE_INVALID_METHOD: - cls = BadStatusLine - - elif errno == cparser.HPE_INVALID_VERSION: - cls = BadStatusLine - - elif errno == cparser.HPE_INVALID_URL: - cls = InvalidURLError - - else: - cls = BadHttpMessage - - return cls(desc.decode('latin-1')) diff --git a/.venv/Lib/site-packages/aiohttp/_http_writer.c b/.venv/Lib/site-packages/aiohttp/_http_writer.c deleted file mode 100644 index 07fd03e..0000000 --- a/.venv/Lib/site-packages/aiohttp/_http_writer.c +++ /dev/null @@ -1,6047 +0,0 @@ -/* Generated by Cython 0.29.24 */ - -#ifndef PY_SSIZE_T_CLEAN -#define PY_SSIZE_T_CLEAN -#endif /* PY_SSIZE_T_CLEAN */ -#include "Python.h" -#ifndef Py_PYTHON_H - #error Python headers needed to compile C extensions, please install development version of Python. -#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03030000) - #error Cython requires Python 2.6+ or Python 3.3+. -#else -#define CYTHON_ABI "0_29_24" -#define CYTHON_HEX_VERSION 0x001D18F0 -#define CYTHON_FUTURE_DIVISION 1 -#include -#ifndef offsetof - #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) -#endif -#if !defined(WIN32) && !defined(MS_WINDOWS) - #ifndef __stdcall - #define __stdcall - #endif - #ifndef __cdecl - #define __cdecl - #endif - #ifndef __fastcall - #define __fastcall - #endif -#endif -#ifndef DL_IMPORT - #define DL_IMPORT(t) t -#endif -#ifndef DL_EXPORT - #define DL_EXPORT(t) t -#endif -#define __PYX_COMMA , -#ifndef HAVE_LONG_LONG - #if PY_VERSION_HEX >= 0x02070000 - #define HAVE_LONG_LONG - #endif -#endif -#ifndef PY_LONG_LONG - #define PY_LONG_LONG LONG_LONG -#endif -#ifndef Py_HUGE_VAL - #define Py_HUGE_VAL HUGE_VAL -#endif -#ifdef PYPY_VERSION - #define CYTHON_COMPILING_IN_PYPY 1 - #define CYTHON_COMPILING_IN_PYSTON 0 - #define CYTHON_COMPILING_IN_CPYTHON 0 - #undef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 0 - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #if PY_VERSION_HEX < 0x03050000 - #undef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 0 - #elif !defined(CYTHON_USE_ASYNC_SLOTS) - #define CYTHON_USE_ASYNC_SLOTS 1 - #endif - #undef CYTHON_USE_PYLIST_INTERNALS - #define CYTHON_USE_PYLIST_INTERNALS 0 - #undef CYTHON_USE_UNICODE_INTERNALS - #define CYTHON_USE_UNICODE_INTERNALS 0 - #undef CYTHON_USE_UNICODE_WRITER - #define CYTHON_USE_UNICODE_WRITER 0 - #undef CYTHON_USE_PYLONG_INTERNALS - #define CYTHON_USE_PYLONG_INTERNALS 0 - #undef CYTHON_AVOID_BORROWED_REFS - #define CYTHON_AVOID_BORROWED_REFS 1 - #undef CYTHON_ASSUME_SAFE_MACROS - #define CYTHON_ASSUME_SAFE_MACROS 0 - #undef CYTHON_UNPACK_METHODS - #define CYTHON_UNPACK_METHODS 0 - #undef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 0 - #undef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL 0 - #undef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT 0 - #undef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE 0 - #undef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS 0 - #undef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK 0 -#elif defined(PYSTON_VERSION) - #define CYTHON_COMPILING_IN_PYPY 0 - #define CYTHON_COMPILING_IN_PYSTON 1 - #define CYTHON_COMPILING_IN_CPYTHON 0 - #ifndef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 1 - #endif - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #undef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 0 - #undef CYTHON_USE_PYLIST_INTERNALS - #define CYTHON_USE_PYLIST_INTERNALS 0 - #ifndef CYTHON_USE_UNICODE_INTERNALS - #define CYTHON_USE_UNICODE_INTERNALS 1 - #endif - #undef CYTHON_USE_UNICODE_WRITER - #define CYTHON_USE_UNICODE_WRITER 0 - #undef CYTHON_USE_PYLONG_INTERNALS - #define CYTHON_USE_PYLONG_INTERNALS 0 - #ifndef CYTHON_AVOID_BORROWED_REFS - #define CYTHON_AVOID_BORROWED_REFS 0 - #endif - #ifndef CYTHON_ASSUME_SAFE_MACROS - #define CYTHON_ASSUME_SAFE_MACROS 1 - #endif - #ifndef CYTHON_UNPACK_METHODS - #define CYTHON_UNPACK_METHODS 1 - #endif - #undef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 0 - #undef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL 0 - #undef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT 0 - #undef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE 0 - #undef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS 0 - #undef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK 0 -#else - #define CYTHON_COMPILING_IN_PYPY 0 - #define CYTHON_COMPILING_IN_PYSTON 0 - #define CYTHON_COMPILING_IN_CPYTHON 1 - #ifndef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 1 - #endif - #if PY_VERSION_HEX < 0x02070000 - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #elif !defined(CYTHON_USE_PYTYPE_LOOKUP) - #define CYTHON_USE_PYTYPE_LOOKUP 1 - #endif - #if PY_MAJOR_VERSION < 3 - #undef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 0 - #elif !defined(CYTHON_USE_ASYNC_SLOTS) - #define CYTHON_USE_ASYNC_SLOTS 1 - #endif - #if PY_VERSION_HEX < 0x02070000 - #undef CYTHON_USE_PYLONG_INTERNALS - #define CYTHON_USE_PYLONG_INTERNALS 0 - #elif !defined(CYTHON_USE_PYLONG_INTERNALS) - #define CYTHON_USE_PYLONG_INTERNALS 1 - #endif - #ifndef CYTHON_USE_PYLIST_INTERNALS - #define CYTHON_USE_PYLIST_INTERNALS 1 - #endif - #ifndef CYTHON_USE_UNICODE_INTERNALS - #define CYTHON_USE_UNICODE_INTERNALS 1 - #endif - #if PY_VERSION_HEX < 0x030300F0 - #undef CYTHON_USE_UNICODE_WRITER - #define CYTHON_USE_UNICODE_WRITER 0 - #elif !defined(CYTHON_USE_UNICODE_WRITER) - #define CYTHON_USE_UNICODE_WRITER 1 - #endif - #ifndef CYTHON_AVOID_BORROWED_REFS - #define CYTHON_AVOID_BORROWED_REFS 0 - #endif - #ifndef CYTHON_ASSUME_SAFE_MACROS - #define CYTHON_ASSUME_SAFE_MACROS 1 - #endif - #ifndef CYTHON_UNPACK_METHODS - #define CYTHON_UNPACK_METHODS 1 - #endif - #ifndef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 1 - #endif - #ifndef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL 1 - #endif - #ifndef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT (PY_VERSION_HEX >= 0x03050000) - #endif - #ifndef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE (PY_VERSION_HEX >= 0x030400a1) - #endif - #ifndef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX >= 0x030600B1) - #endif - #ifndef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK (PY_VERSION_HEX >= 0x030700A3) - #endif -#endif -#if !defined(CYTHON_FAST_PYCCALL) -#define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) -#endif -#if CYTHON_USE_PYLONG_INTERNALS - #include "longintrepr.h" - #undef SHIFT - #undef BASE - #undef MASK - #ifdef SIZEOF_VOID_P - enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; - #endif -#endif -#ifndef __has_attribute - #define __has_attribute(x) 0 -#endif -#ifndef __has_cpp_attribute - #define __has_cpp_attribute(x) 0 -#endif -#ifndef CYTHON_RESTRICT - #if defined(__GNUC__) - #define CYTHON_RESTRICT __restrict__ - #elif defined(_MSC_VER) && _MSC_VER >= 1400 - #define CYTHON_RESTRICT __restrict - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_RESTRICT restrict - #else - #define CYTHON_RESTRICT - #endif -#endif -#ifndef CYTHON_UNUSED -# if defined(__GNUC__) -# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) -# define CYTHON_UNUSED __attribute__ ((__unused__)) -# else -# define CYTHON_UNUSED -# endif -# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) -# define CYTHON_UNUSED __attribute__ ((__unused__)) -# else -# define CYTHON_UNUSED -# endif -#endif -#ifndef CYTHON_MAYBE_UNUSED_VAR -# if defined(__cplusplus) - template void CYTHON_MAYBE_UNUSED_VAR( const T& ) { } -# else -# define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x) -# endif -#endif -#ifndef CYTHON_NCP_UNUSED -# if CYTHON_COMPILING_IN_CPYTHON -# define CYTHON_NCP_UNUSED -# else -# define CYTHON_NCP_UNUSED CYTHON_UNUSED -# endif -#endif -#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) -#ifdef _MSC_VER - #ifndef _MSC_STDINT_H_ - #if _MSC_VER < 1300 - typedef unsigned char uint8_t; - typedef unsigned int uint32_t; - #else - typedef unsigned __int8 uint8_t; - typedef unsigned __int32 uint32_t; - #endif - #endif -#else - #include -#endif -#ifndef CYTHON_FALLTHROUGH - #if defined(__cplusplus) && __cplusplus >= 201103L - #if __has_cpp_attribute(fallthrough) - #define CYTHON_FALLTHROUGH [[fallthrough]] - #elif __has_cpp_attribute(clang::fallthrough) - #define CYTHON_FALLTHROUGH [[clang::fallthrough]] - #elif __has_cpp_attribute(gnu::fallthrough) - #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] - #endif - #endif - #ifndef CYTHON_FALLTHROUGH - #if __has_attribute(fallthrough) - #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) - #else - #define CYTHON_FALLTHROUGH - #endif - #endif - #if defined(__clang__ ) && defined(__apple_build_version__) - #if __apple_build_version__ < 7000000 - #undef CYTHON_FALLTHROUGH - #define CYTHON_FALLTHROUGH - #endif - #endif -#endif - -#ifndef CYTHON_INLINE - #if defined(__clang__) - #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) - #elif defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline - #else - #define CYTHON_INLINE - #endif -#endif - -#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) - #define Py_OptimizeFlag 0 -#endif -#define __PYX_BUILD_PY_SSIZE_T "n" -#define CYTHON_FORMAT_SSIZE_T "z" -#if PY_MAJOR_VERSION < 3 - #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) - #define __Pyx_DefaultClassType PyClass_Type -#else - #define __Pyx_BUILTIN_MODULE_NAME "builtins" -#if PY_VERSION_HEX >= 0x030800A4 && PY_VERSION_HEX < 0x030800B2 - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a, 0, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) -#else - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) -#endif - #define __Pyx_DefaultClassType PyType_Type -#endif -#ifndef Py_TPFLAGS_CHECKTYPES - #define Py_TPFLAGS_CHECKTYPES 0 -#endif -#ifndef Py_TPFLAGS_HAVE_INDEX - #define Py_TPFLAGS_HAVE_INDEX 0 -#endif -#ifndef Py_TPFLAGS_HAVE_NEWBUFFER - #define Py_TPFLAGS_HAVE_NEWBUFFER 0 -#endif -#ifndef Py_TPFLAGS_HAVE_FINALIZE - #define Py_TPFLAGS_HAVE_FINALIZE 0 -#endif -#ifndef METH_STACKLESS - #define METH_STACKLESS 0 -#endif -#if PY_VERSION_HEX <= 0x030700A3 || !defined(METH_FASTCALL) - #ifndef METH_FASTCALL - #define METH_FASTCALL 0x80 - #endif - typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); - typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, - Py_ssize_t nargs, PyObject *kwnames); -#else - #define __Pyx_PyCFunctionFast _PyCFunctionFast - #define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords -#endif -#if CYTHON_FAST_PYCCALL -#define __Pyx_PyFastCFunction_Check(func)\ - ((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))))) -#else -#define __Pyx_PyFastCFunction_Check(func) 0 -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) - #define PyObject_Malloc(s) PyMem_Malloc(s) - #define PyObject_Free(p) PyMem_Free(p) - #define PyObject_Realloc(p) PyMem_Realloc(p) -#endif -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030400A1 - #define PyMem_RawMalloc(n) PyMem_Malloc(n) - #define PyMem_RawRealloc(p, n) PyMem_Realloc(p, n) - #define PyMem_RawFree(p) PyMem_Free(p) -#endif -#if CYTHON_COMPILING_IN_PYSTON - #define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co) - #define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno) -#else - #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) - #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) -#endif -#if !CYTHON_FAST_THREAD_STATE || PY_VERSION_HEX < 0x02070000 - #define __Pyx_PyThreadState_Current PyThreadState_GET() -#elif PY_VERSION_HEX >= 0x03060000 - #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() -#elif PY_VERSION_HEX >= 0x03000000 - #define __Pyx_PyThreadState_Current PyThreadState_GET() -#else - #define __Pyx_PyThreadState_Current _PyThreadState_Current -#endif -#if PY_VERSION_HEX < 0x030700A2 && !defined(PyThread_tss_create) && !defined(Py_tss_NEEDS_INIT) -#include "pythread.h" -#define Py_tss_NEEDS_INIT 0 -typedef int Py_tss_t; -static CYTHON_INLINE int PyThread_tss_create(Py_tss_t *key) { - *key = PyThread_create_key(); - return 0; -} -static CYTHON_INLINE Py_tss_t * PyThread_tss_alloc(void) { - Py_tss_t *key = (Py_tss_t *)PyObject_Malloc(sizeof(Py_tss_t)); - *key = Py_tss_NEEDS_INIT; - return key; -} -static CYTHON_INLINE void PyThread_tss_free(Py_tss_t *key) { - PyObject_Free(key); -} -static CYTHON_INLINE int PyThread_tss_is_created(Py_tss_t *key) { - return *key != Py_tss_NEEDS_INIT; -} -static CYTHON_INLINE void PyThread_tss_delete(Py_tss_t *key) { - PyThread_delete_key(*key); - *key = Py_tss_NEEDS_INIT; -} -static CYTHON_INLINE int PyThread_tss_set(Py_tss_t *key, void *value) { - return PyThread_set_key_value(*key, value); -} -static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) { - return PyThread_get_key_value(*key); -} -#endif -#if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) -#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) -#else -#define __Pyx_PyDict_NewPresized(n) PyDict_New() -#endif -#if PY_MAJOR_VERSION >= 3 || CYTHON_FUTURE_DIVISION - #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) -#else - #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) -#endif -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 && CYTHON_USE_UNICODE_INTERNALS -#define __Pyx_PyDict_GetItemStr(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) -#else -#define __Pyx_PyDict_GetItemStr(dict, name) PyDict_GetItem(dict, name) -#endif -#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) - #define CYTHON_PEP393_ENABLED 1 - #if defined(PyUnicode_IS_READY) - #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ - 0 : _PyUnicode_Ready((PyObject *)(op))) - #else - #define __Pyx_PyUnicode_READY(op) (0) - #endif - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) - #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) - #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) - #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) - #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) - #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) - #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch) - #if defined(PyUnicode_IS_READY) && defined(PyUnicode_GET_SIZE) - #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03090000 - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : ((PyCompactUnicodeObject *)(u))->wstr_length)) - #else - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) - #endif - #else - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) - #endif -#else - #define CYTHON_PEP393_ENABLED 0 - #define PyUnicode_1BYTE_KIND 1 - #define PyUnicode_2BYTE_KIND 2 - #define PyUnicode_4BYTE_KIND 4 - #define __Pyx_PyUnicode_READY(op) (0) - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) - #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) - #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111) - #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) - #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) - #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) - #define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch) - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) -#endif -#if CYTHON_COMPILING_IN_PYPY - #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) - #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) -#else - #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) - #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ - PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains) - #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check) - #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format) - #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) -#endif -#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyString_Check(b) && !PyString_CheckExact(b)))) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) -#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) -#else - #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) -#endif -#if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII) - #define PyObject_ASCII(o) PyObject_Repr(o) -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyBaseString_Type PyUnicode_Type - #define PyStringObject PyUnicodeObject - #define PyString_Type PyUnicode_Type - #define PyString_Check PyUnicode_Check - #define PyString_CheckExact PyUnicode_CheckExact -#ifndef PyObject_Unicode - #define PyObject_Unicode PyObject_Str -#endif -#endif -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) - #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) -#else - #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) - #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) -#endif -#ifndef PySet_CheckExact - #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) -#endif -#if PY_VERSION_HEX >= 0x030900A4 - #define __Pyx_SET_REFCNT(obj, refcnt) Py_SET_REFCNT(obj, refcnt) - #define __Pyx_SET_SIZE(obj, size) Py_SET_SIZE(obj, size) -#else - #define __Pyx_SET_REFCNT(obj, refcnt) Py_REFCNT(obj) = (refcnt) - #define __Pyx_SET_SIZE(obj, size) Py_SIZE(obj) = (size) -#endif -#if CYTHON_ASSUME_SAFE_MACROS - #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) -#else - #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyIntObject PyLongObject - #define PyInt_Type PyLong_Type - #define PyInt_Check(op) PyLong_Check(op) - #define PyInt_CheckExact(op) PyLong_CheckExact(op) - #define PyInt_FromString PyLong_FromString - #define PyInt_FromUnicode PyLong_FromUnicode - #define PyInt_FromLong PyLong_FromLong - #define PyInt_FromSize_t PyLong_FromSize_t - #define PyInt_FromSsize_t PyLong_FromSsize_t - #define PyInt_AsLong PyLong_AsLong - #define PyInt_AS_LONG PyLong_AS_LONG - #define PyInt_AsSsize_t PyLong_AsSsize_t - #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask - #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask - #define PyNumber_Int PyNumber_Long -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyBoolObject PyLongObject -#endif -#if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY - #ifndef PyUnicode_InternFromString - #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) - #endif -#endif -#if PY_VERSION_HEX < 0x030200A4 - typedef long Py_hash_t; - #define __Pyx_PyInt_FromHash_t PyInt_FromLong - #define __Pyx_PyInt_AsHash_t PyInt_AsLong -#else - #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t - #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t -#endif -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyMethod_New(func, self, klass) ((self) ? ((void)(klass), PyMethod_New(func, self)) : __Pyx_NewRef(func)) -#else - #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) -#endif -#if CYTHON_USE_ASYNC_SLOTS - #if PY_VERSION_HEX >= 0x030500B1 - #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods - #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) - #else - #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) - #endif -#else - #define __Pyx_PyType_AsAsync(obj) NULL -#endif -#ifndef __Pyx_PyAsyncMethodsStruct - typedef struct { - unaryfunc am_await; - unaryfunc am_aiter; - unaryfunc am_anext; - } __Pyx_PyAsyncMethodsStruct; -#endif - -#if defined(WIN32) || defined(MS_WINDOWS) - #define _USE_MATH_DEFINES -#endif -#include -#ifdef NAN -#define __PYX_NAN() ((float) NAN) -#else -static CYTHON_INLINE float __PYX_NAN() { - float value; - memset(&value, 0xFF, sizeof(value)); - return value; -} -#endif -#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) -#define __Pyx_truncl trunc -#else -#define __Pyx_truncl truncl -#endif - -#define __PYX_MARK_ERR_POS(f_index, lineno) \ - { __pyx_filename = __pyx_f[f_index]; (void)__pyx_filename; __pyx_lineno = lineno; (void)__pyx_lineno; __pyx_clineno = __LINE__; (void)__pyx_clineno; } -#define __PYX_ERR(f_index, lineno, Ln_error) \ - { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; } - -#ifndef __PYX_EXTERN_C - #ifdef __cplusplus - #define __PYX_EXTERN_C extern "C" - #else - #define __PYX_EXTERN_C extern - #endif -#endif - -#define __PYX_HAVE__aiohttp___http_writer -#define __PYX_HAVE_API__aiohttp___http_writer -/* Early includes */ -#include -#include -#include -#ifdef _OPENMP -#include -#endif /* _OPENMP */ - -#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) -#define CYTHON_WITHOUT_ASSERTIONS -#endif - -typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding; - const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; - -#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 -#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0 -#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT (PY_MAJOR_VERSION >= 3 && __PYX_DEFAULT_STRING_ENCODING_IS_UTF8) -#define __PYX_DEFAULT_STRING_ENCODING "" -#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString -#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize -#define __Pyx_uchar_cast(c) ((unsigned char)c) -#define __Pyx_long_cast(x) ((long)x) -#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ - (sizeof(type) < sizeof(Py_ssize_t)) ||\ - (sizeof(type) > sizeof(Py_ssize_t) &&\ - likely(v < (type)PY_SSIZE_T_MAX ||\ - v == (type)PY_SSIZE_T_MAX) &&\ - (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ - v == (type)PY_SSIZE_T_MIN))) ||\ - (sizeof(type) == sizeof(Py_ssize_t) &&\ - (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ - v == (type)PY_SSIZE_T_MAX))) ) -static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { - return (size_t) i < (size_t) limit; -} -#if defined (__cplusplus) && __cplusplus >= 201103L - #include - #define __Pyx_sst_abs(value) std::abs(value) -#elif SIZEOF_INT >= SIZEOF_SIZE_T - #define __Pyx_sst_abs(value) abs(value) -#elif SIZEOF_LONG >= SIZEOF_SIZE_T - #define __Pyx_sst_abs(value) labs(value) -#elif defined (_MSC_VER) - #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) -#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define __Pyx_sst_abs(value) llabs(value) -#elif defined (__GNUC__) - #define __Pyx_sst_abs(value) __builtin_llabs(value) -#else - #define __Pyx_sst_abs(value) ((value<0) ? -value : value) -#endif -static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); -static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); -#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) -#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) -#define __Pyx_PyBytes_FromString PyBytes_FromString -#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); -#if PY_MAJOR_VERSION < 3 - #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString - #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize -#else - #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString - #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize -#endif -#define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyObject_AsWritableString(s) ((char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsWritableSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) -#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) -#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) -#define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) -#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) -static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) { - const Py_UNICODE *u_end = u; - while (*u_end++) ; - return (size_t)(u_end - u - 1); -} -#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) -#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode -#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode -#define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) -#define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) -static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); -static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); -static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); -static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); -#define __Pyx_PySequence_Tuple(obj)\ - (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) -static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); -static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); -#if CYTHON_ASSUME_SAFE_MACROS -#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) -#else -#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) -#endif -#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) -#if PY_MAJOR_VERSION >= 3 -#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) -#else -#define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x)) -#endif -#define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x)) -#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII -static int __Pyx_sys_getdefaultencoding_not_ascii; -static int __Pyx_init_sys_getdefaultencoding_params(void) { - PyObject* sys; - PyObject* default_encoding = NULL; - PyObject* ascii_chars_u = NULL; - PyObject* ascii_chars_b = NULL; - const char* default_encoding_c; - sys = PyImport_ImportModule("sys"); - if (!sys) goto bad; - default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); - Py_DECREF(sys); - if (!default_encoding) goto bad; - default_encoding_c = PyBytes_AsString(default_encoding); - if (!default_encoding_c) goto bad; - if (strcmp(default_encoding_c, "ascii") == 0) { - __Pyx_sys_getdefaultencoding_not_ascii = 0; - } else { - char ascii_chars[128]; - int c; - for (c = 0; c < 128; c++) { - ascii_chars[c] = c; - } - __Pyx_sys_getdefaultencoding_not_ascii = 1; - ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); - if (!ascii_chars_u) goto bad; - ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); - if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { - PyErr_Format( - PyExc_ValueError, - "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", - default_encoding_c); - goto bad; - } - Py_DECREF(ascii_chars_u); - Py_DECREF(ascii_chars_b); - } - Py_DECREF(default_encoding); - return 0; -bad: - Py_XDECREF(default_encoding); - Py_XDECREF(ascii_chars_u); - Py_XDECREF(ascii_chars_b); - return -1; -} -#endif -#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 -#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) -#else -#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) -#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT -static char* __PYX_DEFAULT_STRING_ENCODING; -static int __Pyx_init_sys_getdefaultencoding_params(void) { - PyObject* sys; - PyObject* default_encoding = NULL; - char* default_encoding_c; - sys = PyImport_ImportModule("sys"); - if (!sys) goto bad; - default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); - Py_DECREF(sys); - if (!default_encoding) goto bad; - default_encoding_c = PyBytes_AsString(default_encoding); - if (!default_encoding_c) goto bad; - __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c) + 1); - if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; - strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); - Py_DECREF(default_encoding); - return 0; -bad: - Py_XDECREF(default_encoding); - return -1; -} -#endif -#endif - - -/* Test for GCC > 2.95 */ -#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) - #define likely(x) __builtin_expect(!!(x), 1) - #define unlikely(x) __builtin_expect(!!(x), 0) -#else /* !__GNUC__ or GCC < 2.95 */ - #define likely(x) (x) - #define unlikely(x) (x) -#endif /* __GNUC__ */ -static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } - -static PyObject *__pyx_m = NULL; -static PyObject *__pyx_d; -static PyObject *__pyx_b; -static PyObject *__pyx_cython_runtime = NULL; -static PyObject *__pyx_empty_tuple; -static PyObject *__pyx_empty_bytes; -static PyObject *__pyx_empty_unicode; -static int __pyx_lineno; -static int __pyx_clineno = 0; -static const char * __pyx_cfilenm= __FILE__; -static const char *__pyx_filename; - - -static const char *__pyx_f[] = { - "aiohttp\\_http_writer.pyx", - "type.pxd", -}; - -/*--- Type declarations ---*/ -struct __pyx_t_7aiohttp_12_http_writer_Writer; - -/* "aiohttp/_http_writer.pyx":18 - * # ----------------- writer --------------------------- - * - * cdef struct Writer: # <<<<<<<<<<<<<< - * char *buf - * Py_ssize_t size - */ -struct __pyx_t_7aiohttp_12_http_writer_Writer { - char *buf; - Py_ssize_t size; - Py_ssize_t pos; -}; - -/* --- Runtime support code (head) --- */ -/* Refnanny.proto */ -#ifndef CYTHON_REFNANNY - #define CYTHON_REFNANNY 0 -#endif -#if CYTHON_REFNANNY - typedef struct { - void (*INCREF)(void*, PyObject*, int); - void (*DECREF)(void*, PyObject*, int); - void (*GOTREF)(void*, PyObject*, int); - void (*GIVEREF)(void*, PyObject*, int); - void* (*SetupContext)(const char*, int, const char*); - void (*FinishContext)(void**); - } __Pyx_RefNannyAPIStruct; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); - #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; -#ifdef WITH_THREAD - #define __Pyx_RefNannySetupContext(name, acquire_gil)\ - if (acquire_gil) {\ - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ - PyGILState_Release(__pyx_gilstate_save);\ - } else {\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ - } -#else - #define __Pyx_RefNannySetupContext(name, acquire_gil)\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) -#endif - #define __Pyx_RefNannyFinishContext()\ - __Pyx_RefNanny->FinishContext(&__pyx_refnanny) - #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) - #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) - #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) - #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) -#else - #define __Pyx_RefNannyDeclarations - #define __Pyx_RefNannySetupContext(name, acquire_gil) - #define __Pyx_RefNannyFinishContext() - #define __Pyx_INCREF(r) Py_INCREF(r) - #define __Pyx_DECREF(r) Py_DECREF(r) - #define __Pyx_GOTREF(r) - #define __Pyx_GIVEREF(r) - #define __Pyx_XINCREF(r) Py_XINCREF(r) - #define __Pyx_XDECREF(r) Py_XDECREF(r) - #define __Pyx_XGOTREF(r) - #define __Pyx_XGIVEREF(r) -#endif -#define __Pyx_XDECREF_SET(r, v) do {\ - PyObject *tmp = (PyObject *) r;\ - r = v; __Pyx_XDECREF(tmp);\ - } while (0) -#define __Pyx_DECREF_SET(r, v) do {\ - PyObject *tmp = (PyObject *) r;\ - r = v; __Pyx_DECREF(tmp);\ - } while (0) -#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) -#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) - -/* PyObjectGetAttrStr.proto */ -#if CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); -#else -#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) -#endif - -/* GetBuiltinName.proto */ -static PyObject *__Pyx_GetBuiltinName(PyObject *name); - -/* PyThreadStateGet.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; -#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; -#define __Pyx_PyErr_Occurred() __pyx_tstate->curexc_type -#else -#define __Pyx_PyThreadState_declare -#define __Pyx_PyThreadState_assign -#define __Pyx_PyErr_Occurred() PyErr_Occurred() -#endif - -/* PyErrFetchRestore.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) -#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) -#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) -#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) -#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); -static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#if CYTHON_COMPILING_IN_CPYTHON -#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) -#else -#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) -#endif -#else -#define __Pyx_PyErr_Clear() PyErr_Clear() -#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) -#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) -#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) -#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) -#endif - -/* WriteUnraisableException.proto */ -static void __Pyx_WriteUnraisable(const char *name, int clineno, - int lineno, const char *filename, - int full_traceback, int nogil); - -/* unicode_iter.proto */ -static CYTHON_INLINE int __Pyx_init_unicode_iteration( - PyObject* ustring, Py_ssize_t *length, void** data, int *kind); - -/* PyCFunctionFastCall.proto */ -#if CYTHON_FAST_PYCCALL -static CYTHON_INLINE PyObject *__Pyx_PyCFunction_FastCall(PyObject *func, PyObject **args, Py_ssize_t nargs); -#else -#define __Pyx_PyCFunction_FastCall(func, args, nargs) (assert(0), NULL) -#endif - -/* PyFunctionFastCall.proto */ -#if CYTHON_FAST_PYCALL -#define __Pyx_PyFunction_FastCall(func, args, nargs)\ - __Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL) -#if 1 || PY_VERSION_HEX < 0x030600B1 -static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs); -#else -#define __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs) _PyFunction_FastCallDict(func, args, nargs, kwargs) -#endif -#define __Pyx_BUILD_ASSERT_EXPR(cond)\ - (sizeof(char [1 - 2*!(cond)]) - 1) -#ifndef Py_MEMBER_SIZE -#define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member) -#endif - static size_t __pyx_pyframe_localsplus_offset = 0; - #include "frameobject.h" - #define __Pxy_PyFrame_Initialize_Offsets()\ - ((void)__Pyx_BUILD_ASSERT_EXPR(sizeof(PyFrameObject) == offsetof(PyFrameObject, f_localsplus) + Py_MEMBER_SIZE(PyFrameObject, f_localsplus)),\ - (void)(__pyx_pyframe_localsplus_offset = ((size_t)PyFrame_Type.tp_basicsize) - Py_MEMBER_SIZE(PyFrameObject, f_localsplus))) - #define __Pyx_PyFrame_GetLocalsplus(frame)\ - (assert(__pyx_pyframe_localsplus_offset), (PyObject **)(((char *)(frame)) + __pyx_pyframe_localsplus_offset)) -#endif - -/* PyObjectCall.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); -#else -#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) -#endif - -/* PyObjectCall2Args.proto */ -static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); - -/* PyObjectCallMethO.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); -#endif - -/* PyObjectCallOneArg.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); - -/* RaiseException.proto */ -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); - -/* PyUnicodeContains.proto */ -static CYTHON_INLINE int __Pyx_PyUnicode_ContainsTF(PyObject* substring, PyObject* text, int eq) { - int result = PyUnicode_Contains(text, substring); - return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); -} - -/* RaiseArgTupleInvalid.proto */ -static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, - Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); - -/* RaiseDoubleKeywords.proto */ -static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); - -/* ParseKeywords.proto */ -static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\ - PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\ - const char* function_name); - -/* ArgTypeTest.proto */ -#define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact)\ - ((likely((Py_TYPE(obj) == type) | (none_allowed && (obj == Py_None)))) ? 1 :\ - __Pyx__ArgTypeTest(obj, type, name, exact)) -static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact); - -/* IterFinish.proto */ -static CYTHON_INLINE int __Pyx_IterFinish(void); - -/* PyObjectCallNoArg.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); -#else -#define __Pyx_PyObject_CallNoArg(func) __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL) -#endif - -/* PyObjectGetMethod.proto */ -static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method); - -/* PyObjectCallMethod0.proto */ -static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name); - -/* RaiseNeedMoreValuesToUnpack.proto */ -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); - -/* RaiseTooManyValuesToUnpack.proto */ -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); - -/* UnpackItemEndCheck.proto */ -static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); - -/* RaiseNoneIterError.proto */ -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); - -/* UnpackTupleError.proto */ -static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); - -/* UnpackTuple2.proto */ -#define __Pyx_unpack_tuple2(tuple, value1, value2, is_tuple, has_known_size, decref_tuple)\ - (likely(is_tuple || PyTuple_Check(tuple)) ?\ - (likely(has_known_size || PyTuple_GET_SIZE(tuple) == 2) ?\ - __Pyx_unpack_tuple2_exact(tuple, value1, value2, decref_tuple) :\ - (__Pyx_UnpackTupleError(tuple, 2), -1)) :\ - __Pyx_unpack_tuple2_generic(tuple, value1, value2, has_known_size, decref_tuple)) -static CYTHON_INLINE int __Pyx_unpack_tuple2_exact( - PyObject* tuple, PyObject** value1, PyObject** value2, int decref_tuple); -static int __Pyx_unpack_tuple2_generic( - PyObject* tuple, PyObject** value1, PyObject** value2, int has_known_size, int decref_tuple); - -/* dict_iter.proto */ -static CYTHON_INLINE PyObject* __Pyx_dict_iterator(PyObject* dict, int is_dict, PyObject* method_name, - Py_ssize_t* p_orig_length, int* p_is_dict); -static CYTHON_INLINE int __Pyx_dict_iter_next(PyObject* dict_or_iter, Py_ssize_t orig_length, Py_ssize_t* ppos, - PyObject** pkey, PyObject** pvalue, PyObject** pitem, int is_dict); - -/* GetTopmostException.proto */ -#if CYTHON_USE_EXC_INFO_STACK -static _PyErr_StackItem * __Pyx_PyErr_GetTopmostException(PyThreadState *tstate); -#endif - -/* ReRaiseException.proto */ -static CYTHON_INLINE void __Pyx_ReraiseException(void); - -/* GetException.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) -static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#else -static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); -#endif - -/* SwapException.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_ExceptionSwap(type, value, tb) __Pyx__ExceptionSwap(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#else -static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); -#endif - -/* SaveResetException.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); -#else -#define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) -#define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) -#endif - -/* TypeImport.proto */ -#ifndef __PYX_HAVE_RT_ImportType_proto -#define __PYX_HAVE_RT_ImportType_proto -enum __Pyx_ImportType_CheckSize { - __Pyx_ImportType_CheckSize_Error = 0, - __Pyx_ImportType_CheckSize_Warn = 1, - __Pyx_ImportType_CheckSize_Ignore = 2 -}; -static PyTypeObject *__Pyx_ImportType(PyObject* module, const char *module_name, const char *class_name, size_t size, enum __Pyx_ImportType_CheckSize check_size); -#endif - -/* Import.proto */ -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); - -/* ImportFrom.proto */ -static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); - -/* PyDictVersioning.proto */ -#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS -#define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1) -#define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) -#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ - (version_var) = __PYX_GET_DICT_VERSION(dict);\ - (cache_var) = (value); -#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ - static PY_UINT64_T __pyx_dict_version = 0;\ - static PyObject *__pyx_dict_cached_value = NULL;\ - if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ - (VAR) = __pyx_dict_cached_value;\ - } else {\ - (VAR) = __pyx_dict_cached_value = (LOOKUP);\ - __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ - }\ -} -static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj); -static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj); -static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version); -#else -#define __PYX_GET_DICT_VERSION(dict) (0) -#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) -#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); -#endif - -/* GetModuleGlobalName.proto */ -#if CYTHON_USE_DICT_VERSIONS -#define __Pyx_GetModuleGlobalName(var, name) {\ - static PY_UINT64_T __pyx_dict_version = 0;\ - static PyObject *__pyx_dict_cached_value = NULL;\ - (var) = (likely(__pyx_dict_version == __PYX_GET_DICT_VERSION(__pyx_d))) ?\ - (likely(__pyx_dict_cached_value) ? __Pyx_NewRef(__pyx_dict_cached_value) : __Pyx_GetBuiltinName(name)) :\ - __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ -} -#define __Pyx_GetModuleGlobalNameUncached(var, name) {\ - PY_UINT64_T __pyx_dict_version;\ - PyObject *__pyx_dict_cached_value;\ - (var) = __Pyx__GetModuleGlobalName(name, &__pyx_dict_version, &__pyx_dict_cached_value);\ -} -static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value); -#else -#define __Pyx_GetModuleGlobalName(var, name) (var) = __Pyx__GetModuleGlobalName(name) -#define __Pyx_GetModuleGlobalNameUncached(var, name) (var) = __Pyx__GetModuleGlobalName(name) -static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name); -#endif - -/* CLineInTraceback.proto */ -#ifdef CYTHON_CLINE_IN_TRACEBACK -#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) -#else -static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); -#endif - -/* CodeObjectCache.proto */ -typedef struct { - PyCodeObject* code_object; - int code_line; -} __Pyx_CodeObjectCacheEntry; -struct __Pyx_CodeObjectCache { - int count; - int max_count; - __Pyx_CodeObjectCacheEntry* entries; -}; -static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); -static PyCodeObject *__pyx_find_code_object(int code_line); -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); - -/* AddTraceback.proto */ -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename); - -/* GCCDiagnostics.proto */ -#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) -#define __Pyx_HAS_GCC_DIAGNOSTIC -#endif - -/* CIntToPy.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); - -/* CIntFromPy.proto */ -static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); - -/* CIntFromPy.proto */ -static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); - -/* FastTypeChecks.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) -static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); -static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); -static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); -#else -#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) -#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) -#define __Pyx_PyErr_GivenExceptionMatches2(err, type1, type2) (PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2)) -#endif -#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) - -/* CheckBinaryVersion.proto */ -static int __Pyx_check_binary_version(void); - -/* InitStrings.proto */ -static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); - - -/* Module declarations from 'libc.string' */ - -/* Module declarations from 'libc.stdio' */ - -/* Module declarations from '__builtin__' */ - -/* Module declarations from 'cpython.type' */ -static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; - -/* Module declarations from 'cpython' */ - -/* Module declarations from 'cpython.object' */ - -/* Module declarations from 'cpython.bytes' */ - -/* Module declarations from 'cpython.exc' */ - -/* Module declarations from 'cpython.mem' */ - -/* Module declarations from 'libc.stdint' */ - -/* Module declarations from 'aiohttp._http_writer' */ -static char __pyx_v_7aiohttp_12_http_writer_BUFFER[0x4000]; -static PyObject *__pyx_v_7aiohttp_12_http_writer__istr = 0; -static CYTHON_INLINE void __pyx_f_7aiohttp_12_http_writer__init_writer(struct __pyx_t_7aiohttp_12_http_writer_Writer *); /*proto*/ -static CYTHON_INLINE void __pyx_f_7aiohttp_12_http_writer__release_writer(struct __pyx_t_7aiohttp_12_http_writer_Writer *); /*proto*/ -static CYTHON_INLINE int __pyx_f_7aiohttp_12_http_writer__write_byte(struct __pyx_t_7aiohttp_12_http_writer_Writer *, uint8_t); /*proto*/ -static CYTHON_INLINE int __pyx_f_7aiohttp_12_http_writer__write_utf8(struct __pyx_t_7aiohttp_12_http_writer_Writer *, Py_UCS4); /*proto*/ -static CYTHON_INLINE int __pyx_f_7aiohttp_12_http_writer__write_str(struct __pyx_t_7aiohttp_12_http_writer_Writer *, PyObject *); /*proto*/ -static PyObject *__pyx_f_7aiohttp_12_http_writer_to_str(PyObject *); /*proto*/ -static void __pyx_f_7aiohttp_12_http_writer__safe_header(PyObject *); /*proto*/ -#define __Pyx_MODULE_NAME "aiohttp._http_writer" -extern int __pyx_module_is_main_aiohttp___http_writer; -int __pyx_module_is_main_aiohttp___http_writer = 0; - -/* Implementation of 'aiohttp._http_writer' */ -static PyObject *__pyx_builtin_TypeError; -static PyObject *__pyx_builtin_ValueError; -static const char __pyx_k_[] = "\r"; -static const char __pyx_k__2[] = "\n"; -static const char __pyx_k_key[] = "key"; -static const char __pyx_k_ret[] = "ret"; -static const char __pyx_k_val[] = "val"; -static const char __pyx_k_istr[] = "istr"; -static const char __pyx_k_main[] = "__main__"; -static const char __pyx_k_name[] = "__name__"; -static const char __pyx_k_test[] = "__test__"; -static const char __pyx_k_items[] = "items"; -static const char __pyx_k_format[] = "format"; -static const char __pyx_k_import[] = "__import__"; -static const char __pyx_k_writer[] = "writer"; -static const char __pyx_k_headers[] = "headers"; -static const char __pyx_k_TypeError[] = "TypeError"; -static const char __pyx_k_multidict[] = "multidict"; -static const char __pyx_k_ValueError[] = "ValueError"; -static const char __pyx_k_status_line[] = "status_line"; -static const char __pyx_k_serialize_headers[] = "_serialize_headers"; -static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback"; -static const char __pyx_k_aiohttp__http_writer[] = "aiohttp._http_writer"; -static const char __pyx_k_aiohttp__http_writer_pyx[] = "aiohttp\\_http_writer.pyx"; -static const char __pyx_k_Cannot_serialize_non_str_key_r[] = "Cannot serialize non-str key {!r}"; -static const char __pyx_k_Newline_or_carriage_return_chara[] = "Newline or carriage return character detected in HTTP status message or header. This is a potential security issue."; -static PyObject *__pyx_kp_u_; -static PyObject *__pyx_kp_u_Cannot_serialize_non_str_key_r; -static PyObject *__pyx_kp_u_Newline_or_carriage_return_chara; -static PyObject *__pyx_n_s_TypeError; -static PyObject *__pyx_n_s_ValueError; -static PyObject *__pyx_kp_u__2; -static PyObject *__pyx_n_s_aiohttp__http_writer; -static PyObject *__pyx_kp_s_aiohttp__http_writer_pyx; -static PyObject *__pyx_n_s_cline_in_traceback; -static PyObject *__pyx_n_s_format; -static PyObject *__pyx_n_s_headers; -static PyObject *__pyx_n_s_import; -static PyObject *__pyx_n_s_istr; -static PyObject *__pyx_n_s_items; -static PyObject *__pyx_n_s_key; -static PyObject *__pyx_n_s_main; -static PyObject *__pyx_n_s_multidict; -static PyObject *__pyx_n_s_name; -static PyObject *__pyx_n_s_ret; -static PyObject *__pyx_n_s_serialize_headers; -static PyObject *__pyx_n_s_status_line; -static PyObject *__pyx_n_s_test; -static PyObject *__pyx_n_s_val; -static PyObject *__pyx_n_s_writer; -static PyObject *__pyx_pf_7aiohttp_12_http_writer__serialize_headers(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_status_line, PyObject *__pyx_v_headers); /* proto */ -static PyObject *__pyx_tuple__3; -static PyObject *__pyx_tuple__4; -static PyObject *__pyx_codeobj__5; -/* Late includes */ - -/* "aiohttp/_http_writer.pyx":24 - * - * - * cdef inline void _init_writer(Writer* writer): # <<<<<<<<<<<<<< - * writer.buf = &BUFFER[0] - * writer.size = BUF_SIZE - */ - -static CYTHON_INLINE void __pyx_f_7aiohttp_12_http_writer__init_writer(struct __pyx_t_7aiohttp_12_http_writer_Writer *__pyx_v_writer) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_init_writer", 0); - - /* "aiohttp/_http_writer.pyx":25 - * - * cdef inline void _init_writer(Writer* writer): - * writer.buf = &BUFFER[0] # <<<<<<<<<<<<<< - * writer.size = BUF_SIZE - * writer.pos = 0 - */ - __pyx_v_writer->buf = (&(__pyx_v_7aiohttp_12_http_writer_BUFFER[0])); - - /* "aiohttp/_http_writer.pyx":26 - * cdef inline void _init_writer(Writer* writer): - * writer.buf = &BUFFER[0] - * writer.size = BUF_SIZE # <<<<<<<<<<<<<< - * writer.pos = 0 - * - */ - __pyx_v_writer->size = 0x4000; - - /* "aiohttp/_http_writer.pyx":27 - * writer.buf = &BUFFER[0] - * writer.size = BUF_SIZE - * writer.pos = 0 # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_writer->pos = 0; - - /* "aiohttp/_http_writer.pyx":24 - * - * - * cdef inline void _init_writer(Writer* writer): # <<<<<<<<<<<<<< - * writer.buf = &BUFFER[0] - * writer.size = BUF_SIZE - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -/* "aiohttp/_http_writer.pyx":30 - * - * - * cdef inline void _release_writer(Writer* writer): # <<<<<<<<<<<<<< - * if writer.buf != BUFFER: - * PyMem_Free(writer.buf) - */ - -static CYTHON_INLINE void __pyx_f_7aiohttp_12_http_writer__release_writer(struct __pyx_t_7aiohttp_12_http_writer_Writer *__pyx_v_writer) { - __Pyx_RefNannyDeclarations - int __pyx_t_1; - __Pyx_RefNannySetupContext("_release_writer", 0); - - /* "aiohttp/_http_writer.pyx":31 - * - * cdef inline void _release_writer(Writer* writer): - * if writer.buf != BUFFER: # <<<<<<<<<<<<<< - * PyMem_Free(writer.buf) - * - */ - __pyx_t_1 = ((__pyx_v_writer->buf != __pyx_v_7aiohttp_12_http_writer_BUFFER) != 0); - if (__pyx_t_1) { - - /* "aiohttp/_http_writer.pyx":32 - * cdef inline void _release_writer(Writer* writer): - * if writer.buf != BUFFER: - * PyMem_Free(writer.buf) # <<<<<<<<<<<<<< - * - * - */ - PyMem_Free(__pyx_v_writer->buf); - - /* "aiohttp/_http_writer.pyx":31 - * - * cdef inline void _release_writer(Writer* writer): - * if writer.buf != BUFFER: # <<<<<<<<<<<<<< - * PyMem_Free(writer.buf) - * - */ - } - - /* "aiohttp/_http_writer.pyx":30 - * - * - * cdef inline void _release_writer(Writer* writer): # <<<<<<<<<<<<<< - * if writer.buf != BUFFER: - * PyMem_Free(writer.buf) - */ - - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -/* "aiohttp/_http_writer.pyx":35 - * - * - * cdef inline int _write_byte(Writer* writer, uint8_t ch): # <<<<<<<<<<<<<< - * cdef char * buf - * cdef Py_ssize_t size - */ - -static CYTHON_INLINE int __pyx_f_7aiohttp_12_http_writer__write_byte(struct __pyx_t_7aiohttp_12_http_writer_Writer *__pyx_v_writer, uint8_t __pyx_v_ch) { - char *__pyx_v_buf; - Py_ssize_t __pyx_v_size; - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - PyObject *__pyx_t_2; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_write_byte", 0); - - /* "aiohttp/_http_writer.pyx":39 - * cdef Py_ssize_t size - * - * if writer.pos == writer.size: # <<<<<<<<<<<<<< - * # reallocate - * size = writer.size + BUF_SIZE - */ - __pyx_t_1 = ((__pyx_v_writer->pos == __pyx_v_writer->size) != 0); - if (__pyx_t_1) { - - /* "aiohttp/_http_writer.pyx":41 - * if writer.pos == writer.size: - * # reallocate - * size = writer.size + BUF_SIZE # <<<<<<<<<<<<<< - * if writer.buf == BUFFER: - * buf = PyMem_Malloc(size) - */ - __pyx_v_size = (__pyx_v_writer->size + 0x4000); - - /* "aiohttp/_http_writer.pyx":42 - * # reallocate - * size = writer.size + BUF_SIZE - * if writer.buf == BUFFER: # <<<<<<<<<<<<<< - * buf = PyMem_Malloc(size) - * if buf == NULL: - */ - __pyx_t_1 = ((__pyx_v_writer->buf == __pyx_v_7aiohttp_12_http_writer_BUFFER) != 0); - if (__pyx_t_1) { - - /* "aiohttp/_http_writer.pyx":43 - * size = writer.size + BUF_SIZE - * if writer.buf == BUFFER: - * buf = PyMem_Malloc(size) # <<<<<<<<<<<<<< - * if buf == NULL: - * PyErr_NoMemory() - */ - __pyx_v_buf = ((char *)PyMem_Malloc(__pyx_v_size)); - - /* "aiohttp/_http_writer.pyx":44 - * if writer.buf == BUFFER: - * buf = PyMem_Malloc(size) - * if buf == NULL: # <<<<<<<<<<<<<< - * PyErr_NoMemory() - * return -1 - */ - __pyx_t_1 = ((__pyx_v_buf == NULL) != 0); - if (__pyx_t_1) { - - /* "aiohttp/_http_writer.pyx":45 - * buf = PyMem_Malloc(size) - * if buf == NULL: - * PyErr_NoMemory() # <<<<<<<<<<<<<< - * return -1 - * memcpy(buf, writer.buf, writer.size) - */ - __pyx_t_2 = PyErr_NoMemory(); if (unlikely(__pyx_t_2 == ((PyObject *)NULL))) __PYX_ERR(0, 45, __pyx_L1_error) - - /* "aiohttp/_http_writer.pyx":46 - * if buf == NULL: - * PyErr_NoMemory() - * return -1 # <<<<<<<<<<<<<< - * memcpy(buf, writer.buf, writer.size) - * else: - */ - __pyx_r = -1; - goto __pyx_L0; - - /* "aiohttp/_http_writer.pyx":44 - * if writer.buf == BUFFER: - * buf = PyMem_Malloc(size) - * if buf == NULL: # <<<<<<<<<<<<<< - * PyErr_NoMemory() - * return -1 - */ - } - - /* "aiohttp/_http_writer.pyx":47 - * PyErr_NoMemory() - * return -1 - * memcpy(buf, writer.buf, writer.size) # <<<<<<<<<<<<<< - * else: - * buf = PyMem_Realloc(writer.buf, size) - */ - (void)(memcpy(__pyx_v_buf, __pyx_v_writer->buf, __pyx_v_writer->size)); - - /* "aiohttp/_http_writer.pyx":42 - * # reallocate - * size = writer.size + BUF_SIZE - * if writer.buf == BUFFER: # <<<<<<<<<<<<<< - * buf = PyMem_Malloc(size) - * if buf == NULL: - */ - goto __pyx_L4; - } - - /* "aiohttp/_http_writer.pyx":49 - * memcpy(buf, writer.buf, writer.size) - * else: - * buf = PyMem_Realloc(writer.buf, size) # <<<<<<<<<<<<<< - * if buf == NULL: - * PyErr_NoMemory() - */ - /*else*/ { - __pyx_v_buf = ((char *)PyMem_Realloc(__pyx_v_writer->buf, __pyx_v_size)); - - /* "aiohttp/_http_writer.pyx":50 - * else: - * buf = PyMem_Realloc(writer.buf, size) - * if buf == NULL: # <<<<<<<<<<<<<< - * PyErr_NoMemory() - * return -1 - */ - __pyx_t_1 = ((__pyx_v_buf == NULL) != 0); - if (__pyx_t_1) { - - /* "aiohttp/_http_writer.pyx":51 - * buf = PyMem_Realloc(writer.buf, size) - * if buf == NULL: - * PyErr_NoMemory() # <<<<<<<<<<<<<< - * return -1 - * writer.buf = buf - */ - __pyx_t_2 = PyErr_NoMemory(); if (unlikely(__pyx_t_2 == ((PyObject *)NULL))) __PYX_ERR(0, 51, __pyx_L1_error) - - /* "aiohttp/_http_writer.pyx":52 - * if buf == NULL: - * PyErr_NoMemory() - * return -1 # <<<<<<<<<<<<<< - * writer.buf = buf - * writer.size = size - */ - __pyx_r = -1; - goto __pyx_L0; - - /* "aiohttp/_http_writer.pyx":50 - * else: - * buf = PyMem_Realloc(writer.buf, size) - * if buf == NULL: # <<<<<<<<<<<<<< - * PyErr_NoMemory() - * return -1 - */ - } - } - __pyx_L4:; - - /* "aiohttp/_http_writer.pyx":53 - * PyErr_NoMemory() - * return -1 - * writer.buf = buf # <<<<<<<<<<<<<< - * writer.size = size - * writer.buf[writer.pos] = ch - */ - __pyx_v_writer->buf = __pyx_v_buf; - - /* "aiohttp/_http_writer.pyx":54 - * return -1 - * writer.buf = buf - * writer.size = size # <<<<<<<<<<<<<< - * writer.buf[writer.pos] = ch - * writer.pos += 1 - */ - __pyx_v_writer->size = __pyx_v_size; - - /* "aiohttp/_http_writer.pyx":39 - * cdef Py_ssize_t size - * - * if writer.pos == writer.size: # <<<<<<<<<<<<<< - * # reallocate - * size = writer.size + BUF_SIZE - */ - } - - /* "aiohttp/_http_writer.pyx":55 - * writer.buf = buf - * writer.size = size - * writer.buf[writer.pos] = ch # <<<<<<<<<<<<<< - * writer.pos += 1 - * return 0 - */ - (__pyx_v_writer->buf[__pyx_v_writer->pos]) = ((char)__pyx_v_ch); - - /* "aiohttp/_http_writer.pyx":56 - * writer.size = size - * writer.buf[writer.pos] = ch - * writer.pos += 1 # <<<<<<<<<<<<<< - * return 0 - * - */ - __pyx_v_writer->pos = (__pyx_v_writer->pos + 1); - - /* "aiohttp/_http_writer.pyx":57 - * writer.buf[writer.pos] = ch - * writer.pos += 1 - * return 0 # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = 0; - goto __pyx_L0; - - /* "aiohttp/_http_writer.pyx":35 - * - * - * cdef inline int _write_byte(Writer* writer, uint8_t ch): # <<<<<<<<<<<<<< - * cdef char * buf - * cdef Py_ssize_t size - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_WriteUnraisable("aiohttp._http_writer._write_byte", __pyx_clineno, __pyx_lineno, __pyx_filename, 1, 0); - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_writer.pyx":60 - * - * - * cdef inline int _write_utf8(Writer* writer, Py_UCS4 symbol): # <<<<<<<<<<<<<< - * cdef uint64_t utf = symbol - * - */ - -static CYTHON_INLINE int __pyx_f_7aiohttp_12_http_writer__write_utf8(struct __pyx_t_7aiohttp_12_http_writer_Writer *__pyx_v_writer, Py_UCS4 __pyx_v_symbol) { - uint64_t __pyx_v_utf; - int __pyx_r; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - __Pyx_RefNannySetupContext("_write_utf8", 0); - - /* "aiohttp/_http_writer.pyx":61 - * - * cdef inline int _write_utf8(Writer* writer, Py_UCS4 symbol): - * cdef uint64_t utf = symbol # <<<<<<<<<<<<<< - * - * if utf < 0x80: - */ - __pyx_v_utf = ((uint64_t)__pyx_v_symbol); - - /* "aiohttp/_http_writer.pyx":63 - * cdef uint64_t utf = symbol - * - * if utf < 0x80: # <<<<<<<<<<<<<< - * return _write_byte(writer, utf) - * elif utf < 0x800: - */ - __pyx_t_1 = ((__pyx_v_utf < 0x80) != 0); - if (__pyx_t_1) { - - /* "aiohttp/_http_writer.pyx":64 - * - * if utf < 0x80: - * return _write_byte(writer, utf) # <<<<<<<<<<<<<< - * elif utf < 0x800: - * if _write_byte(writer, (0xc0 | (utf >> 6))) < 0: - */ - __pyx_r = __pyx_f_7aiohttp_12_http_writer__write_byte(__pyx_v_writer, ((uint8_t)__pyx_v_utf)); - goto __pyx_L0; - - /* "aiohttp/_http_writer.pyx":63 - * cdef uint64_t utf = symbol - * - * if utf < 0x80: # <<<<<<<<<<<<<< - * return _write_byte(writer, utf) - * elif utf < 0x800: - */ - } - - /* "aiohttp/_http_writer.pyx":65 - * if utf < 0x80: - * return _write_byte(writer, utf) - * elif utf < 0x800: # <<<<<<<<<<<<<< - * if _write_byte(writer, (0xc0 | (utf >> 6))) < 0: - * return -1 - */ - __pyx_t_1 = ((__pyx_v_utf < 0x800) != 0); - if (__pyx_t_1) { - - /* "aiohttp/_http_writer.pyx":66 - * return _write_byte(writer, utf) - * elif utf < 0x800: - * if _write_byte(writer, (0xc0 | (utf >> 6))) < 0: # <<<<<<<<<<<<<< - * return -1 - * return _write_byte(writer, (0x80 | (utf & 0x3f))) - */ - __pyx_t_1 = ((__pyx_f_7aiohttp_12_http_writer__write_byte(__pyx_v_writer, ((uint8_t)(0xc0 | (__pyx_v_utf >> 6)))) < 0) != 0); - if (__pyx_t_1) { - - /* "aiohttp/_http_writer.pyx":67 - * elif utf < 0x800: - * if _write_byte(writer, (0xc0 | (utf >> 6))) < 0: - * return -1 # <<<<<<<<<<<<<< - * return _write_byte(writer, (0x80 | (utf & 0x3f))) - * elif 0xD800 <= utf <= 0xDFFF: - */ - __pyx_r = -1; - goto __pyx_L0; - - /* "aiohttp/_http_writer.pyx":66 - * return _write_byte(writer, utf) - * elif utf < 0x800: - * if _write_byte(writer, (0xc0 | (utf >> 6))) < 0: # <<<<<<<<<<<<<< - * return -1 - * return _write_byte(writer, (0x80 | (utf & 0x3f))) - */ - } - - /* "aiohttp/_http_writer.pyx":68 - * if _write_byte(writer, (0xc0 | (utf >> 6))) < 0: - * return -1 - * return _write_byte(writer, (0x80 | (utf & 0x3f))) # <<<<<<<<<<<<<< - * elif 0xD800 <= utf <= 0xDFFF: - * # surogate pair, ignored - */ - __pyx_r = __pyx_f_7aiohttp_12_http_writer__write_byte(__pyx_v_writer, ((uint8_t)(0x80 | (__pyx_v_utf & 0x3f)))); - goto __pyx_L0; - - /* "aiohttp/_http_writer.pyx":65 - * if utf < 0x80: - * return _write_byte(writer, utf) - * elif utf < 0x800: # <<<<<<<<<<<<<< - * if _write_byte(writer, (0xc0 | (utf >> 6))) < 0: - * return -1 - */ - } - - /* "aiohttp/_http_writer.pyx":69 - * return -1 - * return _write_byte(writer, (0x80 | (utf & 0x3f))) - * elif 0xD800 <= utf <= 0xDFFF: # <<<<<<<<<<<<<< - * # surogate pair, ignored - * return 0 - */ - __pyx_t_1 = (0xD800 <= __pyx_v_utf); - if (__pyx_t_1) { - __pyx_t_1 = (__pyx_v_utf <= 0xDFFF); - } - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "aiohttp/_http_writer.pyx":71 - * elif 0xD800 <= utf <= 0xDFFF: - * # surogate pair, ignored - * return 0 # <<<<<<<<<<<<<< - * elif utf < 0x10000: - * if _write_byte(writer, (0xe0 | (utf >> 12))) < 0: - */ - __pyx_r = 0; - goto __pyx_L0; - - /* "aiohttp/_http_writer.pyx":69 - * return -1 - * return _write_byte(writer, (0x80 | (utf & 0x3f))) - * elif 0xD800 <= utf <= 0xDFFF: # <<<<<<<<<<<<<< - * # surogate pair, ignored - * return 0 - */ - } - - /* "aiohttp/_http_writer.pyx":72 - * # surogate pair, ignored - * return 0 - * elif utf < 0x10000: # <<<<<<<<<<<<<< - * if _write_byte(writer, (0xe0 | (utf >> 12))) < 0: - * return -1 - */ - __pyx_t_2 = ((__pyx_v_utf < 0x10000) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_http_writer.pyx":73 - * return 0 - * elif utf < 0x10000: - * if _write_byte(writer, (0xe0 | (utf >> 12))) < 0: # <<<<<<<<<<<<<< - * return -1 - * if _write_byte(writer, (0x80 | ((utf >> 6) & 0x3f))) < 0: - */ - __pyx_t_2 = ((__pyx_f_7aiohttp_12_http_writer__write_byte(__pyx_v_writer, ((uint8_t)(0xe0 | (__pyx_v_utf >> 12)))) < 0) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_http_writer.pyx":74 - * elif utf < 0x10000: - * if _write_byte(writer, (0xe0 | (utf >> 12))) < 0: - * return -1 # <<<<<<<<<<<<<< - * if _write_byte(writer, (0x80 | ((utf >> 6) & 0x3f))) < 0: - * return -1 - */ - __pyx_r = -1; - goto __pyx_L0; - - /* "aiohttp/_http_writer.pyx":73 - * return 0 - * elif utf < 0x10000: - * if _write_byte(writer, (0xe0 | (utf >> 12))) < 0: # <<<<<<<<<<<<<< - * return -1 - * if _write_byte(writer, (0x80 | ((utf >> 6) & 0x3f))) < 0: - */ - } - - /* "aiohttp/_http_writer.pyx":75 - * if _write_byte(writer, (0xe0 | (utf >> 12))) < 0: - * return -1 - * if _write_byte(writer, (0x80 | ((utf >> 6) & 0x3f))) < 0: # <<<<<<<<<<<<<< - * return -1 - * return _write_byte(writer, (0x80 | (utf & 0x3f))) - */ - __pyx_t_2 = ((__pyx_f_7aiohttp_12_http_writer__write_byte(__pyx_v_writer, ((uint8_t)(0x80 | ((__pyx_v_utf >> 6) & 0x3f)))) < 0) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_http_writer.pyx":76 - * return -1 - * if _write_byte(writer, (0x80 | ((utf >> 6) & 0x3f))) < 0: - * return -1 # <<<<<<<<<<<<<< - * return _write_byte(writer, (0x80 | (utf & 0x3f))) - * elif utf > 0x10FFFF: - */ - __pyx_r = -1; - goto __pyx_L0; - - /* "aiohttp/_http_writer.pyx":75 - * if _write_byte(writer, (0xe0 | (utf >> 12))) < 0: - * return -1 - * if _write_byte(writer, (0x80 | ((utf >> 6) & 0x3f))) < 0: # <<<<<<<<<<<<<< - * return -1 - * return _write_byte(writer, (0x80 | (utf & 0x3f))) - */ - } - - /* "aiohttp/_http_writer.pyx":77 - * if _write_byte(writer, (0x80 | ((utf >> 6) & 0x3f))) < 0: - * return -1 - * return _write_byte(writer, (0x80 | (utf & 0x3f))) # <<<<<<<<<<<<<< - * elif utf > 0x10FFFF: - * # symbol is too large - */ - __pyx_r = __pyx_f_7aiohttp_12_http_writer__write_byte(__pyx_v_writer, ((uint8_t)(0x80 | (__pyx_v_utf & 0x3f)))); - goto __pyx_L0; - - /* "aiohttp/_http_writer.pyx":72 - * # surogate pair, ignored - * return 0 - * elif utf < 0x10000: # <<<<<<<<<<<<<< - * if _write_byte(writer, (0xe0 | (utf >> 12))) < 0: - * return -1 - */ - } - - /* "aiohttp/_http_writer.pyx":78 - * return -1 - * return _write_byte(writer, (0x80 | (utf & 0x3f))) - * elif utf > 0x10FFFF: # <<<<<<<<<<<<<< - * # symbol is too large - * return 0 - */ - __pyx_t_2 = ((__pyx_v_utf > 0x10FFFF) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_http_writer.pyx":80 - * elif utf > 0x10FFFF: - * # symbol is too large - * return 0 # <<<<<<<<<<<<<< - * else: - * if _write_byte(writer, (0xf0 | (utf >> 18))) < 0: - */ - __pyx_r = 0; - goto __pyx_L0; - - /* "aiohttp/_http_writer.pyx":78 - * return -1 - * return _write_byte(writer, (0x80 | (utf & 0x3f))) - * elif utf > 0x10FFFF: # <<<<<<<<<<<<<< - * # symbol is too large - * return 0 - */ - } - - /* "aiohttp/_http_writer.pyx":82 - * return 0 - * else: - * if _write_byte(writer, (0xf0 | (utf >> 18))) < 0: # <<<<<<<<<<<<<< - * return -1 - * if _write_byte(writer, - */ - /*else*/ { - __pyx_t_2 = ((__pyx_f_7aiohttp_12_http_writer__write_byte(__pyx_v_writer, ((uint8_t)(0xf0 | (__pyx_v_utf >> 18)))) < 0) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_http_writer.pyx":83 - * else: - * if _write_byte(writer, (0xf0 | (utf >> 18))) < 0: - * return -1 # <<<<<<<<<<<<<< - * if _write_byte(writer, - * (0x80 | ((utf >> 12) & 0x3f))) < 0: - */ - __pyx_r = -1; - goto __pyx_L0; - - /* "aiohttp/_http_writer.pyx":82 - * return 0 - * else: - * if _write_byte(writer, (0xf0 | (utf >> 18))) < 0: # <<<<<<<<<<<<<< - * return -1 - * if _write_byte(writer, - */ - } - - /* "aiohttp/_http_writer.pyx":85 - * return -1 - * if _write_byte(writer, - * (0x80 | ((utf >> 12) & 0x3f))) < 0: # <<<<<<<<<<<<<< - * return -1 - * if _write_byte(writer, - */ - __pyx_t_2 = ((__pyx_f_7aiohttp_12_http_writer__write_byte(__pyx_v_writer, ((uint8_t)(0x80 | ((__pyx_v_utf >> 12) & 0x3f)))) < 0) != 0); - - /* "aiohttp/_http_writer.pyx":84 - * if _write_byte(writer, (0xf0 | (utf >> 18))) < 0: - * return -1 - * if _write_byte(writer, # <<<<<<<<<<<<<< - * (0x80 | ((utf >> 12) & 0x3f))) < 0: - * return -1 - */ - if (__pyx_t_2) { - - /* "aiohttp/_http_writer.pyx":86 - * if _write_byte(writer, - * (0x80 | ((utf >> 12) & 0x3f))) < 0: - * return -1 # <<<<<<<<<<<<<< - * if _write_byte(writer, - * (0x80 | ((utf >> 6) & 0x3f))) < 0: - */ - __pyx_r = -1; - goto __pyx_L0; - - /* "aiohttp/_http_writer.pyx":84 - * if _write_byte(writer, (0xf0 | (utf >> 18))) < 0: - * return -1 - * if _write_byte(writer, # <<<<<<<<<<<<<< - * (0x80 | ((utf >> 12) & 0x3f))) < 0: - * return -1 - */ - } - - /* "aiohttp/_http_writer.pyx":88 - * return -1 - * if _write_byte(writer, - * (0x80 | ((utf >> 6) & 0x3f))) < 0: # <<<<<<<<<<<<<< - * return -1 - * return _write_byte(writer, (0x80 | (utf & 0x3f))) - */ - __pyx_t_2 = ((__pyx_f_7aiohttp_12_http_writer__write_byte(__pyx_v_writer, ((uint8_t)(0x80 | ((__pyx_v_utf >> 6) & 0x3f)))) < 0) != 0); - - /* "aiohttp/_http_writer.pyx":87 - * (0x80 | ((utf >> 12) & 0x3f))) < 0: - * return -1 - * if _write_byte(writer, # <<<<<<<<<<<<<< - * (0x80 | ((utf >> 6) & 0x3f))) < 0: - * return -1 - */ - if (__pyx_t_2) { - - /* "aiohttp/_http_writer.pyx":89 - * if _write_byte(writer, - * (0x80 | ((utf >> 6) & 0x3f))) < 0: - * return -1 # <<<<<<<<<<<<<< - * return _write_byte(writer, (0x80 | (utf & 0x3f))) - * - */ - __pyx_r = -1; - goto __pyx_L0; - - /* "aiohttp/_http_writer.pyx":87 - * (0x80 | ((utf >> 12) & 0x3f))) < 0: - * return -1 - * if _write_byte(writer, # <<<<<<<<<<<<<< - * (0x80 | ((utf >> 6) & 0x3f))) < 0: - * return -1 - */ - } - - /* "aiohttp/_http_writer.pyx":90 - * (0x80 | ((utf >> 6) & 0x3f))) < 0: - * return -1 - * return _write_byte(writer, (0x80 | (utf & 0x3f))) # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = __pyx_f_7aiohttp_12_http_writer__write_byte(__pyx_v_writer, ((uint8_t)(0x80 | (__pyx_v_utf & 0x3f)))); - goto __pyx_L0; - } - - /* "aiohttp/_http_writer.pyx":60 - * - * - * cdef inline int _write_utf8(Writer* writer, Py_UCS4 symbol): # <<<<<<<<<<<<<< - * cdef uint64_t utf = symbol - * - */ - - /* function exit code */ - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_writer.pyx":93 - * - * - * cdef inline int _write_str(Writer* writer, str s): # <<<<<<<<<<<<<< - * cdef Py_UCS4 ch - * for ch in s: - */ - -static CYTHON_INLINE int __pyx_f_7aiohttp_12_http_writer__write_str(struct __pyx_t_7aiohttp_12_http_writer_Writer *__pyx_v_writer, PyObject *__pyx_v_s) { - Py_UCS4 __pyx_v_ch; - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - Py_ssize_t __pyx_t_3; - void *__pyx_t_4; - int __pyx_t_5; - int __pyx_t_6; - Py_ssize_t __pyx_t_7; - int __pyx_t_8; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_write_str", 0); - - /* "aiohttp/_http_writer.pyx":95 - * cdef inline int _write_str(Writer* writer, str s): - * cdef Py_UCS4 ch - * for ch in s: # <<<<<<<<<<<<<< - * if _write_utf8(writer, ch) < 0: - * return -1 - */ - if (unlikely(__pyx_v_s == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' is not iterable"); - __PYX_ERR(0, 95, __pyx_L1_error) - } - __Pyx_INCREF(__pyx_v_s); - __pyx_t_1 = __pyx_v_s; - __pyx_t_6 = __Pyx_init_unicode_iteration(__pyx_t_1, (&__pyx_t_3), (&__pyx_t_4), (&__pyx_t_5)); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(0, 95, __pyx_L1_error) - for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_3; __pyx_t_7++) { - __pyx_t_2 = __pyx_t_7; - __pyx_v_ch = __Pyx_PyUnicode_READ(__pyx_t_5, __pyx_t_4, __pyx_t_2); - - /* "aiohttp/_http_writer.pyx":96 - * cdef Py_UCS4 ch - * for ch in s: - * if _write_utf8(writer, ch) < 0: # <<<<<<<<<<<<<< - * return -1 - * - */ - __pyx_t_8 = ((__pyx_f_7aiohttp_12_http_writer__write_utf8(__pyx_v_writer, __pyx_v_ch) < 0) != 0); - if (__pyx_t_8) { - - /* "aiohttp/_http_writer.pyx":97 - * for ch in s: - * if _write_utf8(writer, ch) < 0: - * return -1 # <<<<<<<<<<<<<< - * - * - */ - __pyx_r = -1; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - goto __pyx_L0; - - /* "aiohttp/_http_writer.pyx":96 - * cdef Py_UCS4 ch - * for ch in s: - * if _write_utf8(writer, ch) < 0: # <<<<<<<<<<<<<< - * return -1 - * - */ - } - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_writer.pyx":93 - * - * - * cdef inline int _write_str(Writer* writer, str s): # <<<<<<<<<<<<<< - * cdef Py_UCS4 ch - * for ch in s: - */ - - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_WriteUnraisable("aiohttp._http_writer._write_str", __pyx_clineno, __pyx_lineno, __pyx_filename, 1, 0); - __pyx_r = 0; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_writer.pyx":102 - * # --------------- _serialize_headers ---------------------- - * - * cdef str to_str(object s): # <<<<<<<<<<<<<< - * typ = type(s) - * if typ is str: - */ - -static PyObject *__pyx_f_7aiohttp_12_http_writer_to_str(PyObject *__pyx_v_s) { - PyTypeObject *__pyx_v_typ = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("to_str", 0); - - /* "aiohttp/_http_writer.pyx":103 - * - * cdef str to_str(object s): - * typ = type(s) # <<<<<<<<<<<<<< - * if typ is str: - * return s - */ - __Pyx_INCREF(((PyObject *)Py_TYPE(__pyx_v_s))); - __pyx_v_typ = ((PyTypeObject*)((PyObject *)Py_TYPE(__pyx_v_s))); - - /* "aiohttp/_http_writer.pyx":104 - * cdef str to_str(object s): - * typ = type(s) - * if typ is str: # <<<<<<<<<<<<<< - * return s - * elif typ is _istr: - */ - __pyx_t_1 = (__pyx_v_typ == (&PyUnicode_Type)); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { - - /* "aiohttp/_http_writer.pyx":105 - * typ = type(s) - * if typ is str: - * return s # <<<<<<<<<<<<<< - * elif typ is _istr: - * return PyObject_Str(s) - */ - __Pyx_XDECREF(__pyx_r); - __Pyx_INCREF(((PyObject*)__pyx_v_s)); - __pyx_r = ((PyObject*)__pyx_v_s); - goto __pyx_L0; - - /* "aiohttp/_http_writer.pyx":104 - * cdef str to_str(object s): - * typ = type(s) - * if typ is str: # <<<<<<<<<<<<<< - * return s - * elif typ is _istr: - */ - } - - /* "aiohttp/_http_writer.pyx":106 - * if typ is str: - * return s - * elif typ is _istr: # <<<<<<<<<<<<<< - * return PyObject_Str(s) - * elif not isinstance(s, str): - */ - __pyx_t_2 = (__pyx_v_typ == ((PyTypeObject*)__pyx_v_7aiohttp_12_http_writer__istr)); - __pyx_t_1 = (__pyx_t_2 != 0); - if (__pyx_t_1) { - - /* "aiohttp/_http_writer.pyx":107 - * return s - * elif typ is _istr: - * return PyObject_Str(s) # <<<<<<<<<<<<<< - * elif not isinstance(s, str): - * raise TypeError("Cannot serialize non-str key {!r}".format(s)) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = PyObject_Str(__pyx_v_s); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 107, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - if (!(likely(PyUnicode_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "unicode", Py_TYPE(__pyx_t_3)->tp_name), 0))) __PYX_ERR(0, 107, __pyx_L1_error) - __pyx_r = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - goto __pyx_L0; - - /* "aiohttp/_http_writer.pyx":106 - * if typ is str: - * return s - * elif typ is _istr: # <<<<<<<<<<<<<< - * return PyObject_Str(s) - * elif not isinstance(s, str): - */ - } - - /* "aiohttp/_http_writer.pyx":108 - * elif typ is _istr: - * return PyObject_Str(s) - * elif not isinstance(s, str): # <<<<<<<<<<<<<< - * raise TypeError("Cannot serialize non-str key {!r}".format(s)) - * else: - */ - __pyx_t_1 = PyUnicode_Check(__pyx_v_s); - __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); - if (unlikely(__pyx_t_2)) { - - /* "aiohttp/_http_writer.pyx":109 - * return PyObject_Str(s) - * elif not isinstance(s, str): - * raise TypeError("Cannot serialize non-str key {!r}".format(s)) # <<<<<<<<<<<<<< - * else: - * return str(s) - */ - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_kp_u_Cannot_serialize_non_str_key_r, __pyx_n_s_format); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 109, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - __pyx_t_3 = (__pyx_t_5) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_5, __pyx_v_s) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_v_s); - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 109, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_CallOneArg(__pyx_builtin_TypeError, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 109, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __PYX_ERR(0, 109, __pyx_L1_error) - - /* "aiohttp/_http_writer.pyx":108 - * elif typ is _istr: - * return PyObject_Str(s) - * elif not isinstance(s, str): # <<<<<<<<<<<<<< - * raise TypeError("Cannot serialize non-str key {!r}".format(s)) - * else: - */ - } - - /* "aiohttp/_http_writer.pyx":111 - * raise TypeError("Cannot serialize non-str key {!r}".format(s)) - * else: - * return str(s) # <<<<<<<<<<<<<< - * - * - */ - /*else*/ { - __Pyx_XDECREF(__pyx_r); - __pyx_t_4 = __Pyx_PyObject_CallOneArg(((PyObject *)(&PyUnicode_Type)), __pyx_v_s); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 111, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_r = ((PyObject*)__pyx_t_4); - __pyx_t_4 = 0; - goto __pyx_L0; - } - - /* "aiohttp/_http_writer.pyx":102 - * # --------------- _serialize_headers ---------------------- - * - * cdef str to_str(object s): # <<<<<<<<<<<<<< - * typ = type(s) - * if typ is str: - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_AddTraceback("aiohttp._http_writer.to_str", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_typ); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_writer.pyx":114 - * - * - * cdef void _safe_header(str string) except *: # <<<<<<<<<<<<<< - * if "\r" in string or "\n" in string: - * raise ValueError( - */ - -static void __pyx_f_7aiohttp_12_http_writer__safe_header(PyObject *__pyx_v_string) { - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_safe_header", 0); - - /* "aiohttp/_http_writer.pyx":115 - * - * cdef void _safe_header(str string) except *: - * if "\r" in string or "\n" in string: # <<<<<<<<<<<<<< - * raise ValueError( - * "Newline or carriage return character detected in HTTP status message or " - */ - if (unlikely(__pyx_v_string == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - __PYX_ERR(0, 115, __pyx_L1_error) - } - __pyx_t_2 = (__Pyx_PyUnicode_ContainsTF(__pyx_kp_u_, __pyx_v_string, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(0, 115, __pyx_L1_error) - __pyx_t_3 = (__pyx_t_2 != 0); - if (!__pyx_t_3) { - } else { - __pyx_t_1 = __pyx_t_3; - goto __pyx_L4_bool_binop_done; - } - if (unlikely(__pyx_v_string == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - __PYX_ERR(0, 115, __pyx_L1_error) - } - __pyx_t_3 = (__Pyx_PyUnicode_ContainsTF(__pyx_kp_u__2, __pyx_v_string, Py_EQ)); if (unlikely(__pyx_t_3 < 0)) __PYX_ERR(0, 115, __pyx_L1_error) - __pyx_t_2 = (__pyx_t_3 != 0); - __pyx_t_1 = __pyx_t_2; - __pyx_L4_bool_binop_done:; - if (unlikely(__pyx_t_1)) { - - /* "aiohttp/_http_writer.pyx":116 - * cdef void _safe_header(str string) except *: - * if "\r" in string or "\n" in string: - * raise ValueError( # <<<<<<<<<<<<<< - * "Newline or carriage return character detected in HTTP status message or " - * "header. This is a potential security issue." - */ - __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 116, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __PYX_ERR(0, 116, __pyx_L1_error) - - /* "aiohttp/_http_writer.pyx":115 - * - * cdef void _safe_header(str string) except *: - * if "\r" in string or "\n" in string: # <<<<<<<<<<<<<< - * raise ValueError( - * "Newline or carriage return character detected in HTTP status message or " - */ - } - - /* "aiohttp/_http_writer.pyx":114 - * - * - * cdef void _safe_header(str string) except *: # <<<<<<<<<<<<<< - * if "\r" in string or "\n" in string: - * raise ValueError( - */ - - /* function exit code */ - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("aiohttp._http_writer._safe_header", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_L0:; - __Pyx_RefNannyFinishContext(); -} - -/* "aiohttp/_http_writer.pyx":122 - * - * - * def _serialize_headers(str status_line, headers): # <<<<<<<<<<<<<< - * cdef Writer writer - * cdef object key - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_writer_1_serialize_headers(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyMethodDef __pyx_mdef_7aiohttp_12_http_writer_1_serialize_headers = {"_serialize_headers", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_7aiohttp_12_http_writer_1_serialize_headers, METH_VARARGS|METH_KEYWORDS, 0}; -static PyObject *__pyx_pw_7aiohttp_12_http_writer_1_serialize_headers(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_status_line = 0; - PyObject *__pyx_v_headers = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_serialize_headers (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_status_line,&__pyx_n_s_headers,0}; - PyObject* values[2] = {0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_status_line)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_headers)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_serialize_headers", 1, 2, 2, 1); __PYX_ERR(0, 122, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_serialize_headers") < 0)) __PYX_ERR(0, 122, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_status_line = ((PyObject*)values[0]); - __pyx_v_headers = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_serialize_headers", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 122, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._http_writer._serialize_headers", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_status_line), (&PyUnicode_Type), 1, "status_line", 1))) __PYX_ERR(0, 122, __pyx_L1_error) - __pyx_r = __pyx_pf_7aiohttp_12_http_writer__serialize_headers(__pyx_self, __pyx_v_status_line, __pyx_v_headers); - - /* function exit code */ - goto __pyx_L0; - __pyx_L1_error:; - __pyx_r = NULL; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_writer__serialize_headers(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_status_line, PyObject *__pyx_v_headers) { - struct __pyx_t_7aiohttp_12_http_writer_Writer __pyx_v_writer; - PyObject *__pyx_v_key = 0; - PyObject *__pyx_v_val = 0; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - Py_ssize_t __pyx_t_2; - Py_ssize_t __pyx_t_3; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - int __pyx_t_7; - int __pyx_t_8; - char const *__pyx_t_9; - PyObject *__pyx_t_10 = NULL; - PyObject *__pyx_t_11 = NULL; - PyObject *__pyx_t_12 = NULL; - PyObject *__pyx_t_13 = NULL; - PyObject *__pyx_t_14 = NULL; - PyObject *__pyx_t_15 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_serialize_headers", 0); - - /* "aiohttp/_http_writer.pyx":128 - * cdef bytes ret - * - * _init_writer(&writer) # <<<<<<<<<<<<<< - * - * for key, val in headers.items(): - */ - __pyx_f_7aiohttp_12_http_writer__init_writer((&__pyx_v_writer)); - - /* "aiohttp/_http_writer.pyx":130 - * _init_writer(&writer) - * - * for key, val in headers.items(): # <<<<<<<<<<<<<< - * _safe_header(to_str(key)) - * _safe_header(to_str(val)) - */ - __pyx_t_2 = 0; - if (unlikely(__pyx_v_headers == Py_None)) { - PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "items"); - __PYX_ERR(0, 130, __pyx_L1_error) - } - __pyx_t_5 = __Pyx_dict_iterator(__pyx_v_headers, 0, __pyx_n_s_items, (&__pyx_t_3), (&__pyx_t_4)); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 130, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_1); - __pyx_t_1 = __pyx_t_5; - __pyx_t_5 = 0; - while (1) { - __pyx_t_7 = __Pyx_dict_iter_next(__pyx_t_1, __pyx_t_3, &__pyx_t_2, &__pyx_t_5, &__pyx_t_6, NULL, __pyx_t_4); - if (unlikely(__pyx_t_7 == 0)) break; - if (unlikely(__pyx_t_7 == -1)) __PYX_ERR(0, 130, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GOTREF(__pyx_t_6); - __Pyx_XDECREF_SET(__pyx_v_key, __pyx_t_5); - __pyx_t_5 = 0; - __Pyx_XDECREF_SET(__pyx_v_val, __pyx_t_6); - __pyx_t_6 = 0; - - /* "aiohttp/_http_writer.pyx":131 - * - * for key, val in headers.items(): - * _safe_header(to_str(key)) # <<<<<<<<<<<<<< - * _safe_header(to_str(val)) - * - */ - __pyx_t_6 = __pyx_f_7aiohttp_12_http_writer_to_str(__pyx_v_key); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 131, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_f_7aiohttp_12_http_writer__safe_header(((PyObject*)__pyx_t_6)); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 131, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - - /* "aiohttp/_http_writer.pyx":132 - * for key, val in headers.items(): - * _safe_header(to_str(key)) - * _safe_header(to_str(val)) # <<<<<<<<<<<<<< - * - * try: - */ - __pyx_t_6 = __pyx_f_7aiohttp_12_http_writer_to_str(__pyx_v_val); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 132, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_f_7aiohttp_12_http_writer__safe_header(((PyObject*)__pyx_t_6)); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 132, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_writer.pyx":134 - * _safe_header(to_str(val)) - * - * try: # <<<<<<<<<<<<<< - * if _write_str(&writer, status_line) < 0: - * raise - */ - /*try:*/ { - - /* "aiohttp/_http_writer.pyx":135 - * - * try: - * if _write_str(&writer, status_line) < 0: # <<<<<<<<<<<<<< - * raise - * if _write_byte(&writer, b'\r') < 0: - */ - __pyx_t_8 = ((__pyx_f_7aiohttp_12_http_writer__write_str((&__pyx_v_writer), __pyx_v_status_line) < 0) != 0); - if (unlikely(__pyx_t_8)) { - - /* "aiohttp/_http_writer.pyx":136 - * try: - * if _write_str(&writer, status_line) < 0: - * raise # <<<<<<<<<<<<<< - * if _write_byte(&writer, b'\r') < 0: - * raise - */ - __Pyx_ReraiseException(); __PYX_ERR(0, 136, __pyx_L6_error) - - /* "aiohttp/_http_writer.pyx":135 - * - * try: - * if _write_str(&writer, status_line) < 0: # <<<<<<<<<<<<<< - * raise - * if _write_byte(&writer, b'\r') < 0: - */ - } - - /* "aiohttp/_http_writer.pyx":137 - * if _write_str(&writer, status_line) < 0: - * raise - * if _write_byte(&writer, b'\r') < 0: # <<<<<<<<<<<<<< - * raise - * if _write_byte(&writer, b'\n') < 0: - */ - __pyx_t_8 = ((__pyx_f_7aiohttp_12_http_writer__write_byte((&__pyx_v_writer), '\r') < 0) != 0); - if (unlikely(__pyx_t_8)) { - - /* "aiohttp/_http_writer.pyx":138 - * raise - * if _write_byte(&writer, b'\r') < 0: - * raise # <<<<<<<<<<<<<< - * if _write_byte(&writer, b'\n') < 0: - * raise - */ - __Pyx_ReraiseException(); __PYX_ERR(0, 138, __pyx_L6_error) - - /* "aiohttp/_http_writer.pyx":137 - * if _write_str(&writer, status_line) < 0: - * raise - * if _write_byte(&writer, b'\r') < 0: # <<<<<<<<<<<<<< - * raise - * if _write_byte(&writer, b'\n') < 0: - */ - } - - /* "aiohttp/_http_writer.pyx":139 - * if _write_byte(&writer, b'\r') < 0: - * raise - * if _write_byte(&writer, b'\n') < 0: # <<<<<<<<<<<<<< - * raise - * - */ - __pyx_t_8 = ((__pyx_f_7aiohttp_12_http_writer__write_byte((&__pyx_v_writer), '\n') < 0) != 0); - if (unlikely(__pyx_t_8)) { - - /* "aiohttp/_http_writer.pyx":140 - * raise - * if _write_byte(&writer, b'\n') < 0: - * raise # <<<<<<<<<<<<<< - * - * for key, val in headers.items(): - */ - __Pyx_ReraiseException(); __PYX_ERR(0, 140, __pyx_L6_error) - - /* "aiohttp/_http_writer.pyx":139 - * if _write_byte(&writer, b'\r') < 0: - * raise - * if _write_byte(&writer, b'\n') < 0: # <<<<<<<<<<<<<< - * raise - * - */ - } - - /* "aiohttp/_http_writer.pyx":142 - * raise - * - * for key, val in headers.items(): # <<<<<<<<<<<<<< - * if _write_str(&writer, to_str(key)) < 0: - * raise - */ - __pyx_t_3 = 0; - if (unlikely(__pyx_v_headers == Py_None)) { - PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "items"); - __PYX_ERR(0, 142, __pyx_L6_error) - } - __pyx_t_6 = __Pyx_dict_iterator(__pyx_v_headers, 0, __pyx_n_s_items, (&__pyx_t_2), (&__pyx_t_4)); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 142, __pyx_L6_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_1); - __pyx_t_1 = __pyx_t_6; - __pyx_t_6 = 0; - while (1) { - __pyx_t_7 = __Pyx_dict_iter_next(__pyx_t_1, __pyx_t_2, &__pyx_t_3, &__pyx_t_6, &__pyx_t_5, NULL, __pyx_t_4); - if (unlikely(__pyx_t_7 == 0)) break; - if (unlikely(__pyx_t_7 == -1)) __PYX_ERR(0, 142, __pyx_L6_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GOTREF(__pyx_t_5); - __Pyx_XDECREF_SET(__pyx_v_key, __pyx_t_6); - __pyx_t_6 = 0; - __Pyx_XDECREF_SET(__pyx_v_val, __pyx_t_5); - __pyx_t_5 = 0; - - /* "aiohttp/_http_writer.pyx":143 - * - * for key, val in headers.items(): - * if _write_str(&writer, to_str(key)) < 0: # <<<<<<<<<<<<<< - * raise - * if _write_byte(&writer, b':') < 0: - */ - __pyx_t_5 = __pyx_f_7aiohttp_12_http_writer_to_str(__pyx_v_key); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 143, __pyx_L6_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_8 = ((__pyx_f_7aiohttp_12_http_writer__write_str((&__pyx_v_writer), ((PyObject*)__pyx_t_5)) < 0) != 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (unlikely(__pyx_t_8)) { - - /* "aiohttp/_http_writer.pyx":144 - * for key, val in headers.items(): - * if _write_str(&writer, to_str(key)) < 0: - * raise # <<<<<<<<<<<<<< - * if _write_byte(&writer, b':') < 0: - * raise - */ - __Pyx_ReraiseException(); __PYX_ERR(0, 144, __pyx_L6_error) - - /* "aiohttp/_http_writer.pyx":143 - * - * for key, val in headers.items(): - * if _write_str(&writer, to_str(key)) < 0: # <<<<<<<<<<<<<< - * raise - * if _write_byte(&writer, b':') < 0: - */ - } - - /* "aiohttp/_http_writer.pyx":145 - * if _write_str(&writer, to_str(key)) < 0: - * raise - * if _write_byte(&writer, b':') < 0: # <<<<<<<<<<<<<< - * raise - * if _write_byte(&writer, b' ') < 0: - */ - __pyx_t_8 = ((__pyx_f_7aiohttp_12_http_writer__write_byte((&__pyx_v_writer), ':') < 0) != 0); - if (unlikely(__pyx_t_8)) { - - /* "aiohttp/_http_writer.pyx":146 - * raise - * if _write_byte(&writer, b':') < 0: - * raise # <<<<<<<<<<<<<< - * if _write_byte(&writer, b' ') < 0: - * raise - */ - __Pyx_ReraiseException(); __PYX_ERR(0, 146, __pyx_L6_error) - - /* "aiohttp/_http_writer.pyx":145 - * if _write_str(&writer, to_str(key)) < 0: - * raise - * if _write_byte(&writer, b':') < 0: # <<<<<<<<<<<<<< - * raise - * if _write_byte(&writer, b' ') < 0: - */ - } - - /* "aiohttp/_http_writer.pyx":147 - * if _write_byte(&writer, b':') < 0: - * raise - * if _write_byte(&writer, b' ') < 0: # <<<<<<<<<<<<<< - * raise - * if _write_str(&writer, to_str(val)) < 0: - */ - __pyx_t_8 = ((__pyx_f_7aiohttp_12_http_writer__write_byte((&__pyx_v_writer), ' ') < 0) != 0); - if (unlikely(__pyx_t_8)) { - - /* "aiohttp/_http_writer.pyx":148 - * raise - * if _write_byte(&writer, b' ') < 0: - * raise # <<<<<<<<<<<<<< - * if _write_str(&writer, to_str(val)) < 0: - * raise - */ - __Pyx_ReraiseException(); __PYX_ERR(0, 148, __pyx_L6_error) - - /* "aiohttp/_http_writer.pyx":147 - * if _write_byte(&writer, b':') < 0: - * raise - * if _write_byte(&writer, b' ') < 0: # <<<<<<<<<<<<<< - * raise - * if _write_str(&writer, to_str(val)) < 0: - */ - } - - /* "aiohttp/_http_writer.pyx":149 - * if _write_byte(&writer, b' ') < 0: - * raise - * if _write_str(&writer, to_str(val)) < 0: # <<<<<<<<<<<<<< - * raise - * if _write_byte(&writer, b'\r') < 0: - */ - __pyx_t_5 = __pyx_f_7aiohttp_12_http_writer_to_str(__pyx_v_val); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 149, __pyx_L6_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_8 = ((__pyx_f_7aiohttp_12_http_writer__write_str((&__pyx_v_writer), ((PyObject*)__pyx_t_5)) < 0) != 0); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - if (unlikely(__pyx_t_8)) { - - /* "aiohttp/_http_writer.pyx":150 - * raise - * if _write_str(&writer, to_str(val)) < 0: - * raise # <<<<<<<<<<<<<< - * if _write_byte(&writer, b'\r') < 0: - * raise - */ - __Pyx_ReraiseException(); __PYX_ERR(0, 150, __pyx_L6_error) - - /* "aiohttp/_http_writer.pyx":149 - * if _write_byte(&writer, b' ') < 0: - * raise - * if _write_str(&writer, to_str(val)) < 0: # <<<<<<<<<<<<<< - * raise - * if _write_byte(&writer, b'\r') < 0: - */ - } - - /* "aiohttp/_http_writer.pyx":151 - * if _write_str(&writer, to_str(val)) < 0: - * raise - * if _write_byte(&writer, b'\r') < 0: # <<<<<<<<<<<<<< - * raise - * if _write_byte(&writer, b'\n') < 0: - */ - __pyx_t_8 = ((__pyx_f_7aiohttp_12_http_writer__write_byte((&__pyx_v_writer), '\r') < 0) != 0); - if (unlikely(__pyx_t_8)) { - - /* "aiohttp/_http_writer.pyx":152 - * raise - * if _write_byte(&writer, b'\r') < 0: - * raise # <<<<<<<<<<<<<< - * if _write_byte(&writer, b'\n') < 0: - * raise - */ - __Pyx_ReraiseException(); __PYX_ERR(0, 152, __pyx_L6_error) - - /* "aiohttp/_http_writer.pyx":151 - * if _write_str(&writer, to_str(val)) < 0: - * raise - * if _write_byte(&writer, b'\r') < 0: # <<<<<<<<<<<<<< - * raise - * if _write_byte(&writer, b'\n') < 0: - */ - } - - /* "aiohttp/_http_writer.pyx":153 - * if _write_byte(&writer, b'\r') < 0: - * raise - * if _write_byte(&writer, b'\n') < 0: # <<<<<<<<<<<<<< - * raise - * - */ - __pyx_t_8 = ((__pyx_f_7aiohttp_12_http_writer__write_byte((&__pyx_v_writer), '\n') < 0) != 0); - if (unlikely(__pyx_t_8)) { - - /* "aiohttp/_http_writer.pyx":154 - * raise - * if _write_byte(&writer, b'\n') < 0: - * raise # <<<<<<<<<<<<<< - * - * if _write_byte(&writer, b'\r') < 0: - */ - __Pyx_ReraiseException(); __PYX_ERR(0, 154, __pyx_L6_error) - - /* "aiohttp/_http_writer.pyx":153 - * if _write_byte(&writer, b'\r') < 0: - * raise - * if _write_byte(&writer, b'\n') < 0: # <<<<<<<<<<<<<< - * raise - * - */ - } - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_writer.pyx":156 - * raise - * - * if _write_byte(&writer, b'\r') < 0: # <<<<<<<<<<<<<< - * raise - * if _write_byte(&writer, b'\n') < 0: - */ - __pyx_t_8 = ((__pyx_f_7aiohttp_12_http_writer__write_byte((&__pyx_v_writer), '\r') < 0) != 0); - if (unlikely(__pyx_t_8)) { - - /* "aiohttp/_http_writer.pyx":157 - * - * if _write_byte(&writer, b'\r') < 0: - * raise # <<<<<<<<<<<<<< - * if _write_byte(&writer, b'\n') < 0: - * raise - */ - __Pyx_ReraiseException(); __PYX_ERR(0, 157, __pyx_L6_error) - - /* "aiohttp/_http_writer.pyx":156 - * raise - * - * if _write_byte(&writer, b'\r') < 0: # <<<<<<<<<<<<<< - * raise - * if _write_byte(&writer, b'\n') < 0: - */ - } - - /* "aiohttp/_http_writer.pyx":158 - * if _write_byte(&writer, b'\r') < 0: - * raise - * if _write_byte(&writer, b'\n') < 0: # <<<<<<<<<<<<<< - * raise - * - */ - __pyx_t_8 = ((__pyx_f_7aiohttp_12_http_writer__write_byte((&__pyx_v_writer), '\n') < 0) != 0); - if (unlikely(__pyx_t_8)) { - - /* "aiohttp/_http_writer.pyx":159 - * raise - * if _write_byte(&writer, b'\n') < 0: - * raise # <<<<<<<<<<<<<< - * - * return PyBytes_FromStringAndSize(writer.buf, writer.pos) - */ - __Pyx_ReraiseException(); __PYX_ERR(0, 159, __pyx_L6_error) - - /* "aiohttp/_http_writer.pyx":158 - * if _write_byte(&writer, b'\r') < 0: - * raise - * if _write_byte(&writer, b'\n') < 0: # <<<<<<<<<<<<<< - * raise - * - */ - } - - /* "aiohttp/_http_writer.pyx":161 - * raise - * - * return PyBytes_FromStringAndSize(writer.buf, writer.pos) # <<<<<<<<<<<<<< - * finally: - * _release_writer(&writer) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyBytes_FromStringAndSize(__pyx_v_writer.buf, __pyx_v_writer.pos); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 161, __pyx_L6_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_r = __pyx_t_1; - __pyx_t_1 = 0; - goto __pyx_L5_return; - } - - /* "aiohttp/_http_writer.pyx":163 - * return PyBytes_FromStringAndSize(writer.buf, writer.pos) - * finally: - * _release_writer(&writer) # <<<<<<<<<<<<<< - */ - /*finally:*/ { - __pyx_L6_error:; - /*exception exit:*/{ - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; __pyx_t_13 = 0; __pyx_t_14 = 0; __pyx_t_15 = 0; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_13, &__pyx_t_14, &__pyx_t_15); - if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12) < 0)) __Pyx_ErrFetch(&__pyx_t_10, &__pyx_t_11, &__pyx_t_12); - __Pyx_XGOTREF(__pyx_t_10); - __Pyx_XGOTREF(__pyx_t_11); - __Pyx_XGOTREF(__pyx_t_12); - __Pyx_XGOTREF(__pyx_t_13); - __Pyx_XGOTREF(__pyx_t_14); - __Pyx_XGOTREF(__pyx_t_15); - __pyx_t_4 = __pyx_lineno; __pyx_t_7 = __pyx_clineno; __pyx_t_9 = __pyx_filename; - { - __pyx_f_7aiohttp_12_http_writer__release_writer((&__pyx_v_writer)); - } - if (PY_MAJOR_VERSION >= 3) { - __Pyx_XGIVEREF(__pyx_t_13); - __Pyx_XGIVEREF(__pyx_t_14); - __Pyx_XGIVEREF(__pyx_t_15); - __Pyx_ExceptionReset(__pyx_t_13, __pyx_t_14, __pyx_t_15); - } - __Pyx_XGIVEREF(__pyx_t_10); - __Pyx_XGIVEREF(__pyx_t_11); - __Pyx_XGIVEREF(__pyx_t_12); - __Pyx_ErrRestore(__pyx_t_10, __pyx_t_11, __pyx_t_12); - __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_t_12 = 0; __pyx_t_13 = 0; __pyx_t_14 = 0; __pyx_t_15 = 0; - __pyx_lineno = __pyx_t_4; __pyx_clineno = __pyx_t_7; __pyx_filename = __pyx_t_9; - goto __pyx_L1_error; - } - __pyx_L5_return: { - __pyx_t_15 = __pyx_r; - __pyx_r = 0; - __pyx_f_7aiohttp_12_http_writer__release_writer((&__pyx_v_writer)); - __pyx_r = __pyx_t_15; - __pyx_t_15 = 0; - goto __pyx_L0; - } - } - - /* "aiohttp/_http_writer.pyx":122 - * - * - * def _serialize_headers(str status_line, headers): # <<<<<<<<<<<<<< - * cdef Writer writer - * cdef object key - */ - - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); - __Pyx_AddTraceback("aiohttp._http_writer._serialize_headers", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_key); - __Pyx_XDECREF(__pyx_v_val); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyMethodDef __pyx_methods[] = { - {0, 0, 0, 0} -}; - -#if PY_MAJOR_VERSION >= 3 -#if CYTHON_PEP489_MULTI_PHASE_INIT -static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ -static int __pyx_pymod_exec__http_writer(PyObject* module); /*proto*/ -static PyModuleDef_Slot __pyx_moduledef_slots[] = { - {Py_mod_create, (void*)__pyx_pymod_create}, - {Py_mod_exec, (void*)__pyx_pymod_exec__http_writer}, - {0, NULL} -}; -#endif - -static struct PyModuleDef __pyx_moduledef = { - PyModuleDef_HEAD_INIT, - "_http_writer", - 0, /* m_doc */ - #if CYTHON_PEP489_MULTI_PHASE_INIT - 0, /* m_size */ - #else - -1, /* m_size */ - #endif - __pyx_methods /* m_methods */, - #if CYTHON_PEP489_MULTI_PHASE_INIT - __pyx_moduledef_slots, /* m_slots */ - #else - NULL, /* m_reload */ - #endif - NULL, /* m_traverse */ - NULL, /* m_clear */ - NULL /* m_free */ -}; -#endif -#ifndef CYTHON_SMALL_CODE -#if defined(__clang__) - #define CYTHON_SMALL_CODE -#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) - #define CYTHON_SMALL_CODE __attribute__((cold)) -#else - #define CYTHON_SMALL_CODE -#endif -#endif - -static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_kp_u_, __pyx_k_, sizeof(__pyx_k_), 0, 1, 0, 0}, - {&__pyx_kp_u_Cannot_serialize_non_str_key_r, __pyx_k_Cannot_serialize_non_str_key_r, sizeof(__pyx_k_Cannot_serialize_non_str_key_r), 0, 1, 0, 0}, - {&__pyx_kp_u_Newline_or_carriage_return_chara, __pyx_k_Newline_or_carriage_return_chara, sizeof(__pyx_k_Newline_or_carriage_return_chara), 0, 1, 0, 0}, - {&__pyx_n_s_TypeError, __pyx_k_TypeError, sizeof(__pyx_k_TypeError), 0, 0, 1, 1}, - {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, - {&__pyx_kp_u__2, __pyx_k__2, sizeof(__pyx_k__2), 0, 1, 0, 0}, - {&__pyx_n_s_aiohttp__http_writer, __pyx_k_aiohttp__http_writer, sizeof(__pyx_k_aiohttp__http_writer), 0, 0, 1, 1}, - {&__pyx_kp_s_aiohttp__http_writer_pyx, __pyx_k_aiohttp__http_writer_pyx, sizeof(__pyx_k_aiohttp__http_writer_pyx), 0, 0, 1, 0}, - {&__pyx_n_s_cline_in_traceback, __pyx_k_cline_in_traceback, sizeof(__pyx_k_cline_in_traceback), 0, 0, 1, 1}, - {&__pyx_n_s_format, __pyx_k_format, sizeof(__pyx_k_format), 0, 0, 1, 1}, - {&__pyx_n_s_headers, __pyx_k_headers, sizeof(__pyx_k_headers), 0, 0, 1, 1}, - {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, - {&__pyx_n_s_istr, __pyx_k_istr, sizeof(__pyx_k_istr), 0, 0, 1, 1}, - {&__pyx_n_s_items, __pyx_k_items, sizeof(__pyx_k_items), 0, 0, 1, 1}, - {&__pyx_n_s_key, __pyx_k_key, sizeof(__pyx_k_key), 0, 0, 1, 1}, - {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, - {&__pyx_n_s_multidict, __pyx_k_multidict, sizeof(__pyx_k_multidict), 0, 0, 1, 1}, - {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, - {&__pyx_n_s_ret, __pyx_k_ret, sizeof(__pyx_k_ret), 0, 0, 1, 1}, - {&__pyx_n_s_serialize_headers, __pyx_k_serialize_headers, sizeof(__pyx_k_serialize_headers), 0, 0, 1, 1}, - {&__pyx_n_s_status_line, __pyx_k_status_line, sizeof(__pyx_k_status_line), 0, 0, 1, 1}, - {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, - {&__pyx_n_s_val, __pyx_k_val, sizeof(__pyx_k_val), 0, 0, 1, 1}, - {&__pyx_n_s_writer, __pyx_k_writer, sizeof(__pyx_k_writer), 0, 0, 1, 1}, - {0, 0, 0, 0, 0, 0, 0} -}; -static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) __PYX_ERR(0, 109, __pyx_L1_error) - __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) __PYX_ERR(0, 116, __pyx_L1_error) - return 0; - __pyx_L1_error:; - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); - - /* "aiohttp/_http_writer.pyx":116 - * cdef void _safe_header(str string) except *: - * if "\r" in string or "\n" in string: - * raise ValueError( # <<<<<<<<<<<<<< - * "Newline or carriage return character detected in HTTP status message or " - * "header. This is a potential security issue." - */ - __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_u_Newline_or_carriage_return_chara); if (unlikely(!__pyx_tuple__3)) __PYX_ERR(0, 116, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__3); - __Pyx_GIVEREF(__pyx_tuple__3); - - /* "aiohttp/_http_writer.pyx":122 - * - * - * def _serialize_headers(str status_line, headers): # <<<<<<<<<<<<<< - * cdef Writer writer - * cdef object key - */ - __pyx_tuple__4 = PyTuple_Pack(6, __pyx_n_s_status_line, __pyx_n_s_headers, __pyx_n_s_writer, __pyx_n_s_key, __pyx_n_s_val, __pyx_n_s_ret); if (unlikely(!__pyx_tuple__4)) __PYX_ERR(0, 122, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__4); - __Pyx_GIVEREF(__pyx_tuple__4); - __pyx_codeobj__5 = (PyObject*)__Pyx_PyCode_New(2, 0, 6, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__4, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_aiohttp__http_writer_pyx, __pyx_n_s_serialize_headers, 122, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__5)) __PYX_ERR(0, 122, __pyx_L1_error) - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_RefNannyFinishContext(); - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) { - if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error); - return 0; - __pyx_L1_error:; - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(void); /*proto*/ - -static int __Pyx_modinit_global_init_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0); - /*--- Global init code ---*/ - __pyx_v_7aiohttp_12_http_writer__istr = Py_None; Py_INCREF(Py_None); - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_variable_export_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0); - /*--- Variable export code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_function_export_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0); - /*--- Function export code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_type_init_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); - /*--- Type init code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_type_import_code(void) { - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); - /*--- Type import code ---*/ - __pyx_t_1 = PyImport_ImportModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 9, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__pyx_t_1, __Pyx_BUILTIN_MODULE_NAME, "type", - #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 - sizeof(PyTypeObject), - #else - sizeof(PyHeapTypeObject), - #endif - __Pyx_ImportType_CheckSize_Warn); - if (!__pyx_ptype_7cpython_4type_type) __PYX_ERR(1, 9, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_RefNannyFinishContext(); - return -1; -} - -static int __Pyx_modinit_variable_import_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0); - /*--- Variable import code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_function_import_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0); - /*--- Function import code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - - -#ifndef CYTHON_NO_PYINIT_EXPORT -#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC -#elif PY_MAJOR_VERSION < 3 -#ifdef __cplusplus -#define __Pyx_PyMODINIT_FUNC extern "C" void -#else -#define __Pyx_PyMODINIT_FUNC void -#endif -#else -#ifdef __cplusplus -#define __Pyx_PyMODINIT_FUNC extern "C" PyObject * -#else -#define __Pyx_PyMODINIT_FUNC PyObject * -#endif -#endif - - -#if PY_MAJOR_VERSION < 3 -__Pyx_PyMODINIT_FUNC init_http_writer(void) CYTHON_SMALL_CODE; /*proto*/ -__Pyx_PyMODINIT_FUNC init_http_writer(void) -#else -__Pyx_PyMODINIT_FUNC PyInit__http_writer(void) CYTHON_SMALL_CODE; /*proto*/ -__Pyx_PyMODINIT_FUNC PyInit__http_writer(void) -#if CYTHON_PEP489_MULTI_PHASE_INIT -{ - return PyModuleDef_Init(&__pyx_moduledef); -} -static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { - #if PY_VERSION_HEX >= 0x030700A1 - static PY_INT64_T main_interpreter_id = -1; - PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); - if (main_interpreter_id == -1) { - main_interpreter_id = current_id; - return (unlikely(current_id == -1)) ? -1 : 0; - } else if (unlikely(main_interpreter_id != current_id)) - #else - static PyInterpreterState *main_interpreter = NULL; - PyInterpreterState *current_interpreter = PyThreadState_Get()->interp; - if (!main_interpreter) { - main_interpreter = current_interpreter; - } else if (unlikely(main_interpreter != current_interpreter)) - #endif - { - PyErr_SetString( - PyExc_ImportError, - "Interpreter change detected - this module can only be loaded into one interpreter per process."); - return -1; - } - return 0; -} -static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) { - PyObject *value = PyObject_GetAttrString(spec, from_name); - int result = 0; - if (likely(value)) { - if (allow_none || value != Py_None) { - result = PyDict_SetItemString(moddict, to_name, value); - } - Py_DECREF(value); - } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Clear(); - } else { - result = -1; - } - return result; -} -static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, CYTHON_UNUSED PyModuleDef *def) { - PyObject *module = NULL, *moddict, *modname; - if (__Pyx_check_single_interpreter()) - return NULL; - if (__pyx_m) - return __Pyx_NewRef(__pyx_m); - modname = PyObject_GetAttrString(spec, "name"); - if (unlikely(!modname)) goto bad; - module = PyModule_NewObject(modname); - Py_DECREF(modname); - if (unlikely(!module)) goto bad; - moddict = PyModule_GetDict(module); - if (unlikely(!moddict)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; - return module; -bad: - Py_XDECREF(module); - return NULL; -} - - -static CYTHON_SMALL_CODE int __pyx_pymod_exec__http_writer(PyObject *__pyx_pyinit_module) -#endif -#endif -{ - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannyDeclarations - #if CYTHON_PEP489_MULTI_PHASE_INIT - if (__pyx_m) { - if (__pyx_m == __pyx_pyinit_module) return 0; - PyErr_SetString(PyExc_RuntimeError, "Module '_http_writer' has already been imported. Re-initialisation is not supported."); - return -1; - } - #elif PY_MAJOR_VERSION >= 3 - if (__pyx_m) return __Pyx_NewRef(__pyx_m); - #endif - #if CYTHON_REFNANNY -__Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); -if (!__Pyx_RefNanny) { - PyErr_Clear(); - __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); - if (!__Pyx_RefNanny) - Py_FatalError("failed to import 'refnanny' module"); -} -#endif - __Pyx_RefNannySetupContext("__Pyx_PyMODINIT_FUNC PyInit__http_writer(void)", 0); - if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #ifdef __Pxy_PyFrame_Initialize_Offsets - __Pxy_PyFrame_Initialize_Offsets(); - #endif - __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) - #ifdef __Pyx_CyFunction_USED - if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_FusedFunction_USED - if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_Coroutine_USED - if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_Generator_USED - if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_AsyncGen_USED - if (__pyx_AsyncGen_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_StopAsyncIteration_USED - if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - /*--- Library function declarations ---*/ - /*--- Threads initialization code ---*/ - #if defined(WITH_THREAD) && PY_VERSION_HEX < 0x030700F0 && defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS - PyEval_InitThreads(); - #endif - /*--- Module creation code ---*/ - #if CYTHON_PEP489_MULTI_PHASE_INIT - __pyx_m = __pyx_pyinit_module; - Py_INCREF(__pyx_m); - #else - #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4("_http_writer", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); - #else - __pyx_m = PyModule_Create(&__pyx_moduledef); - #endif - if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_d); - __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_b); - __pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_cython_runtime); - if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error); - /*--- Initialize various global constants etc. ---*/ - if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) - if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - if (__pyx_module_is_main_aiohttp___http_writer) { - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_name, __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - } - #if PY_MAJOR_VERSION >= 3 - { - PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) - if (!PyDict_GetItemString(modules, "aiohttp._http_writer")) { - if (unlikely(PyDict_SetItemString(modules, "aiohttp._http_writer", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error) - } - } - #endif - /*--- Builtin init code ---*/ - if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - /*--- Constants init code ---*/ - if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - /*--- Global type/function init code ---*/ - (void)__Pyx_modinit_global_init_code(); - (void)__Pyx_modinit_variable_export_code(); - (void)__Pyx_modinit_function_export_code(); - (void)__Pyx_modinit_type_init_code(); - if (unlikely(__Pyx_modinit_type_import_code() < 0)) __PYX_ERR(0, 1, __pyx_L1_error) - (void)__Pyx_modinit_variable_import_code(); - (void)__Pyx_modinit_function_import_code(); - /*--- Execution code ---*/ - #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) - if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - - /* "aiohttp/_http_writer.pyx":8 - * from libc.string cimport memcpy - * - * from multidict import istr # <<<<<<<<<<<<<< - * - * DEF BUF_SIZE = 16 * 1024 # 16KiB - */ - __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 8, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_s_istr); - __Pyx_GIVEREF(__pyx_n_s_istr); - PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_istr); - __pyx_t_2 = __Pyx_Import(__pyx_n_s_multidict, __pyx_t_1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 8, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_istr); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 8, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_istr, __pyx_t_1) < 0) __PYX_ERR(0, 8, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_http_writer.pyx":13 - * cdef char BUFFER[BUF_SIZE] - * - * cdef object _istr = istr # <<<<<<<<<<<<<< - * - * - */ - __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_istr); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_XGOTREF(__pyx_v_7aiohttp_12_http_writer__istr); - __Pyx_DECREF_SET(__pyx_v_7aiohttp_12_http_writer__istr, __pyx_t_2); - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - - /* "aiohttp/_http_writer.pyx":122 - * - * - * def _serialize_headers(str status_line, headers): # <<<<<<<<<<<<<< - * cdef Writer writer - * cdef object key - */ - __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7aiohttp_12_http_writer_1_serialize_headers, NULL, __pyx_n_s_aiohttp__http_writer); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 122, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_serialize_headers, __pyx_t_2) < 0) __PYX_ERR(0, 122, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /* "aiohttp/_http_writer.pyx":1 - * from cpython.bytes cimport PyBytes_FromStringAndSize # <<<<<<<<<<<<<< - * from cpython.exc cimport PyErr_NoMemory - * from cpython.mem cimport PyMem_Free, PyMem_Malloc, PyMem_Realloc - */ - __pyx_t_2 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_2) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - - /*--- Wrapped vars code ---*/ - - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_2); - if (__pyx_m) { - if (__pyx_d) { - __Pyx_AddTraceback("init aiohttp._http_writer", __pyx_clineno, __pyx_lineno, __pyx_filename); - } - Py_CLEAR(__pyx_m); - } else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_ImportError, "init aiohttp._http_writer"); - } - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - #if CYTHON_PEP489_MULTI_PHASE_INIT - return (__pyx_m != NULL) ? 0 : -1; - #elif PY_MAJOR_VERSION >= 3 - return __pyx_m; - #else - return; - #endif -} - -/* --- Runtime support code --- */ -/* Refnanny */ -#if CYTHON_REFNANNY -static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { - PyObject *m = NULL, *p = NULL; - void *r = NULL; - m = PyImport_ImportModule(modname); - if (!m) goto end; - p = PyObject_GetAttrString(m, "RefNannyAPI"); - if (!p) goto end; - r = PyLong_AsVoidPtr(p); -end: - Py_XDECREF(p); - Py_XDECREF(m); - return (__Pyx_RefNannyAPIStruct *)r; -} -#endif - -/* PyObjectGetAttrStr */ -#if CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { - PyTypeObject* tp = Py_TYPE(obj); - if (likely(tp->tp_getattro)) - return tp->tp_getattro(obj, attr_name); -#if PY_MAJOR_VERSION < 3 - if (likely(tp->tp_getattr)) - return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); -#endif - return PyObject_GetAttr(obj, attr_name); -} -#endif - -/* GetBuiltinName */ -static PyObject *__Pyx_GetBuiltinName(PyObject *name) { - PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); - if (unlikely(!result)) { - PyErr_Format(PyExc_NameError, -#if PY_MAJOR_VERSION >= 3 - "name '%U' is not defined", name); -#else - "name '%.200s' is not defined", PyString_AS_STRING(name)); -#endif - } - return result; -} - -/* PyErrFetchRestore */ -#if CYTHON_FAST_THREAD_STATE -static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - tmp_type = tstate->curexc_type; - tmp_value = tstate->curexc_value; - tmp_tb = tstate->curexc_traceback; - tstate->curexc_type = type; - tstate->curexc_value = value; - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -} -static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { - *type = tstate->curexc_type; - *value = tstate->curexc_value; - *tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; -} -#endif - -/* WriteUnraisableException */ -static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, - CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename, - int full_traceback, CYTHON_UNUSED int nogil) { - PyObject *old_exc, *old_val, *old_tb; - PyObject *ctx; - __Pyx_PyThreadState_declare -#ifdef WITH_THREAD - PyGILState_STATE state; - if (nogil) - state = PyGILState_Ensure(); -#ifdef _MSC_VER - else state = (PyGILState_STATE)-1; -#endif -#endif - __Pyx_PyThreadState_assign - __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); - if (full_traceback) { - Py_XINCREF(old_exc); - Py_XINCREF(old_val); - Py_XINCREF(old_tb); - __Pyx_ErrRestore(old_exc, old_val, old_tb); - PyErr_PrintEx(1); - } - #if PY_MAJOR_VERSION < 3 - ctx = PyString_FromString(name); - #else - ctx = PyUnicode_FromString(name); - #endif - __Pyx_ErrRestore(old_exc, old_val, old_tb); - if (!ctx) { - PyErr_WriteUnraisable(Py_None); - } else { - PyErr_WriteUnraisable(ctx); - Py_DECREF(ctx); - } -#ifdef WITH_THREAD - if (nogil) - PyGILState_Release(state); -#endif -} - -/* unicode_iter */ -static CYTHON_INLINE int __Pyx_init_unicode_iteration( - PyObject* ustring, Py_ssize_t *length, void** data, int *kind) { -#if CYTHON_PEP393_ENABLED - if (unlikely(__Pyx_PyUnicode_READY(ustring) < 0)) return -1; - *kind = PyUnicode_KIND(ustring); - *length = PyUnicode_GET_LENGTH(ustring); - *data = PyUnicode_DATA(ustring); -#else - *kind = 0; - *length = PyUnicode_GET_SIZE(ustring); - *data = (void*)PyUnicode_AS_UNICODE(ustring); -#endif - return 0; -} - -/* PyCFunctionFastCall */ -#if CYTHON_FAST_PYCCALL -static CYTHON_INLINE PyObject * __Pyx_PyCFunction_FastCall(PyObject *func_obj, PyObject **args, Py_ssize_t nargs) { - PyCFunctionObject *func = (PyCFunctionObject*)func_obj; - PyCFunction meth = PyCFunction_GET_FUNCTION(func); - PyObject *self = PyCFunction_GET_SELF(func); - int flags = PyCFunction_GET_FLAGS(func); - assert(PyCFunction_Check(func)); - assert(METH_FASTCALL == (flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))); - assert(nargs >= 0); - assert(nargs == 0 || args != NULL); - /* _PyCFunction_FastCallDict() must not be called with an exception set, - because it may clear it (directly or indirectly) and so the - caller loses its exception */ - assert(!PyErr_Occurred()); - if ((PY_VERSION_HEX < 0x030700A0) || unlikely(flags & METH_KEYWORDS)) { - return (*((__Pyx_PyCFunctionFastWithKeywords)(void*)meth)) (self, args, nargs, NULL); - } else { - return (*((__Pyx_PyCFunctionFast)(void*)meth)) (self, args, nargs); - } -} -#endif - -/* PyFunctionFastCall */ -#if CYTHON_FAST_PYCALL -static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na, - PyObject *globals) { - PyFrameObject *f; - PyThreadState *tstate = __Pyx_PyThreadState_Current; - PyObject **fastlocals; - Py_ssize_t i; - PyObject *result; - assert(globals != NULL); - /* XXX Perhaps we should create a specialized - PyFrame_New() that doesn't take locals, but does - take builtins without sanity checking them. - */ - assert(tstate != NULL); - f = PyFrame_New(tstate, co, globals, NULL); - if (f == NULL) { - return NULL; - } - fastlocals = __Pyx_PyFrame_GetLocalsplus(f); - for (i = 0; i < na; i++) { - Py_INCREF(*args); - fastlocals[i] = *args++; - } - result = PyEval_EvalFrameEx(f,0); - ++tstate->recursion_depth; - Py_DECREF(f); - --tstate->recursion_depth; - return result; -} -#if 1 || PY_VERSION_HEX < 0x030600B1 -static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) { - PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); - PyObject *globals = PyFunction_GET_GLOBALS(func); - PyObject *argdefs = PyFunction_GET_DEFAULTS(func); - PyObject *closure; -#if PY_MAJOR_VERSION >= 3 - PyObject *kwdefs; -#endif - PyObject *kwtuple, **k; - PyObject **d; - Py_ssize_t nd; - Py_ssize_t nk; - PyObject *result; - assert(kwargs == NULL || PyDict_Check(kwargs)); - nk = kwargs ? PyDict_Size(kwargs) : 0; - if (Py_EnterRecursiveCall((char*)" while calling a Python object")) { - return NULL; - } - if ( -#if PY_MAJOR_VERSION >= 3 - co->co_kwonlyargcount == 0 && -#endif - likely(kwargs == NULL || nk == 0) && - co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { - if (argdefs == NULL && co->co_argcount == nargs) { - result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals); - goto done; - } - else if (nargs == 0 && argdefs != NULL - && co->co_argcount == Py_SIZE(argdefs)) { - /* function called with no arguments, but all parameters have - a default value: use default values as arguments .*/ - args = &PyTuple_GET_ITEM(argdefs, 0); - result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals); - goto done; - } - } - if (kwargs != NULL) { - Py_ssize_t pos, i; - kwtuple = PyTuple_New(2 * nk); - if (kwtuple == NULL) { - result = NULL; - goto done; - } - k = &PyTuple_GET_ITEM(kwtuple, 0); - pos = i = 0; - while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) { - Py_INCREF(k[i]); - Py_INCREF(k[i+1]); - i += 2; - } - nk = i / 2; - } - else { - kwtuple = NULL; - k = NULL; - } - closure = PyFunction_GET_CLOSURE(func); -#if PY_MAJOR_VERSION >= 3 - kwdefs = PyFunction_GET_KW_DEFAULTS(func); -#endif - if (argdefs != NULL) { - d = &PyTuple_GET_ITEM(argdefs, 0); - nd = Py_SIZE(argdefs); - } - else { - d = NULL; - nd = 0; - } -#if PY_MAJOR_VERSION >= 3 - result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL, - args, (int)nargs, - k, (int)nk, - d, (int)nd, kwdefs, closure); -#else - result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL, - args, (int)nargs, - k, (int)nk, - d, (int)nd, closure); -#endif - Py_XDECREF(kwtuple); -done: - Py_LeaveRecursiveCall(); - return result; -} -#endif -#endif - -/* PyObjectCall */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { - PyObject *result; - ternaryfunc call = Py_TYPE(func)->tp_call; - if (unlikely(!call)) - return PyObject_Call(func, arg, kw); - if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) - return NULL; - result = (*call)(func, arg, kw); - Py_LeaveRecursiveCall(); - if (unlikely(!result) && unlikely(!PyErr_Occurred())) { - PyErr_SetString( - PyExc_SystemError, - "NULL result without error in PyObject_Call"); - } - return result; -} -#endif - -/* PyObjectCall2Args */ -static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2) { - PyObject *args, *result = NULL; - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(function)) { - PyObject *args[2] = {arg1, arg2}; - return __Pyx_PyFunction_FastCall(function, args, 2); - } - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(function)) { - PyObject *args[2] = {arg1, arg2}; - return __Pyx_PyCFunction_FastCall(function, args, 2); - } - #endif - args = PyTuple_New(2); - if (unlikely(!args)) goto done; - Py_INCREF(arg1); - PyTuple_SET_ITEM(args, 0, arg1); - Py_INCREF(arg2); - PyTuple_SET_ITEM(args, 1, arg2); - Py_INCREF(function); - result = __Pyx_PyObject_Call(function, args, NULL); - Py_DECREF(args); - Py_DECREF(function); -done: - return result; -} - -/* PyObjectCallMethO */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { - PyObject *self, *result; - PyCFunction cfunc; - cfunc = PyCFunction_GET_FUNCTION(func); - self = PyCFunction_GET_SELF(func); - if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) - return NULL; - result = cfunc(self, arg); - Py_LeaveRecursiveCall(); - if (unlikely(!result) && unlikely(!PyErr_Occurred())) { - PyErr_SetString( - PyExc_SystemError, - "NULL result without error in PyObject_Call"); - } - return result; -} -#endif - -/* PyObjectCallOneArg */ -#if CYTHON_COMPILING_IN_CPYTHON -static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { - PyObject *result; - PyObject *args = PyTuple_New(1); - if (unlikely(!args)) return NULL; - Py_INCREF(arg); - PyTuple_SET_ITEM(args, 0, arg); - result = __Pyx_PyObject_Call(func, args, NULL); - Py_DECREF(args); - return result; -} -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { -#if CYTHON_FAST_PYCALL - if (PyFunction_Check(func)) { - return __Pyx_PyFunction_FastCall(func, &arg, 1); - } -#endif - if (likely(PyCFunction_Check(func))) { - if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { - return __Pyx_PyObject_CallMethO(func, arg); -#if CYTHON_FAST_PYCCALL - } else if (__Pyx_PyFastCFunction_Check(func)) { - return __Pyx_PyCFunction_FastCall(func, &arg, 1); -#endif - } - } - return __Pyx__PyObject_CallOneArg(func, arg); -} -#else -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { - PyObject *result; - PyObject *args = PyTuple_Pack(1, arg); - if (unlikely(!args)) return NULL; - result = __Pyx_PyObject_Call(func, args, NULL); - Py_DECREF(args); - return result; -} -#endif - -/* RaiseException */ -#if PY_MAJOR_VERSION < 3 -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, - CYTHON_UNUSED PyObject *cause) { - __Pyx_PyThreadState_declare - Py_XINCREF(type); - if (!value || value == Py_None) - value = NULL; - else - Py_INCREF(value); - if (!tb || tb == Py_None) - tb = NULL; - else { - Py_INCREF(tb); - if (!PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto raise_error; - } - } - if (PyType_Check(type)) { -#if CYTHON_COMPILING_IN_PYPY - if (!value) { - Py_INCREF(Py_None); - value = Py_None; - } -#endif - PyErr_NormalizeException(&type, &value, &tb); - } else { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto raise_error; - } - value = type; - type = (PyObject*) Py_TYPE(type); - Py_INCREF(type); - if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto raise_error; - } - } - __Pyx_PyThreadState_assign - __Pyx_ErrRestore(type, value, tb); - return; -raise_error: - Py_XDECREF(value); - Py_XDECREF(type); - Py_XDECREF(tb); - return; -} -#else -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { - PyObject* owned_instance = NULL; - if (tb == Py_None) { - tb = 0; - } else if (tb && !PyTraceBack_Check(tb)) { - PyErr_SetString(PyExc_TypeError, - "raise: arg 3 must be a traceback or None"); - goto bad; - } - if (value == Py_None) - value = 0; - if (PyExceptionInstance_Check(type)) { - if (value) { - PyErr_SetString(PyExc_TypeError, - "instance exception may not have a separate value"); - goto bad; - } - value = type; - type = (PyObject*) Py_TYPE(value); - } else if (PyExceptionClass_Check(type)) { - PyObject *instance_class = NULL; - if (value && PyExceptionInstance_Check(value)) { - instance_class = (PyObject*) Py_TYPE(value); - if (instance_class != type) { - int is_subclass = PyObject_IsSubclass(instance_class, type); - if (!is_subclass) { - instance_class = NULL; - } else if (unlikely(is_subclass == -1)) { - goto bad; - } else { - type = instance_class; - } - } - } - if (!instance_class) { - PyObject *args; - if (!value) - args = PyTuple_New(0); - else if (PyTuple_Check(value)) { - Py_INCREF(value); - args = value; - } else - args = PyTuple_Pack(1, value); - if (!args) - goto bad; - owned_instance = PyObject_Call(type, args, NULL); - Py_DECREF(args); - if (!owned_instance) - goto bad; - value = owned_instance; - if (!PyExceptionInstance_Check(value)) { - PyErr_Format(PyExc_TypeError, - "calling %R should have returned an instance of " - "BaseException, not %R", - type, Py_TYPE(value)); - goto bad; - } - } - } else { - PyErr_SetString(PyExc_TypeError, - "raise: exception class must be a subclass of BaseException"); - goto bad; - } - if (cause) { - PyObject *fixed_cause; - if (cause == Py_None) { - fixed_cause = NULL; - } else if (PyExceptionClass_Check(cause)) { - fixed_cause = PyObject_CallObject(cause, NULL); - if (fixed_cause == NULL) - goto bad; - } else if (PyExceptionInstance_Check(cause)) { - fixed_cause = cause; - Py_INCREF(fixed_cause); - } else { - PyErr_SetString(PyExc_TypeError, - "exception causes must derive from " - "BaseException"); - goto bad; - } - PyException_SetCause(value, fixed_cause); - } - PyErr_SetObject(type, value); - if (tb) { -#if CYTHON_COMPILING_IN_PYPY - PyObject *tmp_type, *tmp_value, *tmp_tb; - PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); - Py_INCREF(tb); - PyErr_Restore(tmp_type, tmp_value, tb); - Py_XDECREF(tmp_tb); -#else - PyThreadState *tstate = __Pyx_PyThreadState_Current; - PyObject* tmp_tb = tstate->curexc_traceback; - if (tb != tmp_tb) { - Py_INCREF(tb); - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_tb); - } -#endif - } -bad: - Py_XDECREF(owned_instance); - return; -} -#endif - -/* RaiseArgTupleInvalid */ -static void __Pyx_RaiseArgtupleInvalid( - const char* func_name, - int exact, - Py_ssize_t num_min, - Py_ssize_t num_max, - Py_ssize_t num_found) -{ - Py_ssize_t num_expected; - const char *more_or_less; - if (num_found < num_min) { - num_expected = num_min; - more_or_less = "at least"; - } else { - num_expected = num_max; - more_or_less = "at most"; - } - if (exact) { - more_or_less = "exactly"; - } - PyErr_Format(PyExc_TypeError, - "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", - func_name, more_or_less, num_expected, - (num_expected == 1) ? "" : "s", num_found); -} - -/* RaiseDoubleKeywords */ -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, - PyObject* kw_name) -{ - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION >= 3 - "%s() got multiple values for keyword argument '%U'", func_name, kw_name); - #else - "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AsString(kw_name)); - #endif -} - -/* ParseKeywords */ -static int __Pyx_ParseOptionalKeywords( - PyObject *kwds, - PyObject **argnames[], - PyObject *kwds2, - PyObject *values[], - Py_ssize_t num_pos_args, - const char* function_name) -{ - PyObject *key = 0, *value = 0; - Py_ssize_t pos = 0; - PyObject*** name; - PyObject*** first_kw_arg = argnames + num_pos_args; - while (PyDict_Next(kwds, &pos, &key, &value)) { - name = first_kw_arg; - while (*name && (**name != key)) name++; - if (*name) { - values[name-argnames] = value; - continue; - } - name = first_kw_arg; - #if PY_MAJOR_VERSION < 3 - if (likely(PyString_Check(key))) { - while (*name) { - if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) - && _PyString_Eq(**name, key)) { - values[name-argnames] = value; - break; - } - name++; - } - if (*name) continue; - else { - PyObject*** argname = argnames; - while (argname != first_kw_arg) { - if ((**argname == key) || ( - (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) - && _PyString_Eq(**argname, key))) { - goto arg_passed_twice; - } - argname++; - } - } - } else - #endif - if (likely(PyUnicode_Check(key))) { - while (*name) { - int cmp = (**name == key) ? 0 : - #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 - (__Pyx_PyUnicode_GET_LENGTH(**name) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : - #endif - PyUnicode_Compare(**name, key); - if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; - if (cmp == 0) { - values[name-argnames] = value; - break; - } - name++; - } - if (*name) continue; - else { - PyObject*** argname = argnames; - while (argname != first_kw_arg) { - int cmp = (**argname == key) ? 0 : - #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 - (__Pyx_PyUnicode_GET_LENGTH(**argname) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : - #endif - PyUnicode_Compare(**argname, key); - if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; - if (cmp == 0) goto arg_passed_twice; - argname++; - } - } - } else - goto invalid_keyword_type; - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; - } - } - return 0; -arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, key); - goto bad; -invalid_keyword_type: - PyErr_Format(PyExc_TypeError, - "%.200s() keywords must be strings", function_name); - goto bad; -invalid_keyword: - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION < 3 - "%.200s() got an unexpected keyword argument '%.200s'", - function_name, PyString_AsString(key)); - #else - "%s() got an unexpected keyword argument '%U'", - function_name, key); - #endif -bad: - return -1; -} - -/* ArgTypeTest */ -static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact) -{ - if (unlikely(!type)) { - PyErr_SetString(PyExc_SystemError, "Missing type object"); - return 0; - } - else if (exact) { - #if PY_MAJOR_VERSION == 2 - if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; - #endif - } - else { - if (likely(__Pyx_TypeCheck(obj, type))) return 1; - } - PyErr_Format(PyExc_TypeError, - "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", - name, type->tp_name, Py_TYPE(obj)->tp_name); - return 0; -} - -/* IterFinish */ -static CYTHON_INLINE int __Pyx_IterFinish(void) { -#if CYTHON_FAST_THREAD_STATE - PyThreadState *tstate = __Pyx_PyThreadState_Current; - PyObject* exc_type = tstate->curexc_type; - if (unlikely(exc_type)) { - if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) { - PyObject *exc_value, *exc_tb; - exc_value = tstate->curexc_value; - exc_tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; - Py_DECREF(exc_type); - Py_XDECREF(exc_value); - Py_XDECREF(exc_tb); - return 0; - } else { - return -1; - } - } - return 0; -#else - if (unlikely(PyErr_Occurred())) { - if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { - PyErr_Clear(); - return 0; - } else { - return -1; - } - } - return 0; -#endif -} - -/* PyObjectCallNoArg */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { -#if CYTHON_FAST_PYCALL - if (PyFunction_Check(func)) { - return __Pyx_PyFunction_FastCall(func, NULL, 0); - } -#endif -#ifdef __Pyx_CyFunction_USED - if (likely(PyCFunction_Check(func) || __Pyx_CyFunction_Check(func))) -#else - if (likely(PyCFunction_Check(func))) -#endif - { - if (likely(PyCFunction_GET_FLAGS(func) & METH_NOARGS)) { - return __Pyx_PyObject_CallMethO(func, NULL); - } - } - return __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL); -} -#endif - -/* PyObjectGetMethod */ -static int __Pyx_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method) { - PyObject *attr; -#if CYTHON_UNPACK_METHODS && CYTHON_COMPILING_IN_CPYTHON && CYTHON_USE_PYTYPE_LOOKUP - PyTypeObject *tp = Py_TYPE(obj); - PyObject *descr; - descrgetfunc f = NULL; - PyObject **dictptr, *dict; - int meth_found = 0; - assert (*method == NULL); - if (unlikely(tp->tp_getattro != PyObject_GenericGetAttr)) { - attr = __Pyx_PyObject_GetAttrStr(obj, name); - goto try_unpack; - } - if (unlikely(tp->tp_dict == NULL) && unlikely(PyType_Ready(tp) < 0)) { - return 0; - } - descr = _PyType_Lookup(tp, name); - if (likely(descr != NULL)) { - Py_INCREF(descr); -#if PY_MAJOR_VERSION >= 3 - #ifdef __Pyx_CyFunction_USED - if (likely(PyFunction_Check(descr) || (Py_TYPE(descr) == &PyMethodDescr_Type) || __Pyx_CyFunction_Check(descr))) - #else - if (likely(PyFunction_Check(descr) || (Py_TYPE(descr) == &PyMethodDescr_Type))) - #endif -#else - #ifdef __Pyx_CyFunction_USED - if (likely(PyFunction_Check(descr) || __Pyx_CyFunction_Check(descr))) - #else - if (likely(PyFunction_Check(descr))) - #endif -#endif - { - meth_found = 1; - } else { - f = Py_TYPE(descr)->tp_descr_get; - if (f != NULL && PyDescr_IsData(descr)) { - attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); - Py_DECREF(descr); - goto try_unpack; - } - } - } - dictptr = _PyObject_GetDictPtr(obj); - if (dictptr != NULL && (dict = *dictptr) != NULL) { - Py_INCREF(dict); - attr = __Pyx_PyDict_GetItemStr(dict, name); - if (attr != NULL) { - Py_INCREF(attr); - Py_DECREF(dict); - Py_XDECREF(descr); - goto try_unpack; - } - Py_DECREF(dict); - } - if (meth_found) { - *method = descr; - return 1; - } - if (f != NULL) { - attr = f(descr, obj, (PyObject *)Py_TYPE(obj)); - Py_DECREF(descr); - goto try_unpack; - } - if (descr != NULL) { - *method = descr; - return 0; - } - PyErr_Format(PyExc_AttributeError, -#if PY_MAJOR_VERSION >= 3 - "'%.50s' object has no attribute '%U'", - tp->tp_name, name); -#else - "'%.50s' object has no attribute '%.400s'", - tp->tp_name, PyString_AS_STRING(name)); -#endif - return 0; -#else - attr = __Pyx_PyObject_GetAttrStr(obj, name); - goto try_unpack; -#endif -try_unpack: -#if CYTHON_UNPACK_METHODS - if (likely(attr) && PyMethod_Check(attr) && likely(PyMethod_GET_SELF(attr) == obj)) { - PyObject *function = PyMethod_GET_FUNCTION(attr); - Py_INCREF(function); - Py_DECREF(attr); - *method = function; - return 1; - } -#endif - *method = attr; - return 0; -} - -/* PyObjectCallMethod0 */ -static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name) { - PyObject *method = NULL, *result = NULL; - int is_method = __Pyx_PyObject_GetMethod(obj, method_name, &method); - if (likely(is_method)) { - result = __Pyx_PyObject_CallOneArg(method, obj); - Py_DECREF(method); - return result; - } - if (unlikely(!method)) goto bad; - result = __Pyx_PyObject_CallNoArg(method); - Py_DECREF(method); -bad: - return result; -} - -/* RaiseNeedMoreValuesToUnpack */ -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { - PyErr_Format(PyExc_ValueError, - "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", - index, (index == 1) ? "" : "s"); -} - -/* RaiseTooManyValuesToUnpack */ -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { - PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); -} - -/* UnpackItemEndCheck */ -static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { - if (unlikely(retval)) { - Py_DECREF(retval); - __Pyx_RaiseTooManyValuesError(expected); - return -1; - } else { - return __Pyx_IterFinish(); - } - return 0; -} - -/* RaiseNoneIterError */ -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); -} - -/* UnpackTupleError */ -static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { - if (t == Py_None) { - __Pyx_RaiseNoneNotIterableError(); - } else if (PyTuple_GET_SIZE(t) < index) { - __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t)); - } else { - __Pyx_RaiseTooManyValuesError(index); - } -} - -/* UnpackTuple2 */ -static CYTHON_INLINE int __Pyx_unpack_tuple2_exact( - PyObject* tuple, PyObject** pvalue1, PyObject** pvalue2, int decref_tuple) { - PyObject *value1 = NULL, *value2 = NULL; -#if CYTHON_COMPILING_IN_PYPY - value1 = PySequence_ITEM(tuple, 0); if (unlikely(!value1)) goto bad; - value2 = PySequence_ITEM(tuple, 1); if (unlikely(!value2)) goto bad; -#else - value1 = PyTuple_GET_ITEM(tuple, 0); Py_INCREF(value1); - value2 = PyTuple_GET_ITEM(tuple, 1); Py_INCREF(value2); -#endif - if (decref_tuple) { - Py_DECREF(tuple); - } - *pvalue1 = value1; - *pvalue2 = value2; - return 0; -#if CYTHON_COMPILING_IN_PYPY -bad: - Py_XDECREF(value1); - Py_XDECREF(value2); - if (decref_tuple) { Py_XDECREF(tuple); } - return -1; -#endif -} -static int __Pyx_unpack_tuple2_generic(PyObject* tuple, PyObject** pvalue1, PyObject** pvalue2, - int has_known_size, int decref_tuple) { - Py_ssize_t index; - PyObject *value1 = NULL, *value2 = NULL, *iter = NULL; - iternextfunc iternext; - iter = PyObject_GetIter(tuple); - if (unlikely(!iter)) goto bad; - if (decref_tuple) { Py_DECREF(tuple); tuple = NULL; } - iternext = Py_TYPE(iter)->tp_iternext; - value1 = iternext(iter); if (unlikely(!value1)) { index = 0; goto unpacking_failed; } - value2 = iternext(iter); if (unlikely(!value2)) { index = 1; goto unpacking_failed; } - if (!has_known_size && unlikely(__Pyx_IternextUnpackEndCheck(iternext(iter), 2))) goto bad; - Py_DECREF(iter); - *pvalue1 = value1; - *pvalue2 = value2; - return 0; -unpacking_failed: - if (!has_known_size && __Pyx_IterFinish() == 0) - __Pyx_RaiseNeedMoreValuesError(index); -bad: - Py_XDECREF(iter); - Py_XDECREF(value1); - Py_XDECREF(value2); - if (decref_tuple) { Py_XDECREF(tuple); } - return -1; -} - -/* dict_iter */ -static CYTHON_INLINE PyObject* __Pyx_dict_iterator(PyObject* iterable, int is_dict, PyObject* method_name, - Py_ssize_t* p_orig_length, int* p_source_is_dict) { - is_dict = is_dict || likely(PyDict_CheckExact(iterable)); - *p_source_is_dict = is_dict; - if (is_dict) { -#if !CYTHON_COMPILING_IN_PYPY - *p_orig_length = PyDict_Size(iterable); - Py_INCREF(iterable); - return iterable; -#elif PY_MAJOR_VERSION >= 3 - static PyObject *py_items = NULL, *py_keys = NULL, *py_values = NULL; - PyObject **pp = NULL; - if (method_name) { - const char *name = PyUnicode_AsUTF8(method_name); - if (strcmp(name, "iteritems") == 0) pp = &py_items; - else if (strcmp(name, "iterkeys") == 0) pp = &py_keys; - else if (strcmp(name, "itervalues") == 0) pp = &py_values; - if (pp) { - if (!*pp) { - *pp = PyUnicode_FromString(name + 4); - if (!*pp) - return NULL; - } - method_name = *pp; - } - } -#endif - } - *p_orig_length = 0; - if (method_name) { - PyObject* iter; - iterable = __Pyx_PyObject_CallMethod0(iterable, method_name); - if (!iterable) - return NULL; -#if !CYTHON_COMPILING_IN_PYPY - if (PyTuple_CheckExact(iterable) || PyList_CheckExact(iterable)) - return iterable; -#endif - iter = PyObject_GetIter(iterable); - Py_DECREF(iterable); - return iter; - } - return PyObject_GetIter(iterable); -} -static CYTHON_INLINE int __Pyx_dict_iter_next( - PyObject* iter_obj, CYTHON_NCP_UNUSED Py_ssize_t orig_length, CYTHON_NCP_UNUSED Py_ssize_t* ppos, - PyObject** pkey, PyObject** pvalue, PyObject** pitem, int source_is_dict) { - PyObject* next_item; -#if !CYTHON_COMPILING_IN_PYPY - if (source_is_dict) { - PyObject *key, *value; - if (unlikely(orig_length != PyDict_Size(iter_obj))) { - PyErr_SetString(PyExc_RuntimeError, "dictionary changed size during iteration"); - return -1; - } - if (unlikely(!PyDict_Next(iter_obj, ppos, &key, &value))) { - return 0; - } - if (pitem) { - PyObject* tuple = PyTuple_New(2); - if (unlikely(!tuple)) { - return -1; - } - Py_INCREF(key); - Py_INCREF(value); - PyTuple_SET_ITEM(tuple, 0, key); - PyTuple_SET_ITEM(tuple, 1, value); - *pitem = tuple; - } else { - if (pkey) { - Py_INCREF(key); - *pkey = key; - } - if (pvalue) { - Py_INCREF(value); - *pvalue = value; - } - } - return 1; - } else if (PyTuple_CheckExact(iter_obj)) { - Py_ssize_t pos = *ppos; - if (unlikely(pos >= PyTuple_GET_SIZE(iter_obj))) return 0; - *ppos = pos + 1; - next_item = PyTuple_GET_ITEM(iter_obj, pos); - Py_INCREF(next_item); - } else if (PyList_CheckExact(iter_obj)) { - Py_ssize_t pos = *ppos; - if (unlikely(pos >= PyList_GET_SIZE(iter_obj))) return 0; - *ppos = pos + 1; - next_item = PyList_GET_ITEM(iter_obj, pos); - Py_INCREF(next_item); - } else -#endif - { - next_item = PyIter_Next(iter_obj); - if (unlikely(!next_item)) { - return __Pyx_IterFinish(); - } - } - if (pitem) { - *pitem = next_item; - } else if (pkey && pvalue) { - if (__Pyx_unpack_tuple2(next_item, pkey, pvalue, source_is_dict, source_is_dict, 1)) - return -1; - } else if (pkey) { - *pkey = next_item; - } else { - *pvalue = next_item; - } - return 1; -} - -/* GetTopmostException */ -#if CYTHON_USE_EXC_INFO_STACK -static _PyErr_StackItem * -__Pyx_PyErr_GetTopmostException(PyThreadState *tstate) -{ - _PyErr_StackItem *exc_info = tstate->exc_info; - while ((exc_info->exc_type == NULL || exc_info->exc_type == Py_None) && - exc_info->previous_item != NULL) - { - exc_info = exc_info->previous_item; - } - return exc_info; -} -#endif - -/* ReRaiseException */ -static CYTHON_INLINE void __Pyx_ReraiseException(void) { - PyObject *type = NULL, *value = NULL, *tb = NULL; -#if CYTHON_FAST_THREAD_STATE - PyThreadState *tstate = PyThreadState_GET(); - #if CYTHON_USE_EXC_INFO_STACK - _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); - type = exc_info->exc_type; - value = exc_info->exc_value; - tb = exc_info->exc_traceback; - #else - type = tstate->exc_type; - value = tstate->exc_value; - tb = tstate->exc_traceback; - #endif -#else - PyErr_GetExcInfo(&type, &value, &tb); -#endif - if (!type || type == Py_None) { -#if !CYTHON_FAST_THREAD_STATE - Py_XDECREF(type); - Py_XDECREF(value); - Py_XDECREF(tb); -#endif - PyErr_SetString(PyExc_RuntimeError, - "No active exception to reraise"); - } else { -#if CYTHON_FAST_THREAD_STATE - Py_INCREF(type); - Py_XINCREF(value); - Py_XINCREF(tb); -#endif - PyErr_Restore(type, value, tb); - } -} - -/* GetException */ -#if CYTHON_FAST_THREAD_STATE -static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) -#else -static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) -#endif -{ - PyObject *local_type, *local_value, *local_tb; -#if CYTHON_FAST_THREAD_STATE - PyObject *tmp_type, *tmp_value, *tmp_tb; - local_type = tstate->curexc_type; - local_value = tstate->curexc_value; - local_tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; -#else - PyErr_Fetch(&local_type, &local_value, &local_tb); -#endif - PyErr_NormalizeException(&local_type, &local_value, &local_tb); -#if CYTHON_FAST_THREAD_STATE - if (unlikely(tstate->curexc_type)) -#else - if (unlikely(PyErr_Occurred())) -#endif - goto bad; - #if PY_MAJOR_VERSION >= 3 - if (local_tb) { - if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) - goto bad; - } - #endif - Py_XINCREF(local_tb); - Py_XINCREF(local_type); - Py_XINCREF(local_value); - *type = local_type; - *value = local_value; - *tb = local_tb; -#if CYTHON_FAST_THREAD_STATE - #if CYTHON_USE_EXC_INFO_STACK - { - _PyErr_StackItem *exc_info = tstate->exc_info; - tmp_type = exc_info->exc_type; - tmp_value = exc_info->exc_value; - tmp_tb = exc_info->exc_traceback; - exc_info->exc_type = local_type; - exc_info->exc_value = local_value; - exc_info->exc_traceback = local_tb; - } - #else - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - tstate->exc_type = local_type; - tstate->exc_value = local_value; - tstate->exc_traceback = local_tb; - #endif - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -#else - PyErr_SetExcInfo(local_type, local_value, local_tb); -#endif - return 0; -bad: - *type = 0; - *value = 0; - *tb = 0; - Py_XDECREF(local_type); - Py_XDECREF(local_value); - Py_XDECREF(local_tb); - return -1; -} - -/* SwapException */ -#if CYTHON_FAST_THREAD_STATE -static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - #if CYTHON_USE_EXC_INFO_STACK - _PyErr_StackItem *exc_info = tstate->exc_info; - tmp_type = exc_info->exc_type; - tmp_value = exc_info->exc_value; - tmp_tb = exc_info->exc_traceback; - exc_info->exc_type = *type; - exc_info->exc_value = *value; - exc_info->exc_traceback = *tb; - #else - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - tstate->exc_type = *type; - tstate->exc_value = *value; - tstate->exc_traceback = *tb; - #endif - *type = tmp_type; - *value = tmp_value; - *tb = tmp_tb; -} -#else -static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); - PyErr_SetExcInfo(*type, *value, *tb); - *type = tmp_type; - *value = tmp_value; - *tb = tmp_tb; -} -#endif - -/* SaveResetException */ -#if CYTHON_FAST_THREAD_STATE -static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { - #if CYTHON_USE_EXC_INFO_STACK - _PyErr_StackItem *exc_info = __Pyx_PyErr_GetTopmostException(tstate); - *type = exc_info->exc_type; - *value = exc_info->exc_value; - *tb = exc_info->exc_traceback; - #else - *type = tstate->exc_type; - *value = tstate->exc_value; - *tb = tstate->exc_traceback; - #endif - Py_XINCREF(*type); - Py_XINCREF(*value); - Py_XINCREF(*tb); -} -static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - #if CYTHON_USE_EXC_INFO_STACK - _PyErr_StackItem *exc_info = tstate->exc_info; - tmp_type = exc_info->exc_type; - tmp_value = exc_info->exc_value; - tmp_tb = exc_info->exc_traceback; - exc_info->exc_type = type; - exc_info->exc_value = value; - exc_info->exc_traceback = tb; - #else - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - tstate->exc_type = type; - tstate->exc_value = value; - tstate->exc_traceback = tb; - #endif - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -} -#endif - -/* TypeImport */ -#ifndef __PYX_HAVE_RT_ImportType -#define __PYX_HAVE_RT_ImportType -static PyTypeObject *__Pyx_ImportType(PyObject *module, const char *module_name, const char *class_name, - size_t size, enum __Pyx_ImportType_CheckSize check_size) -{ - PyObject *result = 0; - char warning[200]; - Py_ssize_t basicsize; -#ifdef Py_LIMITED_API - PyObject *py_basicsize; -#endif - result = PyObject_GetAttrString(module, class_name); - if (!result) - goto bad; - if (!PyType_Check(result)) { - PyErr_Format(PyExc_TypeError, - "%.200s.%.200s is not a type object", - module_name, class_name); - goto bad; - } -#ifndef Py_LIMITED_API - basicsize = ((PyTypeObject *)result)->tp_basicsize; -#else - py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); - if (!py_basicsize) - goto bad; - basicsize = PyLong_AsSsize_t(py_basicsize); - Py_DECREF(py_basicsize); - py_basicsize = 0; - if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) - goto bad; -#endif - if ((size_t)basicsize < size) { - PyErr_Format(PyExc_ValueError, - "%.200s.%.200s size changed, may indicate binary incompatibility. " - "Expected %zd from C header, got %zd from PyObject", - module_name, class_name, size, basicsize); - goto bad; - } - if (check_size == __Pyx_ImportType_CheckSize_Error && (size_t)basicsize != size) { - PyErr_Format(PyExc_ValueError, - "%.200s.%.200s size changed, may indicate binary incompatibility. " - "Expected %zd from C header, got %zd from PyObject", - module_name, class_name, size, basicsize); - goto bad; - } - else if (check_size == __Pyx_ImportType_CheckSize_Warn && (size_t)basicsize > size) { - PyOS_snprintf(warning, sizeof(warning), - "%s.%s size changed, may indicate binary incompatibility. " - "Expected %zd from C header, got %zd from PyObject", - module_name, class_name, size, basicsize); - if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; - } - return (PyTypeObject *)result; -bad: - Py_XDECREF(result); - return NULL; -} -#endif - -/* Import */ -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { - PyObject *empty_list = 0; - PyObject *module = 0; - PyObject *global_dict = 0; - PyObject *empty_dict = 0; - PyObject *list; - #if PY_MAJOR_VERSION < 3 - PyObject *py_import; - py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); - if (!py_import) - goto bad; - #endif - if (from_list) - list = from_list; - else { - empty_list = PyList_New(0); - if (!empty_list) - goto bad; - list = empty_list; - } - global_dict = PyModule_GetDict(__pyx_m); - if (!global_dict) - goto bad; - empty_dict = PyDict_New(); - if (!empty_dict) - goto bad; - { - #if PY_MAJOR_VERSION >= 3 - if (level == -1) { - if ((1) && (strchr(__Pyx_MODULE_NAME, '.'))) { - module = PyImport_ImportModuleLevelObject( - name, global_dict, empty_dict, list, 1); - if (!module) { - if (!PyErr_ExceptionMatches(PyExc_ImportError)) - goto bad; - PyErr_Clear(); - } - } - level = 0; - } - #endif - if (!module) { - #if PY_MAJOR_VERSION < 3 - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, (PyObject *)NULL); - Py_DECREF(py_level); - #else - module = PyImport_ImportModuleLevelObject( - name, global_dict, empty_dict, list, level); - #endif - } - } -bad: - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(py_import); - #endif - Py_XDECREF(empty_list); - Py_XDECREF(empty_dict); - return module; -} - -/* ImportFrom */ -static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { - PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); - if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Format(PyExc_ImportError, - #if PY_MAJOR_VERSION < 3 - "cannot import name %.230s", PyString_AS_STRING(name)); - #else - "cannot import name %S", name); - #endif - } - return value; -} - -/* PyDictVersioning */ -#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) { - PyObject *dict = Py_TYPE(obj)->tp_dict; - return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0; -} -static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) { - PyObject **dictptr = NULL; - Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset; - if (offset) { -#if CYTHON_COMPILING_IN_CPYTHON - dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj); -#else - dictptr = _PyObject_GetDictPtr(obj); -#endif - } - return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0; -} -static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) { - PyObject *dict = Py_TYPE(obj)->tp_dict; - if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict))) - return 0; - return obj_dict_version == __Pyx_get_object_dict_version(obj); -} -#endif - -/* GetModuleGlobalName */ -#if CYTHON_USE_DICT_VERSIONS -static PyObject *__Pyx__GetModuleGlobalName(PyObject *name, PY_UINT64_T *dict_version, PyObject **dict_cached_value) -#else -static CYTHON_INLINE PyObject *__Pyx__GetModuleGlobalName(PyObject *name) -#endif -{ - PyObject *result; -#if !CYTHON_AVOID_BORROWED_REFS -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 - result = _PyDict_GetItem_KnownHash(__pyx_d, name, ((PyASCIIObject *) name)->hash); - __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) - if (likely(result)) { - return __Pyx_NewRef(result); - } else if (unlikely(PyErr_Occurred())) { - return NULL; - } -#else - result = PyDict_GetItem(__pyx_d, name); - __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) - if (likely(result)) { - return __Pyx_NewRef(result); - } -#endif -#else - result = PyObject_GetItem(__pyx_d, name); - __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) - if (likely(result)) { - return __Pyx_NewRef(result); - } - PyErr_Clear(); -#endif - return __Pyx_GetBuiltinName(name); -} - -/* CLineInTraceback */ -#ifndef CYTHON_CLINE_IN_TRACEBACK -static int __Pyx_CLineForTraceback(CYTHON_NCP_UNUSED PyThreadState *tstate, int c_line) { - PyObject *use_cline; - PyObject *ptype, *pvalue, *ptraceback; -#if CYTHON_COMPILING_IN_CPYTHON - PyObject **cython_runtime_dict; -#endif - if (unlikely(!__pyx_cython_runtime)) { - return c_line; - } - __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); -#if CYTHON_COMPILING_IN_CPYTHON - cython_runtime_dict = _PyObject_GetDictPtr(__pyx_cython_runtime); - if (likely(cython_runtime_dict)) { - __PYX_PY_DICT_LOOKUP_IF_MODIFIED( - use_cline, *cython_runtime_dict, - __Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_n_s_cline_in_traceback)) - } else -#endif - { - PyObject *use_cline_obj = __Pyx_PyObject_GetAttrStr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback); - if (use_cline_obj) { - use_cline = PyObject_Not(use_cline_obj) ? Py_False : Py_True; - Py_DECREF(use_cline_obj); - } else { - PyErr_Clear(); - use_cline = NULL; - } - } - if (!use_cline) { - c_line = 0; - PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False); - } - else if (use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { - c_line = 0; - } - __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); - return c_line; -} -#endif - -/* CodeObjectCache */ -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { - int start = 0, mid = 0, end = count - 1; - if (end >= 0 && code_line > entries[end].code_line) { - return count; - } - while (start < end) { - mid = start + (end - start) / 2; - if (code_line < entries[mid].code_line) { - end = mid; - } else if (code_line > entries[mid].code_line) { - start = mid + 1; - } else { - return mid; - } - } - if (code_line <= entries[mid].code_line) { - return mid; - } else { - return mid + 1; - } -} -static PyCodeObject *__pyx_find_code_object(int code_line) { - PyCodeObject* code_object; - int pos; - if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { - return NULL; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { - return NULL; - } - code_object = __pyx_code_cache.entries[pos].code_object; - Py_INCREF(code_object); - return code_object; -} -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { - int pos, i; - __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; - if (unlikely(!code_line)) { - return; - } - if (unlikely(!entries)) { - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); - if (likely(entries)) { - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = 64; - __pyx_code_cache.count = 1; - entries[0].code_line = code_line; - entries[0].code_object = code_object; - Py_INCREF(code_object); - } - return; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { - PyCodeObject* tmp = entries[pos].code_object; - entries[pos].code_object = code_object; - Py_DECREF(tmp); - return; - } - if (__pyx_code_cache.count == __pyx_code_cache.max_count) { - int new_max = __pyx_code_cache.max_count + 64; - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( - __pyx_code_cache.entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry)); - if (unlikely(!entries)) { - return; - } - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = new_max; - } - for (i=__pyx_code_cache.count; i>pos; i--) { - entries[i] = entries[i-1]; - } - entries[pos].code_line = code_line; - entries[pos].code_object = code_object; - __pyx_code_cache.count++; - Py_INCREF(code_object); -} - -/* AddTraceback */ -#include "compile.h" -#include "frameobject.h" -#include "traceback.h" -static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( - const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyObject *py_srcfile = 0; - PyObject *py_funcname = 0; - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(filename); - #else - py_srcfile = PyUnicode_FromString(filename); - #endif - if (!py_srcfile) goto bad; - if (c_line) { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #endif - } - else { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromString(funcname); - #else - py_funcname = PyUnicode_FromString(funcname); - #endif - } - if (!py_funcname) goto bad; - py_code = __Pyx_PyCode_New( - 0, - 0, - 0, - 0, - 0, - __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ - py_srcfile, /*PyObject *filename,*/ - py_funcname, /*PyObject *name,*/ - py_line, - __pyx_empty_bytes /*PyObject *lnotab*/ - ); - Py_DECREF(py_srcfile); - Py_DECREF(py_funcname); - return py_code; -bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); - return NULL; -} -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - PyThreadState *tstate = __Pyx_PyThreadState_Current; - if (c_line) { - c_line = __Pyx_CLineForTraceback(tstate, c_line); - } - py_code = __pyx_find_code_object(c_line ? -c_line : py_line); - if (!py_code) { - py_code = __Pyx_CreateCodeObjectForTraceback( - funcname, c_line, py_line, filename); - if (!py_code) goto bad; - __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); - } - py_frame = PyFrame_New( - tstate, /*PyThreadState *tstate,*/ - py_code, /*PyCodeObject *code,*/ - __pyx_d, /*PyObject *globals,*/ - 0 /*PyObject *locals*/ - ); - if (!py_frame) goto bad; - __Pyx_PyFrame_SetLineNumber(py_frame, py_line); - PyTraceBack_Here(py_frame); -bad: - Py_XDECREF(py_code); - Py_XDECREF(py_frame); -} - -/* CIntToPy */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - const long neg_one = (long) -1, const_zero = (long) 0; -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic pop -#endif - const int is_unsigned = neg_one > const_zero; - if (is_unsigned) { - if (sizeof(long) < sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof(long) <= sizeof(unsigned long)) { - return PyLong_FromUnsignedLong((unsigned long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); -#endif - } - } else { - if (sizeof(long) <= sizeof(long)) { - return PyInt_FromLong((long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { - return PyLong_FromLongLong((PY_LONG_LONG) value); -#endif - } - } - { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&value; - return _PyLong_FromByteArray(bytes, sizeof(long), - little, !is_unsigned); - } -} - -/* CIntFromPyVerify */ -#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ - __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) -#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ - __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) -#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ - {\ - func_type value = func_value;\ - if (sizeof(target_type) < sizeof(func_type)) {\ - if (unlikely(value != (func_type) (target_type) value)) {\ - func_type zero = 0;\ - if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ - return (target_type) -1;\ - if (is_unsigned && unlikely(value < zero))\ - goto raise_neg_overflow;\ - else\ - goto raise_overflow;\ - }\ - }\ - return (target_type) value;\ - } - -/* CIntFromPy */ -static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - const long neg_one = (long) -1, const_zero = (long) 0; -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic pop -#endif - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - if (sizeof(long) < sizeof(long)) { - __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) - } else { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - goto raise_neg_overflow; - } - return (long) val; - } - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (long) 0; - case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0]) - case 2: - if (8 * sizeof(long) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) { - return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - case 3: - if (8 * sizeof(long) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) { - return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - case 4: - if (8 * sizeof(long) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) { - return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - } -#endif -#if CYTHON_COMPILING_IN_CPYTHON - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } -#else - { - int result = PyObject_RichCompareBool(x, Py_False, Py_LT); - if (unlikely(result < 0)) - return (long) -1; - if (unlikely(result == 1)) - goto raise_neg_overflow; - } -#endif - if (sizeof(long) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) -#endif - } - } else { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (long) 0; - case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0])) - case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0]) - case -2: - if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 2: - if (8 * sizeof(long) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case -3: - if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 3: - if (8 * sizeof(long) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case -4: - if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 4: - if (8 * sizeof(long) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - } -#endif - if (sizeof(long) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) -#endif - } - } - { -#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); -#else - long val; - PyObject *v = __Pyx_PyNumber_IntOrLong(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } -#endif - return (long) -1; - } - } else { - long val; - PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); - if (!tmp) return (long) -1; - val = __Pyx_PyInt_As_long(tmp); - Py_DECREF(tmp); - return val; - } -raise_overflow: - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to long"); - return (long) -1; -raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long) -1; -} - -/* CIntFromPy */ -static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - const int neg_one = (int) -1, const_zero = (int) 0; -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic pop -#endif - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - if (sizeof(int) < sizeof(long)) { - __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) - } else { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - goto raise_neg_overflow; - } - return (int) val; - } - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (int) 0; - case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0]) - case 2: - if (8 * sizeof(int) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) { - return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - case 3: - if (8 * sizeof(int) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) { - return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - case 4: - if (8 * sizeof(int) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) { - return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - } -#endif -#if CYTHON_COMPILING_IN_CPYTHON - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } -#else - { - int result = PyObject_RichCompareBool(x, Py_False, Py_LT); - if (unlikely(result < 0)) - return (int) -1; - if (unlikely(result == 1)) - goto raise_neg_overflow; - } -#endif - if (sizeof(int) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) -#endif - } - } else { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (int) 0; - case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0])) - case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0]) - case -2: - if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 2: - if (8 * sizeof(int) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case -3: - if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 3: - if (8 * sizeof(int) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case -4: - if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 4: - if (8 * sizeof(int) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { - return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - } -#endif - if (sizeof(int) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) -#endif - } - } - { -#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); -#else - int val; - PyObject *v = __Pyx_PyNumber_IntOrLong(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } -#endif - return (int) -1; - } - } else { - int val; - PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); - if (!tmp) return (int) -1; - val = __Pyx_PyInt_As_int(tmp); - Py_DECREF(tmp); - return val; - } -raise_overflow: - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to int"); - return (int) -1; -raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to int"); - return (int) -1; -} - -/* FastTypeChecks */ -#if CYTHON_COMPILING_IN_CPYTHON -static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { - while (a) { - a = a->tp_base; - if (a == b) - return 1; - } - return b == &PyBaseObject_Type; -} -static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { - PyObject *mro; - if (a == b) return 1; - mro = a->tp_mro; - if (likely(mro)) { - Py_ssize_t i, n; - n = PyTuple_GET_SIZE(mro); - for (i = 0; i < n; i++) { - if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) - return 1; - } - return 0; - } - return __Pyx_InBases(a, b); -} -#if PY_MAJOR_VERSION == 2 -static int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject* exc_type2) { - PyObject *exception, *value, *tb; - int res; - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ErrFetch(&exception, &value, &tb); - res = exc_type1 ? PyObject_IsSubclass(err, exc_type1) : 0; - if (unlikely(res == -1)) { - PyErr_WriteUnraisable(err); - res = 0; - } - if (!res) { - res = PyObject_IsSubclass(err, exc_type2); - if (unlikely(res == -1)) { - PyErr_WriteUnraisable(err); - res = 0; - } - } - __Pyx_ErrRestore(exception, value, tb); - return res; -} -#else -static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { - int res = exc_type1 ? __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type1) : 0; - if (!res) { - res = __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); - } - return res; -} -#endif -static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { - Py_ssize_t i, n; - assert(PyExceptionClass_Check(exc_type)); - n = PyTuple_GET_SIZE(tuple); -#if PY_MAJOR_VERSION >= 3 - for (i=0; ip) { - #if PY_MAJOR_VERSION < 3 - if (t->is_unicode) { - *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); - } else if (t->intern) { - *t->p = PyString_InternFromString(t->s); - } else { - *t->p = PyString_FromStringAndSize(t->s, t->n - 1); - } - #else - if (t->is_unicode | t->is_str) { - if (t->intern) { - *t->p = PyUnicode_InternFromString(t->s); - } else if (t->encoding) { - *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); - } else { - *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); - } - } else { - *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); - } - #endif - if (!*t->p) - return -1; - if (PyObject_Hash(*t->p) == -1) - return -1; - ++t; - } - return 0; -} - -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { - return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); -} -static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { - Py_ssize_t ignore; - return __Pyx_PyObject_AsStringAndSize(o, &ignore); -} -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT -#if !CYTHON_PEP393_ENABLED -static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { - char* defenc_c; - PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); - if (!defenc) return NULL; - defenc_c = PyBytes_AS_STRING(defenc); -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - { - char* end = defenc_c + PyBytes_GET_SIZE(defenc); - char* c; - for (c = defenc_c; c < end; c++) { - if ((unsigned char) (*c) >= 128) { - PyUnicode_AsASCIIString(o); - return NULL; - } - } - } -#endif - *length = PyBytes_GET_SIZE(defenc); - return defenc_c; -} -#else -static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { - if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - if (likely(PyUnicode_IS_ASCII(o))) { - *length = PyUnicode_GET_LENGTH(o); - return PyUnicode_AsUTF8(o); - } else { - PyUnicode_AsASCIIString(o); - return NULL; - } -#else - return PyUnicode_AsUTF8AndSize(o, length); -#endif -} -#endif -#endif -static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT - if ( -#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - __Pyx_sys_getdefaultencoding_not_ascii && -#endif - PyUnicode_Check(o)) { - return __Pyx_PyUnicode_AsStringAndSize(o, length); - } else -#endif -#if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) - if (PyByteArray_Check(o)) { - *length = PyByteArray_GET_SIZE(o); - return PyByteArray_AS_STRING(o); - } else -#endif - { - char* result; - int r = PyBytes_AsStringAndSize(o, &result, length); - if (unlikely(r < 0)) { - return NULL; - } else { - return result; - } - } -} -static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { - int is_true = x == Py_True; - if (is_true | (x == Py_False) | (x == Py_None)) return is_true; - else return PyObject_IsTrue(x); -} -static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { - int retval; - if (unlikely(!x)) return -1; - retval = __Pyx_PyObject_IsTrue(x); - Py_DECREF(x); - return retval; -} -static PyObject* __Pyx_PyNumber_IntOrLongWrongResultType(PyObject* result, const char* type_name) { -#if PY_MAJOR_VERSION >= 3 - if (PyLong_Check(result)) { - if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, - "__int__ returned non-int (type %.200s). " - "The ability to return an instance of a strict subclass of int " - "is deprecated, and may be removed in a future version of Python.", - Py_TYPE(result)->tp_name)) { - Py_DECREF(result); - return NULL; - } - return result; - } -#endif - PyErr_Format(PyExc_TypeError, - "__%.4s__ returned non-%.4s (type %.200s)", - type_name, type_name, Py_TYPE(result)->tp_name); - Py_DECREF(result); - return NULL; -} -static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { -#if CYTHON_USE_TYPE_SLOTS - PyNumberMethods *m; -#endif - const char *name = NULL; - PyObject *res = NULL; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x) || PyLong_Check(x))) -#else - if (likely(PyLong_Check(x))) -#endif - return __Pyx_NewRef(x); -#if CYTHON_USE_TYPE_SLOTS - m = Py_TYPE(x)->tp_as_number; - #if PY_MAJOR_VERSION < 3 - if (m && m->nb_int) { - name = "int"; - res = m->nb_int(x); - } - else if (m && m->nb_long) { - name = "long"; - res = m->nb_long(x); - } - #else - if (likely(m && m->nb_int)) { - name = "int"; - res = m->nb_int(x); - } - #endif -#else - if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { - res = PyNumber_Int(x); - } -#endif - if (likely(res)) { -#if PY_MAJOR_VERSION < 3 - if (unlikely(!PyInt_Check(res) && !PyLong_Check(res))) { -#else - if (unlikely(!PyLong_CheckExact(res))) { -#endif - return __Pyx_PyNumber_IntOrLongWrongResultType(res, name); - } - } - else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, - "an integer is required"); - } - return res; -} -static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { - Py_ssize_t ival; - PyObject *x; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_CheckExact(b))) { - if (sizeof(Py_ssize_t) >= sizeof(long)) - return PyInt_AS_LONG(b); - else - return PyInt_AsSsize_t(b); - } -#endif - if (likely(PyLong_CheckExact(b))) { - #if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)b)->ob_digit; - const Py_ssize_t size = Py_SIZE(b); - if (likely(__Pyx_sst_abs(size) <= 1)) { - ival = likely(size) ? digits[0] : 0; - if (size == -1) ival = -ival; - return ival; - } else { - switch (size) { - case 2: - if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { - return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -2: - if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case 3: - if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { - return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -3: - if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case 4: - if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { - return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -4: - if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - } - } - #endif - return PyLong_AsSsize_t(b); - } - x = PyNumber_Index(b); - if (!x) return -1; - ival = PyInt_AsSsize_t(x); - Py_DECREF(x); - return ival; -} -static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { - return b ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False); -} -static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { - return PyInt_FromSize_t(ival); -} - - -#endif /* Py_PYTHON_H */ diff --git a/.venv/Lib/site-packages/aiohttp/_http_writer.cp38-win_amd64.pyd b/.venv/Lib/site-packages/aiohttp/_http_writer.cp38-win_amd64.pyd deleted file mode 100644 index 5a92759..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/_http_writer.cp38-win_amd64.pyd and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/_http_writer.pyx b/.venv/Lib/site-packages/aiohttp/_http_writer.pyx deleted file mode 100644 index eff8521..0000000 --- a/.venv/Lib/site-packages/aiohttp/_http_writer.pyx +++ /dev/null @@ -1,163 +0,0 @@ -from cpython.bytes cimport PyBytes_FromStringAndSize -from cpython.exc cimport PyErr_NoMemory -from cpython.mem cimport PyMem_Free, PyMem_Malloc, PyMem_Realloc -from cpython.object cimport PyObject_Str -from libc.stdint cimport uint8_t, uint64_t -from libc.string cimport memcpy - -from multidict import istr - -DEF BUF_SIZE = 16 * 1024 # 16KiB -cdef char BUFFER[BUF_SIZE] - -cdef object _istr = istr - - -# ----------------- writer --------------------------- - -cdef struct Writer: - char *buf - Py_ssize_t size - Py_ssize_t pos - - -cdef inline void _init_writer(Writer* writer): - writer.buf = &BUFFER[0] - writer.size = BUF_SIZE - writer.pos = 0 - - -cdef inline void _release_writer(Writer* writer): - if writer.buf != BUFFER: - PyMem_Free(writer.buf) - - -cdef inline int _write_byte(Writer* writer, uint8_t ch): - cdef char * buf - cdef Py_ssize_t size - - if writer.pos == writer.size: - # reallocate - size = writer.size + BUF_SIZE - if writer.buf == BUFFER: - buf = PyMem_Malloc(size) - if buf == NULL: - PyErr_NoMemory() - return -1 - memcpy(buf, writer.buf, writer.size) - else: - buf = PyMem_Realloc(writer.buf, size) - if buf == NULL: - PyErr_NoMemory() - return -1 - writer.buf = buf - writer.size = size - writer.buf[writer.pos] = ch - writer.pos += 1 - return 0 - - -cdef inline int _write_utf8(Writer* writer, Py_UCS4 symbol): - cdef uint64_t utf = symbol - - if utf < 0x80: - return _write_byte(writer, utf) - elif utf < 0x800: - if _write_byte(writer, (0xc0 | (utf >> 6))) < 0: - return -1 - return _write_byte(writer, (0x80 | (utf & 0x3f))) - elif 0xD800 <= utf <= 0xDFFF: - # surogate pair, ignored - return 0 - elif utf < 0x10000: - if _write_byte(writer, (0xe0 | (utf >> 12))) < 0: - return -1 - if _write_byte(writer, (0x80 | ((utf >> 6) & 0x3f))) < 0: - return -1 - return _write_byte(writer, (0x80 | (utf & 0x3f))) - elif utf > 0x10FFFF: - # symbol is too large - return 0 - else: - if _write_byte(writer, (0xf0 | (utf >> 18))) < 0: - return -1 - if _write_byte(writer, - (0x80 | ((utf >> 12) & 0x3f))) < 0: - return -1 - if _write_byte(writer, - (0x80 | ((utf >> 6) & 0x3f))) < 0: - return -1 - return _write_byte(writer, (0x80 | (utf & 0x3f))) - - -cdef inline int _write_str(Writer* writer, str s): - cdef Py_UCS4 ch - for ch in s: - if _write_utf8(writer, ch) < 0: - return -1 - - -# --------------- _serialize_headers ---------------------- - -cdef str to_str(object s): - typ = type(s) - if typ is str: - return s - elif typ is _istr: - return PyObject_Str(s) - elif not isinstance(s, str): - raise TypeError("Cannot serialize non-str key {!r}".format(s)) - else: - return str(s) - - -cdef void _safe_header(str string) except *: - if "\r" in string or "\n" in string: - raise ValueError( - "Newline or carriage return character detected in HTTP status message or " - "header. This is a potential security issue." - ) - - -def _serialize_headers(str status_line, headers): - cdef Writer writer - cdef object key - cdef object val - cdef bytes ret - - _init_writer(&writer) - - for key, val in headers.items(): - _safe_header(to_str(key)) - _safe_header(to_str(val)) - - try: - if _write_str(&writer, status_line) < 0: - raise - if _write_byte(&writer, b'\r') < 0: - raise - if _write_byte(&writer, b'\n') < 0: - raise - - for key, val in headers.items(): - if _write_str(&writer, to_str(key)) < 0: - raise - if _write_byte(&writer, b':') < 0: - raise - if _write_byte(&writer, b' ') < 0: - raise - if _write_str(&writer, to_str(val)) < 0: - raise - if _write_byte(&writer, b'\r') < 0: - raise - if _write_byte(&writer, b'\n') < 0: - raise - - if _write_byte(&writer, b'\r') < 0: - raise - if _write_byte(&writer, b'\n') < 0: - raise - - return PyBytes_FromStringAndSize(writer.buf, writer.pos) - finally: - _release_writer(&writer) diff --git a/.venv/Lib/site-packages/aiohttp/_websocket.c b/.venv/Lib/site-packages/aiohttp/_websocket.c deleted file mode 100644 index d47da21..0000000 --- a/.venv/Lib/site-packages/aiohttp/_websocket.c +++ /dev/null @@ -1,3622 +0,0 @@ -/* Generated by Cython 0.29.24 */ - -#ifndef PY_SSIZE_T_CLEAN -#define PY_SSIZE_T_CLEAN -#endif /* PY_SSIZE_T_CLEAN */ -#include "Python.h" -#ifndef Py_PYTHON_H - #error Python headers needed to compile C extensions, please install development version of Python. -#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03030000) - #error Cython requires Python 2.6+ or Python 3.3+. -#else -#define CYTHON_ABI "0_29_24" -#define CYTHON_HEX_VERSION 0x001D18F0 -#define CYTHON_FUTURE_DIVISION 1 -#include -#ifndef offsetof - #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) -#endif -#if !defined(WIN32) && !defined(MS_WINDOWS) - #ifndef __stdcall - #define __stdcall - #endif - #ifndef __cdecl - #define __cdecl - #endif - #ifndef __fastcall - #define __fastcall - #endif -#endif -#ifndef DL_IMPORT - #define DL_IMPORT(t) t -#endif -#ifndef DL_EXPORT - #define DL_EXPORT(t) t -#endif -#define __PYX_COMMA , -#ifndef HAVE_LONG_LONG - #if PY_VERSION_HEX >= 0x02070000 - #define HAVE_LONG_LONG - #endif -#endif -#ifndef PY_LONG_LONG - #define PY_LONG_LONG LONG_LONG -#endif -#ifndef Py_HUGE_VAL - #define Py_HUGE_VAL HUGE_VAL -#endif -#ifdef PYPY_VERSION - #define CYTHON_COMPILING_IN_PYPY 1 - #define CYTHON_COMPILING_IN_PYSTON 0 - #define CYTHON_COMPILING_IN_CPYTHON 0 - #undef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 0 - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #if PY_VERSION_HEX < 0x03050000 - #undef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 0 - #elif !defined(CYTHON_USE_ASYNC_SLOTS) - #define CYTHON_USE_ASYNC_SLOTS 1 - #endif - #undef CYTHON_USE_PYLIST_INTERNALS - #define CYTHON_USE_PYLIST_INTERNALS 0 - #undef CYTHON_USE_UNICODE_INTERNALS - #define CYTHON_USE_UNICODE_INTERNALS 0 - #undef CYTHON_USE_UNICODE_WRITER - #define CYTHON_USE_UNICODE_WRITER 0 - #undef CYTHON_USE_PYLONG_INTERNALS - #define CYTHON_USE_PYLONG_INTERNALS 0 - #undef CYTHON_AVOID_BORROWED_REFS - #define CYTHON_AVOID_BORROWED_REFS 1 - #undef CYTHON_ASSUME_SAFE_MACROS - #define CYTHON_ASSUME_SAFE_MACROS 0 - #undef CYTHON_UNPACK_METHODS - #define CYTHON_UNPACK_METHODS 0 - #undef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 0 - #undef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL 0 - #undef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT 0 - #undef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE 0 - #undef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS 0 - #undef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK 0 -#elif defined(PYSTON_VERSION) - #define CYTHON_COMPILING_IN_PYPY 0 - #define CYTHON_COMPILING_IN_PYSTON 1 - #define CYTHON_COMPILING_IN_CPYTHON 0 - #ifndef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 1 - #endif - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #undef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 0 - #undef CYTHON_USE_PYLIST_INTERNALS - #define CYTHON_USE_PYLIST_INTERNALS 0 - #ifndef CYTHON_USE_UNICODE_INTERNALS - #define CYTHON_USE_UNICODE_INTERNALS 1 - #endif - #undef CYTHON_USE_UNICODE_WRITER - #define CYTHON_USE_UNICODE_WRITER 0 - #undef CYTHON_USE_PYLONG_INTERNALS - #define CYTHON_USE_PYLONG_INTERNALS 0 - #ifndef CYTHON_AVOID_BORROWED_REFS - #define CYTHON_AVOID_BORROWED_REFS 0 - #endif - #ifndef CYTHON_ASSUME_SAFE_MACROS - #define CYTHON_ASSUME_SAFE_MACROS 1 - #endif - #ifndef CYTHON_UNPACK_METHODS - #define CYTHON_UNPACK_METHODS 1 - #endif - #undef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 0 - #undef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL 0 - #undef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT 0 - #undef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE 0 - #undef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS 0 - #undef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK 0 -#else - #define CYTHON_COMPILING_IN_PYPY 0 - #define CYTHON_COMPILING_IN_PYSTON 0 - #define CYTHON_COMPILING_IN_CPYTHON 1 - #ifndef CYTHON_USE_TYPE_SLOTS - #define CYTHON_USE_TYPE_SLOTS 1 - #endif - #if PY_VERSION_HEX < 0x02070000 - #undef CYTHON_USE_PYTYPE_LOOKUP - #define CYTHON_USE_PYTYPE_LOOKUP 0 - #elif !defined(CYTHON_USE_PYTYPE_LOOKUP) - #define CYTHON_USE_PYTYPE_LOOKUP 1 - #endif - #if PY_MAJOR_VERSION < 3 - #undef CYTHON_USE_ASYNC_SLOTS - #define CYTHON_USE_ASYNC_SLOTS 0 - #elif !defined(CYTHON_USE_ASYNC_SLOTS) - #define CYTHON_USE_ASYNC_SLOTS 1 - #endif - #if PY_VERSION_HEX < 0x02070000 - #undef CYTHON_USE_PYLONG_INTERNALS - #define CYTHON_USE_PYLONG_INTERNALS 0 - #elif !defined(CYTHON_USE_PYLONG_INTERNALS) - #define CYTHON_USE_PYLONG_INTERNALS 1 - #endif - #ifndef CYTHON_USE_PYLIST_INTERNALS - #define CYTHON_USE_PYLIST_INTERNALS 1 - #endif - #ifndef CYTHON_USE_UNICODE_INTERNALS - #define CYTHON_USE_UNICODE_INTERNALS 1 - #endif - #if PY_VERSION_HEX < 0x030300F0 - #undef CYTHON_USE_UNICODE_WRITER - #define CYTHON_USE_UNICODE_WRITER 0 - #elif !defined(CYTHON_USE_UNICODE_WRITER) - #define CYTHON_USE_UNICODE_WRITER 1 - #endif - #ifndef CYTHON_AVOID_BORROWED_REFS - #define CYTHON_AVOID_BORROWED_REFS 0 - #endif - #ifndef CYTHON_ASSUME_SAFE_MACROS - #define CYTHON_ASSUME_SAFE_MACROS 1 - #endif - #ifndef CYTHON_UNPACK_METHODS - #define CYTHON_UNPACK_METHODS 1 - #endif - #ifndef CYTHON_FAST_THREAD_STATE - #define CYTHON_FAST_THREAD_STATE 1 - #endif - #ifndef CYTHON_FAST_PYCALL - #define CYTHON_FAST_PYCALL 1 - #endif - #ifndef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT (PY_VERSION_HEX >= 0x03050000) - #endif - #ifndef CYTHON_USE_TP_FINALIZE - #define CYTHON_USE_TP_FINALIZE (PY_VERSION_HEX >= 0x030400a1) - #endif - #ifndef CYTHON_USE_DICT_VERSIONS - #define CYTHON_USE_DICT_VERSIONS (PY_VERSION_HEX >= 0x030600B1) - #endif - #ifndef CYTHON_USE_EXC_INFO_STACK - #define CYTHON_USE_EXC_INFO_STACK (PY_VERSION_HEX >= 0x030700A3) - #endif -#endif -#if !defined(CYTHON_FAST_PYCCALL) -#define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) -#endif -#if CYTHON_USE_PYLONG_INTERNALS - #include "longintrepr.h" - #undef SHIFT - #undef BASE - #undef MASK - #ifdef SIZEOF_VOID_P - enum { __pyx_check_sizeof_voidp = 1 / (int)(SIZEOF_VOID_P == sizeof(void*)) }; - #endif -#endif -#ifndef __has_attribute - #define __has_attribute(x) 0 -#endif -#ifndef __has_cpp_attribute - #define __has_cpp_attribute(x) 0 -#endif -#ifndef CYTHON_RESTRICT - #if defined(__GNUC__) - #define CYTHON_RESTRICT __restrict__ - #elif defined(_MSC_VER) && _MSC_VER >= 1400 - #define CYTHON_RESTRICT __restrict - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_RESTRICT restrict - #else - #define CYTHON_RESTRICT - #endif -#endif -#ifndef CYTHON_UNUSED -# if defined(__GNUC__) -# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) -# define CYTHON_UNUSED __attribute__ ((__unused__)) -# else -# define CYTHON_UNUSED -# endif -# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) -# define CYTHON_UNUSED __attribute__ ((__unused__)) -# else -# define CYTHON_UNUSED -# endif -#endif -#ifndef CYTHON_MAYBE_UNUSED_VAR -# if defined(__cplusplus) - template void CYTHON_MAYBE_UNUSED_VAR( const T& ) { } -# else -# define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x) -# endif -#endif -#ifndef CYTHON_NCP_UNUSED -# if CYTHON_COMPILING_IN_CPYTHON -# define CYTHON_NCP_UNUSED -# else -# define CYTHON_NCP_UNUSED CYTHON_UNUSED -# endif -#endif -#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) -#ifdef _MSC_VER - #ifndef _MSC_STDINT_H_ - #if _MSC_VER < 1300 - typedef unsigned char uint8_t; - typedef unsigned int uint32_t; - #else - typedef unsigned __int8 uint8_t; - typedef unsigned __int32 uint32_t; - #endif - #endif -#else - #include -#endif -#ifndef CYTHON_FALLTHROUGH - #if defined(__cplusplus) && __cplusplus >= 201103L - #if __has_cpp_attribute(fallthrough) - #define CYTHON_FALLTHROUGH [[fallthrough]] - #elif __has_cpp_attribute(clang::fallthrough) - #define CYTHON_FALLTHROUGH [[clang::fallthrough]] - #elif __has_cpp_attribute(gnu::fallthrough) - #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] - #endif - #endif - #ifndef CYTHON_FALLTHROUGH - #if __has_attribute(fallthrough) - #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) - #else - #define CYTHON_FALLTHROUGH - #endif - #endif - #if defined(__clang__ ) && defined(__apple_build_version__) - #if __apple_build_version__ < 7000000 - #undef CYTHON_FALLTHROUGH - #define CYTHON_FALLTHROUGH - #endif - #endif -#endif - -#ifndef CYTHON_INLINE - #if defined(__clang__) - #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) - #elif defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline - #else - #define CYTHON_INLINE - #endif -#endif - -#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) - #define Py_OptimizeFlag 0 -#endif -#define __PYX_BUILD_PY_SSIZE_T "n" -#define CYTHON_FORMAT_SSIZE_T "z" -#if PY_MAJOR_VERSION < 3 - #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) - #define __Pyx_DefaultClassType PyClass_Type -#else - #define __Pyx_BUILTIN_MODULE_NAME "builtins" -#if PY_VERSION_HEX >= 0x030800A4 && PY_VERSION_HEX < 0x030800B2 - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a, 0, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) -#else - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ - PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) -#endif - #define __Pyx_DefaultClassType PyType_Type -#endif -#ifndef Py_TPFLAGS_CHECKTYPES - #define Py_TPFLAGS_CHECKTYPES 0 -#endif -#ifndef Py_TPFLAGS_HAVE_INDEX - #define Py_TPFLAGS_HAVE_INDEX 0 -#endif -#ifndef Py_TPFLAGS_HAVE_NEWBUFFER - #define Py_TPFLAGS_HAVE_NEWBUFFER 0 -#endif -#ifndef Py_TPFLAGS_HAVE_FINALIZE - #define Py_TPFLAGS_HAVE_FINALIZE 0 -#endif -#ifndef METH_STACKLESS - #define METH_STACKLESS 0 -#endif -#if PY_VERSION_HEX <= 0x030700A3 || !defined(METH_FASTCALL) - #ifndef METH_FASTCALL - #define METH_FASTCALL 0x80 - #endif - typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject *const *args, Py_ssize_t nargs); - typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject *const *args, - Py_ssize_t nargs, PyObject *kwnames); -#else - #define __Pyx_PyCFunctionFast _PyCFunctionFast - #define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords -#endif -#if CYTHON_FAST_PYCCALL -#define __Pyx_PyFastCFunction_Check(func)\ - ((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))))) -#else -#define __Pyx_PyFastCFunction_Check(func) 0 -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) - #define PyObject_Malloc(s) PyMem_Malloc(s) - #define PyObject_Free(p) PyMem_Free(p) - #define PyObject_Realloc(p) PyMem_Realloc(p) -#endif -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX < 0x030400A1 - #define PyMem_RawMalloc(n) PyMem_Malloc(n) - #define PyMem_RawRealloc(p, n) PyMem_Realloc(p, n) - #define PyMem_RawFree(p) PyMem_Free(p) -#endif -#if CYTHON_COMPILING_IN_PYSTON - #define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co) - #define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno) -#else - #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) - #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) -#endif -#if !CYTHON_FAST_THREAD_STATE || PY_VERSION_HEX < 0x02070000 - #define __Pyx_PyThreadState_Current PyThreadState_GET() -#elif PY_VERSION_HEX >= 0x03060000 - #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() -#elif PY_VERSION_HEX >= 0x03000000 - #define __Pyx_PyThreadState_Current PyThreadState_GET() -#else - #define __Pyx_PyThreadState_Current _PyThreadState_Current -#endif -#if PY_VERSION_HEX < 0x030700A2 && !defined(PyThread_tss_create) && !defined(Py_tss_NEEDS_INIT) -#include "pythread.h" -#define Py_tss_NEEDS_INIT 0 -typedef int Py_tss_t; -static CYTHON_INLINE int PyThread_tss_create(Py_tss_t *key) { - *key = PyThread_create_key(); - return 0; -} -static CYTHON_INLINE Py_tss_t * PyThread_tss_alloc(void) { - Py_tss_t *key = (Py_tss_t *)PyObject_Malloc(sizeof(Py_tss_t)); - *key = Py_tss_NEEDS_INIT; - return key; -} -static CYTHON_INLINE void PyThread_tss_free(Py_tss_t *key) { - PyObject_Free(key); -} -static CYTHON_INLINE int PyThread_tss_is_created(Py_tss_t *key) { - return *key != Py_tss_NEEDS_INIT; -} -static CYTHON_INLINE void PyThread_tss_delete(Py_tss_t *key) { - PyThread_delete_key(*key); - *key = Py_tss_NEEDS_INIT; -} -static CYTHON_INLINE int PyThread_tss_set(Py_tss_t *key, void *value) { - return PyThread_set_key_value(*key, value); -} -static CYTHON_INLINE void * PyThread_tss_get(Py_tss_t *key) { - return PyThread_get_key_value(*key); -} -#endif -#if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) -#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) -#else -#define __Pyx_PyDict_NewPresized(n) PyDict_New() -#endif -#if PY_MAJOR_VERSION >= 3 || CYTHON_FUTURE_DIVISION - #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) -#else - #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) -#endif -#if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x030500A1 && CYTHON_USE_UNICODE_INTERNALS -#define __Pyx_PyDict_GetItemStr(dict, name) _PyDict_GetItem_KnownHash(dict, name, ((PyASCIIObject *) name)->hash) -#else -#define __Pyx_PyDict_GetItemStr(dict, name) PyDict_GetItem(dict, name) -#endif -#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) - #define CYTHON_PEP393_ENABLED 1 - #if defined(PyUnicode_IS_READY) - #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ - 0 : _PyUnicode_Ready((PyObject *)(op))) - #else - #define __Pyx_PyUnicode_READY(op) (0) - #endif - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) - #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) - #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) - #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) - #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) - #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) - #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch) - #if defined(PyUnicode_IS_READY) && defined(PyUnicode_GET_SIZE) - #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03090000 - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : ((PyCompactUnicodeObject *)(u))->wstr_length)) - #else - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) - #endif - #else - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_LENGTH(u)) - #endif -#else - #define CYTHON_PEP393_ENABLED 0 - #define PyUnicode_1BYTE_KIND 1 - #define PyUnicode_2BYTE_KIND 2 - #define PyUnicode_4BYTE_KIND 4 - #define __Pyx_PyUnicode_READY(op) (0) - #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) - #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) - #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111) - #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) - #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) - #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) - #define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch) - #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) -#endif -#if CYTHON_COMPILING_IN_PYPY - #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) - #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) -#else - #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) - #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ - PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains) - #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check) - #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) -#endif -#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format) - #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) -#endif -#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyString_Check(b) && !PyString_CheckExact(b)))) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) -#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None || (PyUnicode_Check(b) && !PyUnicode_CheckExact(b)))) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) -#else - #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) -#endif -#if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII) - #define PyObject_ASCII(o) PyObject_Repr(o) -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyBaseString_Type PyUnicode_Type - #define PyStringObject PyUnicodeObject - #define PyString_Type PyUnicode_Type - #define PyString_Check PyUnicode_Check - #define PyString_CheckExact PyUnicode_CheckExact -#ifndef PyObject_Unicode - #define PyObject_Unicode PyObject_Str -#endif -#endif -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) - #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) -#else - #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) - #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) -#endif -#ifndef PySet_CheckExact - #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) -#endif -#if PY_VERSION_HEX >= 0x030900A4 - #define __Pyx_SET_REFCNT(obj, refcnt) Py_SET_REFCNT(obj, refcnt) - #define __Pyx_SET_SIZE(obj, size) Py_SET_SIZE(obj, size) -#else - #define __Pyx_SET_REFCNT(obj, refcnt) Py_REFCNT(obj) = (refcnt) - #define __Pyx_SET_SIZE(obj, size) Py_SIZE(obj) = (size) -#endif -#if CYTHON_ASSUME_SAFE_MACROS - #define __Pyx_PySequence_SIZE(seq) Py_SIZE(seq) -#else - #define __Pyx_PySequence_SIZE(seq) PySequence_Size(seq) -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyIntObject PyLongObject - #define PyInt_Type PyLong_Type - #define PyInt_Check(op) PyLong_Check(op) - #define PyInt_CheckExact(op) PyLong_CheckExact(op) - #define PyInt_FromString PyLong_FromString - #define PyInt_FromUnicode PyLong_FromUnicode - #define PyInt_FromLong PyLong_FromLong - #define PyInt_FromSize_t PyLong_FromSize_t - #define PyInt_FromSsize_t PyLong_FromSsize_t - #define PyInt_AsLong PyLong_AsLong - #define PyInt_AS_LONG PyLong_AS_LONG - #define PyInt_AsSsize_t PyLong_AsSsize_t - #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask - #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask - #define PyNumber_Int PyNumber_Long -#endif -#if PY_MAJOR_VERSION >= 3 - #define PyBoolObject PyLongObject -#endif -#if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY - #ifndef PyUnicode_InternFromString - #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) - #endif -#endif -#if PY_VERSION_HEX < 0x030200A4 - typedef long Py_hash_t; - #define __Pyx_PyInt_FromHash_t PyInt_FromLong - #define __Pyx_PyInt_AsHash_t PyInt_AsLong -#else - #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t - #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t -#endif -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyMethod_New(func, self, klass) ((self) ? ((void)(klass), PyMethod_New(func, self)) : __Pyx_NewRef(func)) -#else - #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) -#endif -#if CYTHON_USE_ASYNC_SLOTS - #if PY_VERSION_HEX >= 0x030500B1 - #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods - #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) - #else - #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) - #endif -#else - #define __Pyx_PyType_AsAsync(obj) NULL -#endif -#ifndef __Pyx_PyAsyncMethodsStruct - typedef struct { - unaryfunc am_await; - unaryfunc am_aiter; - unaryfunc am_anext; - } __Pyx_PyAsyncMethodsStruct; -#endif - -#if defined(WIN32) || defined(MS_WINDOWS) - #define _USE_MATH_DEFINES -#endif -#include -#ifdef NAN -#define __PYX_NAN() ((float) NAN) -#else -static CYTHON_INLINE float __PYX_NAN() { - float value; - memset(&value, 0xFF, sizeof(value)); - return value; -} -#endif -#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) -#define __Pyx_truncl trunc -#else -#define __Pyx_truncl truncl -#endif - -#define __PYX_MARK_ERR_POS(f_index, lineno) \ - { __pyx_filename = __pyx_f[f_index]; (void)__pyx_filename; __pyx_lineno = lineno; (void)__pyx_lineno; __pyx_clineno = __LINE__; (void)__pyx_clineno; } -#define __PYX_ERR(f_index, lineno, Ln_error) \ - { __PYX_MARK_ERR_POS(f_index, lineno) goto Ln_error; } - -#ifndef __PYX_EXTERN_C - #ifdef __cplusplus - #define __PYX_EXTERN_C extern "C" - #else - #define __PYX_EXTERN_C extern - #endif -#endif - -#define __PYX_HAVE__aiohttp___websocket -#define __PYX_HAVE_API__aiohttp___websocket -/* Early includes */ -#include -#include -#include "pythread.h" -#include -#ifdef _OPENMP -#include -#endif /* _OPENMP */ - -#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) -#define CYTHON_WITHOUT_ASSERTIONS -#endif - -typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding; - const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; - -#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 -#define __PYX_DEFAULT_STRING_ENCODING_IS_UTF8 0 -#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT (PY_MAJOR_VERSION >= 3 && __PYX_DEFAULT_STRING_ENCODING_IS_UTF8) -#define __PYX_DEFAULT_STRING_ENCODING "" -#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString -#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize -#define __Pyx_uchar_cast(c) ((unsigned char)c) -#define __Pyx_long_cast(x) ((long)x) -#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ - (sizeof(type) < sizeof(Py_ssize_t)) ||\ - (sizeof(type) > sizeof(Py_ssize_t) &&\ - likely(v < (type)PY_SSIZE_T_MAX ||\ - v == (type)PY_SSIZE_T_MAX) &&\ - (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ - v == (type)PY_SSIZE_T_MIN))) ||\ - (sizeof(type) == sizeof(Py_ssize_t) &&\ - (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ - v == (type)PY_SSIZE_T_MAX))) ) -static CYTHON_INLINE int __Pyx_is_valid_index(Py_ssize_t i, Py_ssize_t limit) { - return (size_t) i < (size_t) limit; -} -#if defined (__cplusplus) && __cplusplus >= 201103L - #include - #define __Pyx_sst_abs(value) std::abs(value) -#elif SIZEOF_INT >= SIZEOF_SIZE_T - #define __Pyx_sst_abs(value) abs(value) -#elif SIZEOF_LONG >= SIZEOF_SIZE_T - #define __Pyx_sst_abs(value) labs(value) -#elif defined (_MSC_VER) - #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) -#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define __Pyx_sst_abs(value) llabs(value) -#elif defined (__GNUC__) - #define __Pyx_sst_abs(value) __builtin_llabs(value) -#else - #define __Pyx_sst_abs(value) ((value<0) ? -value : value) -#endif -static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); -static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); -#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) -#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) -#define __Pyx_PyBytes_FromString PyBytes_FromString -#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); -#if PY_MAJOR_VERSION < 3 - #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString - #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize -#else - #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString - #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize -#endif -#define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) -#define __Pyx_PyObject_AsWritableString(s) ((char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsWritableSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) -#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) -#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) -#define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) -#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) -static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) { - const Py_UNICODE *u_end = u; - while (*u_end++) ; - return (size_t)(u_end - u - 1); -} -#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) -#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode -#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode -#define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) -#define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) -static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b); -static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); -static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject*); -static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); -#define __Pyx_PySequence_Tuple(obj)\ - (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) -static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); -static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); -#if CYTHON_ASSUME_SAFE_MACROS -#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) -#else -#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) -#endif -#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) -#if PY_MAJOR_VERSION >= 3 -#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) -#else -#define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x)) -#endif -#define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x)) -#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII -static int __Pyx_sys_getdefaultencoding_not_ascii; -static int __Pyx_init_sys_getdefaultencoding_params(void) { - PyObject* sys; - PyObject* default_encoding = NULL; - PyObject* ascii_chars_u = NULL; - PyObject* ascii_chars_b = NULL; - const char* default_encoding_c; - sys = PyImport_ImportModule("sys"); - if (!sys) goto bad; - default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); - Py_DECREF(sys); - if (!default_encoding) goto bad; - default_encoding_c = PyBytes_AsString(default_encoding); - if (!default_encoding_c) goto bad; - if (strcmp(default_encoding_c, "ascii") == 0) { - __Pyx_sys_getdefaultencoding_not_ascii = 0; - } else { - char ascii_chars[128]; - int c; - for (c = 0; c < 128; c++) { - ascii_chars[c] = c; - } - __Pyx_sys_getdefaultencoding_not_ascii = 1; - ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); - if (!ascii_chars_u) goto bad; - ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); - if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { - PyErr_Format( - PyExc_ValueError, - "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", - default_encoding_c); - goto bad; - } - Py_DECREF(ascii_chars_u); - Py_DECREF(ascii_chars_b); - } - Py_DECREF(default_encoding); - return 0; -bad: - Py_XDECREF(default_encoding); - Py_XDECREF(ascii_chars_u); - Py_XDECREF(ascii_chars_b); - return -1; -} -#endif -#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 -#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) -#else -#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) -#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT -static char* __PYX_DEFAULT_STRING_ENCODING; -static int __Pyx_init_sys_getdefaultencoding_params(void) { - PyObject* sys; - PyObject* default_encoding = NULL; - char* default_encoding_c; - sys = PyImport_ImportModule("sys"); - if (!sys) goto bad; - default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); - Py_DECREF(sys); - if (!default_encoding) goto bad; - default_encoding_c = PyBytes_AsString(default_encoding); - if (!default_encoding_c) goto bad; - __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c) + 1); - if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; - strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); - Py_DECREF(default_encoding); - return 0; -bad: - Py_XDECREF(default_encoding); - return -1; -} -#endif -#endif - - -/* Test for GCC > 2.95 */ -#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) - #define likely(x) __builtin_expect(!!(x), 1) - #define unlikely(x) __builtin_expect(!!(x), 0) -#else /* !__GNUC__ or GCC < 2.95 */ - #define likely(x) (x) - #define unlikely(x) (x) -#endif /* __GNUC__ */ -static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } - -static PyObject *__pyx_m = NULL; -static PyObject *__pyx_d; -static PyObject *__pyx_b; -static PyObject *__pyx_cython_runtime = NULL; -static PyObject *__pyx_empty_tuple; -static PyObject *__pyx_empty_bytes; -static PyObject *__pyx_empty_unicode; -static int __pyx_lineno; -static int __pyx_clineno = 0; -static const char * __pyx_cfilenm= __FILE__; -static const char *__pyx_filename; - - -static const char *__pyx_f[] = { - "aiohttp\\_websocket.pyx", - "type.pxd", - "bool.pxd", - "complex.pxd", -}; - -/*--- Type declarations ---*/ - -/* --- Runtime support code (head) --- */ -/* Refnanny.proto */ -#ifndef CYTHON_REFNANNY - #define CYTHON_REFNANNY 0 -#endif -#if CYTHON_REFNANNY - typedef struct { - void (*INCREF)(void*, PyObject*, int); - void (*DECREF)(void*, PyObject*, int); - void (*GOTREF)(void*, PyObject*, int); - void (*GIVEREF)(void*, PyObject*, int); - void* (*SetupContext)(const char*, int, const char*); - void (*FinishContext)(void**); - } __Pyx_RefNannyAPIStruct; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; - static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); - #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; -#ifdef WITH_THREAD - #define __Pyx_RefNannySetupContext(name, acquire_gil)\ - if (acquire_gil) {\ - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ - PyGILState_Release(__pyx_gilstate_save);\ - } else {\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ - } -#else - #define __Pyx_RefNannySetupContext(name, acquire_gil)\ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) -#endif - #define __Pyx_RefNannyFinishContext()\ - __Pyx_RefNanny->FinishContext(&__pyx_refnanny) - #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) - #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) - #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) - #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) - #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) -#else - #define __Pyx_RefNannyDeclarations - #define __Pyx_RefNannySetupContext(name, acquire_gil) - #define __Pyx_RefNannyFinishContext() - #define __Pyx_INCREF(r) Py_INCREF(r) - #define __Pyx_DECREF(r) Py_DECREF(r) - #define __Pyx_GOTREF(r) - #define __Pyx_GIVEREF(r) - #define __Pyx_XINCREF(r) Py_XINCREF(r) - #define __Pyx_XDECREF(r) Py_XDECREF(r) - #define __Pyx_XGOTREF(r) - #define __Pyx_XGIVEREF(r) -#endif -#define __Pyx_XDECREF_SET(r, v) do {\ - PyObject *tmp = (PyObject *) r;\ - r = v; __Pyx_XDECREF(tmp);\ - } while (0) -#define __Pyx_DECREF_SET(r, v) do {\ - PyObject *tmp = (PyObject *) r;\ - r = v; __Pyx_DECREF(tmp);\ - } while (0) -#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) -#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) - -/* PyObjectGetAttrStr.proto */ -#if CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name); -#else -#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) -#endif - -/* GetBuiltinName.proto */ -static PyObject *__Pyx_GetBuiltinName(PyObject *name); - -/* RaiseArgTupleInvalid.proto */ -static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, - Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); - -/* RaiseDoubleKeywords.proto */ -static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); - -/* ParseKeywords.proto */ -static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\ - PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\ - const char* function_name); - -/* PyCFunctionFastCall.proto */ -#if CYTHON_FAST_PYCCALL -static CYTHON_INLINE PyObject *__Pyx_PyCFunction_FastCall(PyObject *func, PyObject **args, Py_ssize_t nargs); -#else -#define __Pyx_PyCFunction_FastCall(func, args, nargs) (assert(0), NULL) -#endif - -/* PyFunctionFastCall.proto */ -#if CYTHON_FAST_PYCALL -#define __Pyx_PyFunction_FastCall(func, args, nargs)\ - __Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL) -#if 1 || PY_VERSION_HEX < 0x030600B1 -static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs); -#else -#define __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs) _PyFunction_FastCallDict(func, args, nargs, kwargs) -#endif -#define __Pyx_BUILD_ASSERT_EXPR(cond)\ - (sizeof(char [1 - 2*!(cond)]) - 1) -#ifndef Py_MEMBER_SIZE -#define Py_MEMBER_SIZE(type, member) sizeof(((type *)0)->member) -#endif - static size_t __pyx_pyframe_localsplus_offset = 0; - #include "frameobject.h" - #define __Pxy_PyFrame_Initialize_Offsets()\ - ((void)__Pyx_BUILD_ASSERT_EXPR(sizeof(PyFrameObject) == offsetof(PyFrameObject, f_localsplus) + Py_MEMBER_SIZE(PyFrameObject, f_localsplus)),\ - (void)(__pyx_pyframe_localsplus_offset = ((size_t)PyFrame_Type.tp_basicsize) - Py_MEMBER_SIZE(PyFrameObject, f_localsplus))) - #define __Pyx_PyFrame_GetLocalsplus(frame)\ - (assert(__pyx_pyframe_localsplus_offset), (PyObject **)(((char *)(frame)) + __pyx_pyframe_localsplus_offset)) -#endif - -/* PyObjectCall.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); -#else -#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) -#endif - -/* PyObjectCallMethO.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); -#endif - -/* PyObjectCallOneArg.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); - -/* TypeImport.proto */ -#ifndef __PYX_HAVE_RT_ImportType_proto -#define __PYX_HAVE_RT_ImportType_proto -enum __Pyx_ImportType_CheckSize { - __Pyx_ImportType_CheckSize_Error = 0, - __Pyx_ImportType_CheckSize_Warn = 1, - __Pyx_ImportType_CheckSize_Ignore = 2 -}; -static PyTypeObject *__Pyx_ImportType(PyObject* module, const char *module_name, const char *class_name, size_t size, enum __Pyx_ImportType_CheckSize check_size); -#endif - -/* PyDictVersioning.proto */ -#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS -#define __PYX_DICT_VERSION_INIT ((PY_UINT64_T) -1) -#define __PYX_GET_DICT_VERSION(dict) (((PyDictObject*)(dict))->ma_version_tag) -#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var)\ - (version_var) = __PYX_GET_DICT_VERSION(dict);\ - (cache_var) = (value); -#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) {\ - static PY_UINT64_T __pyx_dict_version = 0;\ - static PyObject *__pyx_dict_cached_value = NULL;\ - if (likely(__PYX_GET_DICT_VERSION(DICT) == __pyx_dict_version)) {\ - (VAR) = __pyx_dict_cached_value;\ - } else {\ - (VAR) = __pyx_dict_cached_value = (LOOKUP);\ - __pyx_dict_version = __PYX_GET_DICT_VERSION(DICT);\ - }\ -} -static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj); -static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj); -static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version); -#else -#define __PYX_GET_DICT_VERSION(dict) (0) -#define __PYX_UPDATE_DICT_CACHE(dict, value, cache_var, version_var) -#define __PYX_PY_DICT_LOOKUP_IF_MODIFIED(VAR, DICT, LOOKUP) (VAR) = (LOOKUP); -#endif - -/* PyThreadStateGet.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; -#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; -#define __Pyx_PyErr_Occurred() __pyx_tstate->curexc_type -#else -#define __Pyx_PyThreadState_declare -#define __Pyx_PyThreadState_assign -#define __Pyx_PyErr_Occurred() PyErr_Occurred() -#endif - -/* PyErrFetchRestore.proto */ -#if CYTHON_FAST_THREAD_STATE -#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) -#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) -#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) -#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) -#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) -static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); -static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); -#if CYTHON_COMPILING_IN_CPYTHON -#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) -#else -#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) -#endif -#else -#define __Pyx_PyErr_Clear() PyErr_Clear() -#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) -#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) -#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) -#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) -#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) -#endif - -/* CLineInTraceback.proto */ -#ifdef CYTHON_CLINE_IN_TRACEBACK -#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) -#else -static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); -#endif - -/* CodeObjectCache.proto */ -typedef struct { - PyCodeObject* code_object; - int code_line; -} __Pyx_CodeObjectCacheEntry; -struct __Pyx_CodeObjectCache { - int count; - int max_count; - __Pyx_CodeObjectCacheEntry* entries; -}; -static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); -static PyCodeObject *__pyx_find_code_object(int code_line); -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); - -/* AddTraceback.proto */ -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename); - -/* GCCDiagnostics.proto */ -#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) -#define __Pyx_HAS_GCC_DIAGNOSTIC -#endif - -/* CIntToPy.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); - -/* CIntFromPy.proto */ -static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); - -/* CIntFromPy.proto */ -static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); - -/* FastTypeChecks.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) -static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); -static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); -static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); -#else -#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) -#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) -#define __Pyx_PyErr_GivenExceptionMatches2(err, type1, type2) (PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2)) -#endif -#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) - -/* CheckBinaryVersion.proto */ -static int __Pyx_check_binary_version(void); - -/* InitStrings.proto */ -static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); - - -/* Module declarations from 'cpython.version' */ - -/* Module declarations from '__builtin__' */ - -/* Module declarations from 'cpython.type' */ -static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; - -/* Module declarations from 'libc.string' */ - -/* Module declarations from 'libc.stdio' */ - -/* Module declarations from 'cpython.object' */ - -/* Module declarations from 'cpython.ref' */ - -/* Module declarations from 'cpython.exc' */ - -/* Module declarations from 'cpython.module' */ - -/* Module declarations from 'cpython.mem' */ - -/* Module declarations from 'cpython.tuple' */ - -/* Module declarations from 'cpython.list' */ - -/* Module declarations from 'cpython.sequence' */ - -/* Module declarations from 'cpython.mapping' */ - -/* Module declarations from 'cpython.iterator' */ - -/* Module declarations from 'cpython.number' */ - -/* Module declarations from 'cpython.int' */ - -/* Module declarations from '__builtin__' */ - -/* Module declarations from 'cpython.bool' */ -static PyTypeObject *__pyx_ptype_7cpython_4bool_bool = 0; - -/* Module declarations from 'cpython.long' */ - -/* Module declarations from 'cpython.float' */ - -/* Module declarations from '__builtin__' */ - -/* Module declarations from 'cpython.complex' */ -static PyTypeObject *__pyx_ptype_7cpython_7complex_complex = 0; - -/* Module declarations from 'cpython.string' */ - -/* Module declarations from 'cpython.unicode' */ - -/* Module declarations from 'cpython.dict' */ - -/* Module declarations from 'cpython.instance' */ - -/* Module declarations from 'cpython.function' */ - -/* Module declarations from 'cpython.method' */ - -/* Module declarations from 'cpython.weakref' */ - -/* Module declarations from 'cpython.getargs' */ - -/* Module declarations from 'cpython.pythread' */ - -/* Module declarations from 'cpython.pystate' */ - -/* Module declarations from 'cpython.cobject' */ - -/* Module declarations from 'cpython.oldbuffer' */ - -/* Module declarations from 'cpython.set' */ - -/* Module declarations from 'cpython.buffer' */ - -/* Module declarations from 'cpython.bytes' */ - -/* Module declarations from 'cpython.pycapsule' */ - -/* Module declarations from 'cpython' */ - -/* Module declarations from 'libc.stdint' */ - -/* Module declarations from 'aiohttp._websocket' */ -#define __Pyx_MODULE_NAME "aiohttp._websocket" -extern int __pyx_module_is_main_aiohttp___websocket; -int __pyx_module_is_main_aiohttp___websocket = 0; - -/* Implementation of 'aiohttp._websocket' */ -static PyObject *__pyx_builtin_range; -static const char __pyx_k_i[] = "i"; -static const char __pyx_k_data[] = "data"; -static const char __pyx_k_main[] = "__main__"; -static const char __pyx_k_mask[] = "mask"; -static const char __pyx_k_name[] = "__name__"; -static const char __pyx_k_test[] = "__test__"; -static const char __pyx_k_range[] = "range"; -static const char __pyx_k_in_buf[] = "in_buf"; -static const char __pyx_k_data_len[] = "data_len"; -static const char __pyx_k_mask_buf[] = "mask_buf"; -static const char __pyx_k_uint32_msk[] = "uint32_msk"; -static const char __pyx_k_uint64_msk[] = "uint64_msk"; -static const char __pyx_k_aiohttp__websocket[] = "aiohttp._websocket"; -static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback"; -static const char __pyx_k_websocket_mask_cython[] = "_websocket_mask_cython"; -static const char __pyx_k_aiohttp__websocket_pyx[] = "aiohttp\\_websocket.pyx"; -static PyObject *__pyx_n_s_aiohttp__websocket; -static PyObject *__pyx_kp_s_aiohttp__websocket_pyx; -static PyObject *__pyx_n_s_cline_in_traceback; -static PyObject *__pyx_n_s_data; -static PyObject *__pyx_n_s_data_len; -static PyObject *__pyx_n_s_i; -static PyObject *__pyx_n_s_in_buf; -static PyObject *__pyx_n_s_main; -static PyObject *__pyx_n_s_mask; -static PyObject *__pyx_n_s_mask_buf; -static PyObject *__pyx_n_s_name; -static PyObject *__pyx_n_s_range; -static PyObject *__pyx_n_s_test; -static PyObject *__pyx_n_s_uint32_msk; -static PyObject *__pyx_n_s_uint64_msk; -static PyObject *__pyx_n_s_websocket_mask_cython; -static PyObject *__pyx_pf_7aiohttp_10_websocket__websocket_mask_cython(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_mask, PyObject *__pyx_v_data); /* proto */ -static PyObject *__pyx_tuple_; -static PyObject *__pyx_codeobj__2; -/* Late includes */ - -/* "aiohttp/_websocket.pyx":11 - * - * - * def _websocket_mask_cython(object mask, object data): # <<<<<<<<<<<<<< - * """Note, this function mutates its `data` argument - * """ - */ - -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_10_websocket_1_websocket_mask_cython(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static char __pyx_doc_7aiohttp_10_websocket__websocket_mask_cython[] = "Note, this function mutates its `data` argument\n "; -static PyMethodDef __pyx_mdef_7aiohttp_10_websocket_1_websocket_mask_cython = {"_websocket_mask_cython", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_7aiohttp_10_websocket_1_websocket_mask_cython, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7aiohttp_10_websocket__websocket_mask_cython}; -static PyObject *__pyx_pw_7aiohttp_10_websocket_1_websocket_mask_cython(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_mask = 0; - PyObject *__pyx_v_data = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - PyObject *__pyx_r = 0; - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_websocket_mask_cython (wrapper)", 0); - { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_mask,&__pyx_n_s_data,0}; - PyObject* values[2] = {0,0}; - if (unlikely(__pyx_kwds)) { - Py_ssize_t kw_args; - const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); - switch (pos_args) { - case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - CYTHON_FALLTHROUGH; - case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - CYTHON_FALLTHROUGH; - case 0: break; - default: goto __pyx_L5_argtuple_error; - } - kw_args = PyDict_Size(__pyx_kwds); - switch (pos_args) { - case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_mask)) != 0)) kw_args--; - else goto __pyx_L5_argtuple_error; - CYTHON_FALLTHROUGH; - case 1: - if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_data)) != 0)) kw_args--; - else { - __Pyx_RaiseArgtupleInvalid("_websocket_mask_cython", 1, 2, 2, 1); __PYX_ERR(0, 11, __pyx_L3_error) - } - } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_websocket_mask_cython") < 0)) __PYX_ERR(0, 11, __pyx_L3_error) - } - } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { - goto __pyx_L5_argtuple_error; - } else { - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - values[1] = PyTuple_GET_ITEM(__pyx_args, 1); - } - __pyx_v_mask = values[0]; - __pyx_v_data = values[1]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_websocket_mask_cython", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 11, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._websocket._websocket_mask_cython", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_10_websocket__websocket_mask_cython(__pyx_self, __pyx_v_mask, __pyx_v_data); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_10_websocket__websocket_mask_cython(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_mask, PyObject *__pyx_v_data) { - Py_ssize_t __pyx_v_data_len; - Py_ssize_t __pyx_v_i; - unsigned char *__pyx_v_in_buf; - unsigned char const *__pyx_v_mask_buf; - uint32_t __pyx_v_uint32_msk; - uint64_t __pyx_v_uint64_msk; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - Py_ssize_t __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - char *__pyx_t_5; - uint64_t *__pyx_t_6; - long __pyx_t_7; - uint32_t *__pyx_t_8; - Py_ssize_t __pyx_t_9; - Py_ssize_t __pyx_t_10; - Py_ssize_t __pyx_t_11; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("_websocket_mask_cython", 0); - __Pyx_INCREF(__pyx_v_mask); - __Pyx_INCREF(__pyx_v_data); - - /* "aiohttp/_websocket.pyx":22 - * uint64_t uint64_msk - * - * assert len(mask) == 4 # <<<<<<<<<<<<<< - * - * if not isinstance(mask, bytes): - */ - #ifndef CYTHON_WITHOUT_ASSERTIONS - if (unlikely(!Py_OptimizeFlag)) { - __pyx_t_1 = PyObject_Length(__pyx_v_mask); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 22, __pyx_L1_error) - if (unlikely(!((__pyx_t_1 == 4) != 0))) { - PyErr_SetNone(PyExc_AssertionError); - __PYX_ERR(0, 22, __pyx_L1_error) - } - } - #endif - - /* "aiohttp/_websocket.pyx":24 - * assert len(mask) == 4 - * - * if not isinstance(mask, bytes): # <<<<<<<<<<<<<< - * mask = bytes(mask) - * - */ - __pyx_t_2 = PyBytes_Check(__pyx_v_mask); - __pyx_t_3 = ((!(__pyx_t_2 != 0)) != 0); - if (__pyx_t_3) { - - /* "aiohttp/_websocket.pyx":25 - * - * if not isinstance(mask, bytes): - * mask = bytes(mask) # <<<<<<<<<<<<<< - * - * if isinstance(data, bytearray): - */ - __pyx_t_4 = __Pyx_PyObject_CallOneArg(((PyObject *)(&PyBytes_Type)), __pyx_v_mask); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 25, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF_SET(__pyx_v_mask, __pyx_t_4); - __pyx_t_4 = 0; - - /* "aiohttp/_websocket.pyx":24 - * assert len(mask) == 4 - * - * if not isinstance(mask, bytes): # <<<<<<<<<<<<<< - * mask = bytes(mask) - * - */ - } - - /* "aiohttp/_websocket.pyx":27 - * mask = bytes(mask) - * - * if isinstance(data, bytearray): # <<<<<<<<<<<<<< - * data = data - * else: - */ - __pyx_t_3 = PyByteArray_Check(__pyx_v_data); - __pyx_t_2 = (__pyx_t_3 != 0); - if (__pyx_t_2) { - - /* "aiohttp/_websocket.pyx":28 - * - * if isinstance(data, bytearray): - * data = data # <<<<<<<<<<<<<< - * else: - * data = bytearray(data) - */ - __pyx_t_4 = __pyx_v_data; - __Pyx_INCREF(__pyx_t_4); - __Pyx_DECREF_SET(__pyx_v_data, __pyx_t_4); - __pyx_t_4 = 0; - - /* "aiohttp/_websocket.pyx":27 - * mask = bytes(mask) - * - * if isinstance(data, bytearray): # <<<<<<<<<<<<<< - * data = data - * else: - */ - goto __pyx_L4; - } - - /* "aiohttp/_websocket.pyx":30 - * data = data - * else: - * data = bytearray(data) # <<<<<<<<<<<<<< - * - * data_len = len(data) - */ - /*else*/ { - __pyx_t_4 = __Pyx_PyObject_CallOneArg(((PyObject *)(&PyByteArray_Type)), __pyx_v_data); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 30, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF_SET(__pyx_v_data, __pyx_t_4); - __pyx_t_4 = 0; - } - __pyx_L4:; - - /* "aiohttp/_websocket.pyx":32 - * data = bytearray(data) - * - * data_len = len(data) # <<<<<<<<<<<<<< - * in_buf = PyByteArray_AsString(data) - * mask_buf = PyBytes_AsString(mask) - */ - __pyx_t_1 = PyObject_Length(__pyx_v_data); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(0, 32, __pyx_L1_error) - __pyx_v_data_len = __pyx_t_1; - - /* "aiohttp/_websocket.pyx":33 - * - * data_len = len(data) - * in_buf = PyByteArray_AsString(data) # <<<<<<<<<<<<<< - * mask_buf = PyBytes_AsString(mask) - * uint32_msk = (mask_buf)[0] - */ - if (!(likely(PyByteArray_CheckExact(__pyx_v_data))||((__pyx_v_data) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytearray", Py_TYPE(__pyx_v_data)->tp_name), 0))) __PYX_ERR(0, 33, __pyx_L1_error) - __pyx_t_5 = PyByteArray_AsString(((PyObject*)__pyx_v_data)); if (unlikely(__pyx_t_5 == ((char *)NULL))) __PYX_ERR(0, 33, __pyx_L1_error) - __pyx_v_in_buf = ((unsigned char *)__pyx_t_5); - - /* "aiohttp/_websocket.pyx":34 - * data_len = len(data) - * in_buf = PyByteArray_AsString(data) - * mask_buf = PyBytes_AsString(mask) # <<<<<<<<<<<<<< - * uint32_msk = (mask_buf)[0] - * - */ - __pyx_t_5 = PyBytes_AsString(__pyx_v_mask); if (unlikely(__pyx_t_5 == ((char *)NULL))) __PYX_ERR(0, 34, __pyx_L1_error) - __pyx_v_mask_buf = ((unsigned char const *)__pyx_t_5); - - /* "aiohttp/_websocket.pyx":35 - * in_buf = PyByteArray_AsString(data) - * mask_buf = PyBytes_AsString(mask) - * uint32_msk = (mask_buf)[0] # <<<<<<<<<<<<<< - * - * # TODO: align in_data ptr to achieve even faster speeds - */ - __pyx_v_uint32_msk = (((uint32_t *)__pyx_v_mask_buf)[0]); - - /* "aiohttp/_websocket.pyx":40 - * # does it need in python ?! malloc() always aligns to sizeof(long) bytes - * - * if sizeof(size_t) >= 8: # <<<<<<<<<<<<<< - * uint64_msk = uint32_msk - * uint64_msk = (uint64_msk << 32) | uint32_msk - */ - __pyx_t_2 = (((sizeof(size_t)) >= 8) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_websocket.pyx":41 - * - * if sizeof(size_t) >= 8: - * uint64_msk = uint32_msk # <<<<<<<<<<<<<< - * uint64_msk = (uint64_msk << 32) | uint32_msk - * - */ - __pyx_v_uint64_msk = __pyx_v_uint32_msk; - - /* "aiohttp/_websocket.pyx":42 - * if sizeof(size_t) >= 8: - * uint64_msk = uint32_msk - * uint64_msk = (uint64_msk << 32) | uint32_msk # <<<<<<<<<<<<<< - * - * while data_len >= 8: - */ - __pyx_v_uint64_msk = ((__pyx_v_uint64_msk << 32) | __pyx_v_uint32_msk); - - /* "aiohttp/_websocket.pyx":44 - * uint64_msk = (uint64_msk << 32) | uint32_msk - * - * while data_len >= 8: # <<<<<<<<<<<<<< - * (in_buf)[0] ^= uint64_msk - * in_buf += 8 - */ - while (1) { - __pyx_t_2 = ((__pyx_v_data_len >= 8) != 0); - if (!__pyx_t_2) break; - - /* "aiohttp/_websocket.pyx":45 - * - * while data_len >= 8: - * (in_buf)[0] ^= uint64_msk # <<<<<<<<<<<<<< - * in_buf += 8 - * data_len -= 8 - */ - __pyx_t_6 = ((uint64_t *)__pyx_v_in_buf); - __pyx_t_7 = 0; - (__pyx_t_6[__pyx_t_7]) = ((__pyx_t_6[__pyx_t_7]) ^ __pyx_v_uint64_msk); - - /* "aiohttp/_websocket.pyx":46 - * while data_len >= 8: - * (in_buf)[0] ^= uint64_msk - * in_buf += 8 # <<<<<<<<<<<<<< - * data_len -= 8 - * - */ - __pyx_v_in_buf = (__pyx_v_in_buf + 8); - - /* "aiohttp/_websocket.pyx":47 - * (in_buf)[0] ^= uint64_msk - * in_buf += 8 - * data_len -= 8 # <<<<<<<<<<<<<< - * - * - */ - __pyx_v_data_len = (__pyx_v_data_len - 8); - } - - /* "aiohttp/_websocket.pyx":40 - * # does it need in python ?! malloc() always aligns to sizeof(long) bytes - * - * if sizeof(size_t) >= 8: # <<<<<<<<<<<<<< - * uint64_msk = uint32_msk - * uint64_msk = (uint64_msk << 32) | uint32_msk - */ - } - - /* "aiohttp/_websocket.pyx":50 - * - * - * while data_len >= 4: # <<<<<<<<<<<<<< - * (in_buf)[0] ^= uint32_msk - * in_buf += 4 - */ - while (1) { - __pyx_t_2 = ((__pyx_v_data_len >= 4) != 0); - if (!__pyx_t_2) break; - - /* "aiohttp/_websocket.pyx":51 - * - * while data_len >= 4: - * (in_buf)[0] ^= uint32_msk # <<<<<<<<<<<<<< - * in_buf += 4 - * data_len -= 4 - */ - __pyx_t_8 = ((uint32_t *)__pyx_v_in_buf); - __pyx_t_7 = 0; - (__pyx_t_8[__pyx_t_7]) = ((__pyx_t_8[__pyx_t_7]) ^ __pyx_v_uint32_msk); - - /* "aiohttp/_websocket.pyx":52 - * while data_len >= 4: - * (in_buf)[0] ^= uint32_msk - * in_buf += 4 # <<<<<<<<<<<<<< - * data_len -= 4 - * - */ - __pyx_v_in_buf = (__pyx_v_in_buf + 4); - - /* "aiohttp/_websocket.pyx":53 - * (in_buf)[0] ^= uint32_msk - * in_buf += 4 - * data_len -= 4 # <<<<<<<<<<<<<< - * - * for i in range(0, data_len): - */ - __pyx_v_data_len = (__pyx_v_data_len - 4); - } - - /* "aiohttp/_websocket.pyx":55 - * data_len -= 4 - * - * for i in range(0, data_len): # <<<<<<<<<<<<<< - * in_buf[i] ^= mask_buf[i] - */ - __pyx_t_1 = __pyx_v_data_len; - __pyx_t_9 = __pyx_t_1; - for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_9; __pyx_t_10+=1) { - __pyx_v_i = __pyx_t_10; - - /* "aiohttp/_websocket.pyx":56 - * - * for i in range(0, data_len): - * in_buf[i] ^= mask_buf[i] # <<<<<<<<<<<<<< - */ - __pyx_t_11 = __pyx_v_i; - (__pyx_v_in_buf[__pyx_t_11]) = ((__pyx_v_in_buf[__pyx_t_11]) ^ (__pyx_v_mask_buf[__pyx_v_i])); - } - - /* "aiohttp/_websocket.pyx":11 - * - * - * def _websocket_mask_cython(object mask, object data): # <<<<<<<<<<<<<< - * """Note, this function mutates its `data` argument - * """ - */ - - /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("aiohttp._websocket._websocket_mask_cython", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __pyx_L0:; - __Pyx_XDECREF(__pyx_v_mask); - __Pyx_XDECREF(__pyx_v_data); - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyMethodDef __pyx_methods[] = { - {0, 0, 0, 0} -}; - -#if PY_MAJOR_VERSION >= 3 -#if CYTHON_PEP489_MULTI_PHASE_INIT -static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ -static int __pyx_pymod_exec__websocket(PyObject* module); /*proto*/ -static PyModuleDef_Slot __pyx_moduledef_slots[] = { - {Py_mod_create, (void*)__pyx_pymod_create}, - {Py_mod_exec, (void*)__pyx_pymod_exec__websocket}, - {0, NULL} -}; -#endif - -static struct PyModuleDef __pyx_moduledef = { - PyModuleDef_HEAD_INIT, - "_websocket", - 0, /* m_doc */ - #if CYTHON_PEP489_MULTI_PHASE_INIT - 0, /* m_size */ - #else - -1, /* m_size */ - #endif - __pyx_methods /* m_methods */, - #if CYTHON_PEP489_MULTI_PHASE_INIT - __pyx_moduledef_slots, /* m_slots */ - #else - NULL, /* m_reload */ - #endif - NULL, /* m_traverse */ - NULL, /* m_clear */ - NULL /* m_free */ -}; -#endif -#ifndef CYTHON_SMALL_CODE -#if defined(__clang__) - #define CYTHON_SMALL_CODE -#elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) - #define CYTHON_SMALL_CODE __attribute__((cold)) -#else - #define CYTHON_SMALL_CODE -#endif -#endif - -static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__pyx_n_s_aiohttp__websocket, __pyx_k_aiohttp__websocket, sizeof(__pyx_k_aiohttp__websocket), 0, 0, 1, 1}, - {&__pyx_kp_s_aiohttp__websocket_pyx, __pyx_k_aiohttp__websocket_pyx, sizeof(__pyx_k_aiohttp__websocket_pyx), 0, 0, 1, 0}, - {&__pyx_n_s_cline_in_traceback, __pyx_k_cline_in_traceback, sizeof(__pyx_k_cline_in_traceback), 0, 0, 1, 1}, - {&__pyx_n_s_data, __pyx_k_data, sizeof(__pyx_k_data), 0, 0, 1, 1}, - {&__pyx_n_s_data_len, __pyx_k_data_len, sizeof(__pyx_k_data_len), 0, 0, 1, 1}, - {&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1}, - {&__pyx_n_s_in_buf, __pyx_k_in_buf, sizeof(__pyx_k_in_buf), 0, 0, 1, 1}, - {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, - {&__pyx_n_s_mask, __pyx_k_mask, sizeof(__pyx_k_mask), 0, 0, 1, 1}, - {&__pyx_n_s_mask_buf, __pyx_k_mask_buf, sizeof(__pyx_k_mask_buf), 0, 0, 1, 1}, - {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, - {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, - {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, - {&__pyx_n_s_uint32_msk, __pyx_k_uint32_msk, sizeof(__pyx_k_uint32_msk), 0, 0, 1, 1}, - {&__pyx_n_s_uint64_msk, __pyx_k_uint64_msk, sizeof(__pyx_k_uint64_msk), 0, 0, 1, 1}, - {&__pyx_n_s_websocket_mask_cython, __pyx_k_websocket_mask_cython, sizeof(__pyx_k_websocket_mask_cython), 0, 0, 1, 1}, - {0, 0, 0, 0, 0, 0, 0} -}; -static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 55, __pyx_L1_error) - return 0; - __pyx_L1_error:; - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); - - /* "aiohttp/_websocket.pyx":11 - * - * - * def _websocket_mask_cython(object mask, object data): # <<<<<<<<<<<<<< - * """Note, this function mutates its `data` argument - * """ - */ - __pyx_tuple_ = PyTuple_Pack(8, __pyx_n_s_mask, __pyx_n_s_data, __pyx_n_s_data_len, __pyx_n_s_i, __pyx_n_s_in_buf, __pyx_n_s_mask_buf, __pyx_n_s_uint32_msk, __pyx_n_s_uint64_msk); if (unlikely(!__pyx_tuple_)) __PYX_ERR(0, 11, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple_); - __Pyx_GIVEREF(__pyx_tuple_); - __pyx_codeobj__2 = (PyObject*)__Pyx_PyCode_New(2, 0, 8, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple_, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_aiohttp__websocket_pyx, __pyx_n_s_websocket_mask_cython, 11, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__2)) __PYX_ERR(0, 11, __pyx_L1_error) - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_RefNannyFinishContext(); - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) { - if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error); - return 0; - __pyx_L1_error:; - return -1; -} - -static CYTHON_SMALL_CODE int __Pyx_modinit_global_init_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_variable_export_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_function_export_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_type_init_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_type_import_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_variable_import_code(void); /*proto*/ -static CYTHON_SMALL_CODE int __Pyx_modinit_function_import_code(void); /*proto*/ - -static int __Pyx_modinit_global_init_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_global_init_code", 0); - /*--- Global init code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_variable_export_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_variable_export_code", 0); - /*--- Variable export code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_function_export_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_function_export_code", 0); - /*--- Function export code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_type_init_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); - /*--- Type init code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_type_import_code(void) { - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); - /*--- Type import code ---*/ - __pyx_t_1 = PyImport_ImportModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 9, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__pyx_t_1, __Pyx_BUILTIN_MODULE_NAME, "type", - #if defined(PYPY_VERSION_NUM) && PYPY_VERSION_NUM < 0x050B0000 - sizeof(PyTypeObject), - #else - sizeof(PyHeapTypeObject), - #endif - __Pyx_ImportType_CheckSize_Warn); - if (!__pyx_ptype_7cpython_4type_type) __PYX_ERR(1, 9, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyImport_ImportModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_t_1)) __PYX_ERR(2, 8, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_ptype_7cpython_4bool_bool = __Pyx_ImportType(__pyx_t_1, __Pyx_BUILTIN_MODULE_NAME, "bool", sizeof(PyBoolObject), __Pyx_ImportType_CheckSize_Warn); - if (!__pyx_ptype_7cpython_4bool_bool) __PYX_ERR(2, 8, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = PyImport_ImportModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_t_1)) __PYX_ERR(3, 15, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_ptype_7cpython_7complex_complex = __Pyx_ImportType(__pyx_t_1, __Pyx_BUILTIN_MODULE_NAME, "complex", sizeof(PyComplexObject), __Pyx_ImportType_CheckSize_Warn); - if (!__pyx_ptype_7cpython_7complex_complex) __PYX_ERR(3, 15, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_RefNannyFinishContext(); - return -1; -} - -static int __Pyx_modinit_variable_import_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_variable_import_code", 0); - /*--- Variable import code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - -static int __Pyx_modinit_function_import_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_function_import_code", 0); - /*--- Function import code ---*/ - __Pyx_RefNannyFinishContext(); - return 0; -} - - -#ifndef CYTHON_NO_PYINIT_EXPORT -#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC -#elif PY_MAJOR_VERSION < 3 -#ifdef __cplusplus -#define __Pyx_PyMODINIT_FUNC extern "C" void -#else -#define __Pyx_PyMODINIT_FUNC void -#endif -#else -#ifdef __cplusplus -#define __Pyx_PyMODINIT_FUNC extern "C" PyObject * -#else -#define __Pyx_PyMODINIT_FUNC PyObject * -#endif -#endif - - -#if PY_MAJOR_VERSION < 3 -__Pyx_PyMODINIT_FUNC init_websocket(void) CYTHON_SMALL_CODE; /*proto*/ -__Pyx_PyMODINIT_FUNC init_websocket(void) -#else -__Pyx_PyMODINIT_FUNC PyInit__websocket(void) CYTHON_SMALL_CODE; /*proto*/ -__Pyx_PyMODINIT_FUNC PyInit__websocket(void) -#if CYTHON_PEP489_MULTI_PHASE_INIT -{ - return PyModuleDef_Init(&__pyx_moduledef); -} -static CYTHON_SMALL_CODE int __Pyx_check_single_interpreter(void) { - #if PY_VERSION_HEX >= 0x030700A1 - static PY_INT64_T main_interpreter_id = -1; - PY_INT64_T current_id = PyInterpreterState_GetID(PyThreadState_Get()->interp); - if (main_interpreter_id == -1) { - main_interpreter_id = current_id; - return (unlikely(current_id == -1)) ? -1 : 0; - } else if (unlikely(main_interpreter_id != current_id)) - #else - static PyInterpreterState *main_interpreter = NULL; - PyInterpreterState *current_interpreter = PyThreadState_Get()->interp; - if (!main_interpreter) { - main_interpreter = current_interpreter; - } else if (unlikely(main_interpreter != current_interpreter)) - #endif - { - PyErr_SetString( - PyExc_ImportError, - "Interpreter change detected - this module can only be loaded into one interpreter per process."); - return -1; - } - return 0; -} -static CYTHON_SMALL_CODE int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name, int allow_none) { - PyObject *value = PyObject_GetAttrString(spec, from_name); - int result = 0; - if (likely(value)) { - if (allow_none || value != Py_None) { - result = PyDict_SetItemString(moddict, to_name, value); - } - Py_DECREF(value); - } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Clear(); - } else { - result = -1; - } - return result; -} -static CYTHON_SMALL_CODE PyObject* __pyx_pymod_create(PyObject *spec, CYTHON_UNUSED PyModuleDef *def) { - PyObject *module = NULL, *moddict, *modname; - if (__Pyx_check_single_interpreter()) - return NULL; - if (__pyx_m) - return __Pyx_NewRef(__pyx_m); - modname = PyObject_GetAttrString(spec, "name"); - if (unlikely(!modname)) goto bad; - module = PyModule_NewObject(modname); - Py_DECREF(modname); - if (unlikely(!module)) goto bad; - moddict = PyModule_GetDict(module); - if (unlikely(!moddict)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__", 1) < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__", 1) < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__", 1) < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__", 0) < 0)) goto bad; - return module; -bad: - Py_XDECREF(module); - return NULL; -} - - -static CYTHON_SMALL_CODE int __pyx_pymod_exec__websocket(PyObject *__pyx_pyinit_module) -#endif -#endif -{ - PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannyDeclarations - #if CYTHON_PEP489_MULTI_PHASE_INIT - if (__pyx_m) { - if (__pyx_m == __pyx_pyinit_module) return 0; - PyErr_SetString(PyExc_RuntimeError, "Module '_websocket' has already been imported. Re-initialisation is not supported."); - return -1; - } - #elif PY_MAJOR_VERSION >= 3 - if (__pyx_m) return __Pyx_NewRef(__pyx_m); - #endif - #if CYTHON_REFNANNY -__Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); -if (!__Pyx_RefNanny) { - PyErr_Clear(); - __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); - if (!__Pyx_RefNanny) - Py_FatalError("failed to import 'refnanny' module"); -} -#endif - __Pyx_RefNannySetupContext("__Pyx_PyMODINIT_FUNC PyInit__websocket(void)", 0); - if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #ifdef __Pxy_PyFrame_Initialize_Offsets - __Pxy_PyFrame_Initialize_Offsets(); - #endif - __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) - __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) - #ifdef __Pyx_CyFunction_USED - if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_FusedFunction_USED - if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_Coroutine_USED - if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_Generator_USED - if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_AsyncGen_USED - if (__pyx_AsyncGen_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - #ifdef __Pyx_StopAsyncIteration_USED - if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - /*--- Library function declarations ---*/ - /*--- Threads initialization code ---*/ - #if defined(WITH_THREAD) && PY_VERSION_HEX < 0x030700F0 && defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS - PyEval_InitThreads(); - #endif - /*--- Module creation code ---*/ - #if CYTHON_PEP489_MULTI_PHASE_INIT - __pyx_m = __pyx_pyinit_module; - Py_INCREF(__pyx_m); - #else - #if PY_MAJOR_VERSION < 3 - __pyx_m = Py_InitModule4("_websocket", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); - #else - __pyx_m = PyModule_Create(&__pyx_moduledef); - #endif - if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_d); - __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_b); - __pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) - Py_INCREF(__pyx_cython_runtime); - if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error); - /*--- Initialize various global constants etc. ---*/ - if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) - if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - if (__pyx_module_is_main_aiohttp___websocket) { - if (PyObject_SetAttr(__pyx_m, __pyx_n_s_name, __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - } - #if PY_MAJOR_VERSION >= 3 - { - PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) - if (!PyDict_GetItemString(modules, "aiohttp._websocket")) { - if (unlikely(PyDict_SetItemString(modules, "aiohttp._websocket", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error) - } - } - #endif - /*--- Builtin init code ---*/ - if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - /*--- Constants init code ---*/ - if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - /*--- Global type/function init code ---*/ - (void)__Pyx_modinit_global_init_code(); - (void)__Pyx_modinit_variable_export_code(); - (void)__Pyx_modinit_function_export_code(); - (void)__Pyx_modinit_type_init_code(); - if (unlikely(__Pyx_modinit_type_import_code() < 0)) __PYX_ERR(0, 1, __pyx_L1_error) - (void)__Pyx_modinit_variable_import_code(); - (void)__Pyx_modinit_function_import_code(); - /*--- Execution code ---*/ - #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) - if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) - #endif - - /* "aiohttp/_websocket.pyx":11 - * - * - * def _websocket_mask_cython(object mask, object data): # <<<<<<<<<<<<<< - * """Note, this function mutates its `data` argument - * """ - */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7aiohttp_10_websocket_1_websocket_mask_cython, NULL, __pyx_n_s_aiohttp__websocket); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 11, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_websocket_mask_cython, __pyx_t_1) < 0) __PYX_ERR(0, 11, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_websocket.pyx":1 - * from cpython cimport PyBytes_AsString # <<<<<<<<<<<<<< - * - * - */ - __pyx_t_1 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) __PYX_ERR(0, 1, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /*--- Wrapped vars code ---*/ - - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - if (__pyx_m) { - if (__pyx_d) { - __Pyx_AddTraceback("init aiohttp._websocket", __pyx_clineno, __pyx_lineno, __pyx_filename); - } - Py_CLEAR(__pyx_m); - } else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_ImportError, "init aiohttp._websocket"); - } - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - #if CYTHON_PEP489_MULTI_PHASE_INIT - return (__pyx_m != NULL) ? 0 : -1; - #elif PY_MAJOR_VERSION >= 3 - return __pyx_m; - #else - return; - #endif -} - -/* --- Runtime support code --- */ -/* Refnanny */ -#if CYTHON_REFNANNY -static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { - PyObject *m = NULL, *p = NULL; - void *r = NULL; - m = PyImport_ImportModule(modname); - if (!m) goto end; - p = PyObject_GetAttrString(m, "RefNannyAPI"); - if (!p) goto end; - r = PyLong_AsVoidPtr(p); -end: - Py_XDECREF(p); - Py_XDECREF(m); - return (__Pyx_RefNannyAPIStruct *)r; -} -#endif - -/* PyObjectGetAttrStr */ -#if CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { - PyTypeObject* tp = Py_TYPE(obj); - if (likely(tp->tp_getattro)) - return tp->tp_getattro(obj, attr_name); -#if PY_MAJOR_VERSION < 3 - if (likely(tp->tp_getattr)) - return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); -#endif - return PyObject_GetAttr(obj, attr_name); -} -#endif - -/* GetBuiltinName */ -static PyObject *__Pyx_GetBuiltinName(PyObject *name) { - PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); - if (unlikely(!result)) { - PyErr_Format(PyExc_NameError, -#if PY_MAJOR_VERSION >= 3 - "name '%U' is not defined", name); -#else - "name '%.200s' is not defined", PyString_AS_STRING(name)); -#endif - } - return result; -} - -/* RaiseArgTupleInvalid */ -static void __Pyx_RaiseArgtupleInvalid( - const char* func_name, - int exact, - Py_ssize_t num_min, - Py_ssize_t num_max, - Py_ssize_t num_found) -{ - Py_ssize_t num_expected; - const char *more_or_less; - if (num_found < num_min) { - num_expected = num_min; - more_or_less = "at least"; - } else { - num_expected = num_max; - more_or_less = "at most"; - } - if (exact) { - more_or_less = "exactly"; - } - PyErr_Format(PyExc_TypeError, - "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", - func_name, more_or_less, num_expected, - (num_expected == 1) ? "" : "s", num_found); -} - -/* RaiseDoubleKeywords */ -static void __Pyx_RaiseDoubleKeywordsError( - const char* func_name, - PyObject* kw_name) -{ - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION >= 3 - "%s() got multiple values for keyword argument '%U'", func_name, kw_name); - #else - "%s() got multiple values for keyword argument '%s'", func_name, - PyString_AsString(kw_name)); - #endif -} - -/* ParseKeywords */ -static int __Pyx_ParseOptionalKeywords( - PyObject *kwds, - PyObject **argnames[], - PyObject *kwds2, - PyObject *values[], - Py_ssize_t num_pos_args, - const char* function_name) -{ - PyObject *key = 0, *value = 0; - Py_ssize_t pos = 0; - PyObject*** name; - PyObject*** first_kw_arg = argnames + num_pos_args; - while (PyDict_Next(kwds, &pos, &key, &value)) { - name = first_kw_arg; - while (*name && (**name != key)) name++; - if (*name) { - values[name-argnames] = value; - continue; - } - name = first_kw_arg; - #if PY_MAJOR_VERSION < 3 - if (likely(PyString_Check(key))) { - while (*name) { - if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) - && _PyString_Eq(**name, key)) { - values[name-argnames] = value; - break; - } - name++; - } - if (*name) continue; - else { - PyObject*** argname = argnames; - while (argname != first_kw_arg) { - if ((**argname == key) || ( - (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) - && _PyString_Eq(**argname, key))) { - goto arg_passed_twice; - } - argname++; - } - } - } else - #endif - if (likely(PyUnicode_Check(key))) { - while (*name) { - int cmp = (**name == key) ? 0 : - #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 - (__Pyx_PyUnicode_GET_LENGTH(**name) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : - #endif - PyUnicode_Compare(**name, key); - if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; - if (cmp == 0) { - values[name-argnames] = value; - break; - } - name++; - } - if (*name) continue; - else { - PyObject*** argname = argnames; - while (argname != first_kw_arg) { - int cmp = (**argname == key) ? 0 : - #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 - (__Pyx_PyUnicode_GET_LENGTH(**argname) != __Pyx_PyUnicode_GET_LENGTH(key)) ? 1 : - #endif - PyUnicode_Compare(**argname, key); - if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; - if (cmp == 0) goto arg_passed_twice; - argname++; - } - } - } else - goto invalid_keyword_type; - if (kwds2) { - if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; - } else { - goto invalid_keyword; - } - } - return 0; -arg_passed_twice: - __Pyx_RaiseDoubleKeywordsError(function_name, key); - goto bad; -invalid_keyword_type: - PyErr_Format(PyExc_TypeError, - "%.200s() keywords must be strings", function_name); - goto bad; -invalid_keyword: - PyErr_Format(PyExc_TypeError, - #if PY_MAJOR_VERSION < 3 - "%.200s() got an unexpected keyword argument '%.200s'", - function_name, PyString_AsString(key)); - #else - "%s() got an unexpected keyword argument '%U'", - function_name, key); - #endif -bad: - return -1; -} - -/* PyCFunctionFastCall */ -#if CYTHON_FAST_PYCCALL -static CYTHON_INLINE PyObject * __Pyx_PyCFunction_FastCall(PyObject *func_obj, PyObject **args, Py_ssize_t nargs) { - PyCFunctionObject *func = (PyCFunctionObject*)func_obj; - PyCFunction meth = PyCFunction_GET_FUNCTION(func); - PyObject *self = PyCFunction_GET_SELF(func); - int flags = PyCFunction_GET_FLAGS(func); - assert(PyCFunction_Check(func)); - assert(METH_FASTCALL == (flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS | METH_STACKLESS))); - assert(nargs >= 0); - assert(nargs == 0 || args != NULL); - /* _PyCFunction_FastCallDict() must not be called with an exception set, - because it may clear it (directly or indirectly) and so the - caller loses its exception */ - assert(!PyErr_Occurred()); - if ((PY_VERSION_HEX < 0x030700A0) || unlikely(flags & METH_KEYWORDS)) { - return (*((__Pyx_PyCFunctionFastWithKeywords)(void*)meth)) (self, args, nargs, NULL); - } else { - return (*((__Pyx_PyCFunctionFast)(void*)meth)) (self, args, nargs); - } -} -#endif - -/* PyFunctionFastCall */ -#if CYTHON_FAST_PYCALL -static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na, - PyObject *globals) { - PyFrameObject *f; - PyThreadState *tstate = __Pyx_PyThreadState_Current; - PyObject **fastlocals; - Py_ssize_t i; - PyObject *result; - assert(globals != NULL); - /* XXX Perhaps we should create a specialized - PyFrame_New() that doesn't take locals, but does - take builtins without sanity checking them. - */ - assert(tstate != NULL); - f = PyFrame_New(tstate, co, globals, NULL); - if (f == NULL) { - return NULL; - } - fastlocals = __Pyx_PyFrame_GetLocalsplus(f); - for (i = 0; i < na; i++) { - Py_INCREF(*args); - fastlocals[i] = *args++; - } - result = PyEval_EvalFrameEx(f,0); - ++tstate->recursion_depth; - Py_DECREF(f); - --tstate->recursion_depth; - return result; -} -#if 1 || PY_VERSION_HEX < 0x030600B1 -static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) { - PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); - PyObject *globals = PyFunction_GET_GLOBALS(func); - PyObject *argdefs = PyFunction_GET_DEFAULTS(func); - PyObject *closure; -#if PY_MAJOR_VERSION >= 3 - PyObject *kwdefs; -#endif - PyObject *kwtuple, **k; - PyObject **d; - Py_ssize_t nd; - Py_ssize_t nk; - PyObject *result; - assert(kwargs == NULL || PyDict_Check(kwargs)); - nk = kwargs ? PyDict_Size(kwargs) : 0; - if (Py_EnterRecursiveCall((char*)" while calling a Python object")) { - return NULL; - } - if ( -#if PY_MAJOR_VERSION >= 3 - co->co_kwonlyargcount == 0 && -#endif - likely(kwargs == NULL || nk == 0) && - co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { - if (argdefs == NULL && co->co_argcount == nargs) { - result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals); - goto done; - } - else if (nargs == 0 && argdefs != NULL - && co->co_argcount == Py_SIZE(argdefs)) { - /* function called with no arguments, but all parameters have - a default value: use default values as arguments .*/ - args = &PyTuple_GET_ITEM(argdefs, 0); - result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals); - goto done; - } - } - if (kwargs != NULL) { - Py_ssize_t pos, i; - kwtuple = PyTuple_New(2 * nk); - if (kwtuple == NULL) { - result = NULL; - goto done; - } - k = &PyTuple_GET_ITEM(kwtuple, 0); - pos = i = 0; - while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) { - Py_INCREF(k[i]); - Py_INCREF(k[i+1]); - i += 2; - } - nk = i / 2; - } - else { - kwtuple = NULL; - k = NULL; - } - closure = PyFunction_GET_CLOSURE(func); -#if PY_MAJOR_VERSION >= 3 - kwdefs = PyFunction_GET_KW_DEFAULTS(func); -#endif - if (argdefs != NULL) { - d = &PyTuple_GET_ITEM(argdefs, 0); - nd = Py_SIZE(argdefs); - } - else { - d = NULL; - nd = 0; - } -#if PY_MAJOR_VERSION >= 3 - result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL, - args, (int)nargs, - k, (int)nk, - d, (int)nd, kwdefs, closure); -#else - result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL, - args, (int)nargs, - k, (int)nk, - d, (int)nd, closure); -#endif - Py_XDECREF(kwtuple); -done: - Py_LeaveRecursiveCall(); - return result; -} -#endif -#endif - -/* PyObjectCall */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { - PyObject *result; - ternaryfunc call = Py_TYPE(func)->tp_call; - if (unlikely(!call)) - return PyObject_Call(func, arg, kw); - if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) - return NULL; - result = (*call)(func, arg, kw); - Py_LeaveRecursiveCall(); - if (unlikely(!result) && unlikely(!PyErr_Occurred())) { - PyErr_SetString( - PyExc_SystemError, - "NULL result without error in PyObject_Call"); - } - return result; -} -#endif - -/* PyObjectCallMethO */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { - PyObject *self, *result; - PyCFunction cfunc; - cfunc = PyCFunction_GET_FUNCTION(func); - self = PyCFunction_GET_SELF(func); - if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) - return NULL; - result = cfunc(self, arg); - Py_LeaveRecursiveCall(); - if (unlikely(!result) && unlikely(!PyErr_Occurred())) { - PyErr_SetString( - PyExc_SystemError, - "NULL result without error in PyObject_Call"); - } - return result; -} -#endif - -/* PyObjectCallOneArg */ -#if CYTHON_COMPILING_IN_CPYTHON -static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { - PyObject *result; - PyObject *args = PyTuple_New(1); - if (unlikely(!args)) return NULL; - Py_INCREF(arg); - PyTuple_SET_ITEM(args, 0, arg); - result = __Pyx_PyObject_Call(func, args, NULL); - Py_DECREF(args); - return result; -} -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { -#if CYTHON_FAST_PYCALL - if (PyFunction_Check(func)) { - return __Pyx_PyFunction_FastCall(func, &arg, 1); - } -#endif - if (likely(PyCFunction_Check(func))) { - if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { - return __Pyx_PyObject_CallMethO(func, arg); -#if CYTHON_FAST_PYCCALL - } else if (__Pyx_PyFastCFunction_Check(func)) { - return __Pyx_PyCFunction_FastCall(func, &arg, 1); -#endif - } - } - return __Pyx__PyObject_CallOneArg(func, arg); -} -#else -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { - PyObject *result; - PyObject *args = PyTuple_Pack(1, arg); - if (unlikely(!args)) return NULL; - result = __Pyx_PyObject_Call(func, args, NULL); - Py_DECREF(args); - return result; -} -#endif - -/* TypeImport */ -#ifndef __PYX_HAVE_RT_ImportType -#define __PYX_HAVE_RT_ImportType -static PyTypeObject *__Pyx_ImportType(PyObject *module, const char *module_name, const char *class_name, - size_t size, enum __Pyx_ImportType_CheckSize check_size) -{ - PyObject *result = 0; - char warning[200]; - Py_ssize_t basicsize; -#ifdef Py_LIMITED_API - PyObject *py_basicsize; -#endif - result = PyObject_GetAttrString(module, class_name); - if (!result) - goto bad; - if (!PyType_Check(result)) { - PyErr_Format(PyExc_TypeError, - "%.200s.%.200s is not a type object", - module_name, class_name); - goto bad; - } -#ifndef Py_LIMITED_API - basicsize = ((PyTypeObject *)result)->tp_basicsize; -#else - py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); - if (!py_basicsize) - goto bad; - basicsize = PyLong_AsSsize_t(py_basicsize); - Py_DECREF(py_basicsize); - py_basicsize = 0; - if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) - goto bad; -#endif - if ((size_t)basicsize < size) { - PyErr_Format(PyExc_ValueError, - "%.200s.%.200s size changed, may indicate binary incompatibility. " - "Expected %zd from C header, got %zd from PyObject", - module_name, class_name, size, basicsize); - goto bad; - } - if (check_size == __Pyx_ImportType_CheckSize_Error && (size_t)basicsize != size) { - PyErr_Format(PyExc_ValueError, - "%.200s.%.200s size changed, may indicate binary incompatibility. " - "Expected %zd from C header, got %zd from PyObject", - module_name, class_name, size, basicsize); - goto bad; - } - else if (check_size == __Pyx_ImportType_CheckSize_Warn && (size_t)basicsize > size) { - PyOS_snprintf(warning, sizeof(warning), - "%s.%s size changed, may indicate binary incompatibility. " - "Expected %zd from C header, got %zd from PyObject", - module_name, class_name, size, basicsize); - if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; - } - return (PyTypeObject *)result; -bad: - Py_XDECREF(result); - return NULL; -} -#endif - -/* PyDictVersioning */ -#if CYTHON_USE_DICT_VERSIONS && CYTHON_USE_TYPE_SLOTS -static CYTHON_INLINE PY_UINT64_T __Pyx_get_tp_dict_version(PyObject *obj) { - PyObject *dict = Py_TYPE(obj)->tp_dict; - return likely(dict) ? __PYX_GET_DICT_VERSION(dict) : 0; -} -static CYTHON_INLINE PY_UINT64_T __Pyx_get_object_dict_version(PyObject *obj) { - PyObject **dictptr = NULL; - Py_ssize_t offset = Py_TYPE(obj)->tp_dictoffset; - if (offset) { -#if CYTHON_COMPILING_IN_CPYTHON - dictptr = (likely(offset > 0)) ? (PyObject **) ((char *)obj + offset) : _PyObject_GetDictPtr(obj); -#else - dictptr = _PyObject_GetDictPtr(obj); -#endif - } - return (dictptr && *dictptr) ? __PYX_GET_DICT_VERSION(*dictptr) : 0; -} -static CYTHON_INLINE int __Pyx_object_dict_version_matches(PyObject* obj, PY_UINT64_T tp_dict_version, PY_UINT64_T obj_dict_version) { - PyObject *dict = Py_TYPE(obj)->tp_dict; - if (unlikely(!dict) || unlikely(tp_dict_version != __PYX_GET_DICT_VERSION(dict))) - return 0; - return obj_dict_version == __Pyx_get_object_dict_version(obj); -} -#endif - -/* PyErrFetchRestore */ -#if CYTHON_FAST_THREAD_STATE -static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { - PyObject *tmp_type, *tmp_value, *tmp_tb; - tmp_type = tstate->curexc_type; - tmp_value = tstate->curexc_value; - tmp_tb = tstate->curexc_traceback; - tstate->curexc_type = type; - tstate->curexc_value = value; - tstate->curexc_traceback = tb; - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -} -static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { - *type = tstate->curexc_type; - *value = tstate->curexc_value; - *tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; -} -#endif - -/* CLineInTraceback */ -#ifndef CYTHON_CLINE_IN_TRACEBACK -static int __Pyx_CLineForTraceback(CYTHON_NCP_UNUSED PyThreadState *tstate, int c_line) { - PyObject *use_cline; - PyObject *ptype, *pvalue, *ptraceback; -#if CYTHON_COMPILING_IN_CPYTHON - PyObject **cython_runtime_dict; -#endif - if (unlikely(!__pyx_cython_runtime)) { - return c_line; - } - __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); -#if CYTHON_COMPILING_IN_CPYTHON - cython_runtime_dict = _PyObject_GetDictPtr(__pyx_cython_runtime); - if (likely(cython_runtime_dict)) { - __PYX_PY_DICT_LOOKUP_IF_MODIFIED( - use_cline, *cython_runtime_dict, - __Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_n_s_cline_in_traceback)) - } else -#endif - { - PyObject *use_cline_obj = __Pyx_PyObject_GetAttrStr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback); - if (use_cline_obj) { - use_cline = PyObject_Not(use_cline_obj) ? Py_False : Py_True; - Py_DECREF(use_cline_obj); - } else { - PyErr_Clear(); - use_cline = NULL; - } - } - if (!use_cline) { - c_line = 0; - PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False); - } - else if (use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { - c_line = 0; - } - __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); - return c_line; -} -#endif - -/* CodeObjectCache */ -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { - int start = 0, mid = 0, end = count - 1; - if (end >= 0 && code_line > entries[end].code_line) { - return count; - } - while (start < end) { - mid = start + (end - start) / 2; - if (code_line < entries[mid].code_line) { - end = mid; - } else if (code_line > entries[mid].code_line) { - start = mid + 1; - } else { - return mid; - } - } - if (code_line <= entries[mid].code_line) { - return mid; - } else { - return mid + 1; - } -} -static PyCodeObject *__pyx_find_code_object(int code_line) { - PyCodeObject* code_object; - int pos; - if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { - return NULL; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { - return NULL; - } - code_object = __pyx_code_cache.entries[pos].code_object; - Py_INCREF(code_object); - return code_object; -} -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { - int pos, i; - __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; - if (unlikely(!code_line)) { - return; - } - if (unlikely(!entries)) { - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); - if (likely(entries)) { - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = 64; - __pyx_code_cache.count = 1; - entries[0].code_line = code_line; - entries[0].code_object = code_object; - Py_INCREF(code_object); - } - return; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { - PyCodeObject* tmp = entries[pos].code_object; - entries[pos].code_object = code_object; - Py_DECREF(tmp); - return; - } - if (__pyx_code_cache.count == __pyx_code_cache.max_count) { - int new_max = __pyx_code_cache.max_count + 64; - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( - __pyx_code_cache.entries, ((size_t)new_max) * sizeof(__Pyx_CodeObjectCacheEntry)); - if (unlikely(!entries)) { - return; - } - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = new_max; - } - for (i=__pyx_code_cache.count; i>pos; i--) { - entries[i] = entries[i-1]; - } - entries[pos].code_line = code_line; - entries[pos].code_object = code_object; - __pyx_code_cache.count++; - Py_INCREF(code_object); -} - -/* AddTraceback */ -#include "compile.h" -#include "frameobject.h" -#include "traceback.h" -static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( - const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyObject *py_srcfile = 0; - PyObject *py_funcname = 0; - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(filename); - #else - py_srcfile = PyUnicode_FromString(filename); - #endif - if (!py_srcfile) goto bad; - if (c_line) { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #endif - } - else { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromString(funcname); - #else - py_funcname = PyUnicode_FromString(funcname); - #endif - } - if (!py_funcname) goto bad; - py_code = __Pyx_PyCode_New( - 0, - 0, - 0, - 0, - 0, - __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ - py_srcfile, /*PyObject *filename,*/ - py_funcname, /*PyObject *name,*/ - py_line, - __pyx_empty_bytes /*PyObject *lnotab*/ - ); - Py_DECREF(py_srcfile); - Py_DECREF(py_funcname); - return py_code; -bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); - return NULL; -} -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - PyThreadState *tstate = __Pyx_PyThreadState_Current; - if (c_line) { - c_line = __Pyx_CLineForTraceback(tstate, c_line); - } - py_code = __pyx_find_code_object(c_line ? -c_line : py_line); - if (!py_code) { - py_code = __Pyx_CreateCodeObjectForTraceback( - funcname, c_line, py_line, filename); - if (!py_code) goto bad; - __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); - } - py_frame = PyFrame_New( - tstate, /*PyThreadState *tstate,*/ - py_code, /*PyCodeObject *code,*/ - __pyx_d, /*PyObject *globals,*/ - 0 /*PyObject *locals*/ - ); - if (!py_frame) goto bad; - __Pyx_PyFrame_SetLineNumber(py_frame, py_line); - PyTraceBack_Here(py_frame); -bad: - Py_XDECREF(py_code); - Py_XDECREF(py_frame); -} - -/* CIntToPy */ -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - const long neg_one = (long) -1, const_zero = (long) 0; -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic pop -#endif - const int is_unsigned = neg_one > const_zero; - if (is_unsigned) { - if (sizeof(long) < sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof(long) <= sizeof(unsigned long)) { - return PyLong_FromUnsignedLong((unsigned long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); -#endif - } - } else { - if (sizeof(long) <= sizeof(long)) { - return PyInt_FromLong((long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { - return PyLong_FromLongLong((PY_LONG_LONG) value); -#endif - } - } - { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&value; - return _PyLong_FromByteArray(bytes, sizeof(long), - little, !is_unsigned); - } -} - -/* CIntFromPyVerify */ -#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ - __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) -#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ - __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) -#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ - {\ - func_type value = func_value;\ - if (sizeof(target_type) < sizeof(func_type)) {\ - if (unlikely(value != (func_type) (target_type) value)) {\ - func_type zero = 0;\ - if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ - return (target_type) -1;\ - if (is_unsigned && unlikely(value < zero))\ - goto raise_neg_overflow;\ - else\ - goto raise_overflow;\ - }\ - }\ - return (target_type) value;\ - } - -/* CIntFromPy */ -static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - const long neg_one = (long) -1, const_zero = (long) 0; -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic pop -#endif - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - if (sizeof(long) < sizeof(long)) { - __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) - } else { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - goto raise_neg_overflow; - } - return (long) val; - } - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (long) 0; - case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0]) - case 2: - if (8 * sizeof(long) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) { - return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - case 3: - if (8 * sizeof(long) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) { - return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - case 4: - if (8 * sizeof(long) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) { - return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); - } - } - break; - } -#endif -#if CYTHON_COMPILING_IN_CPYTHON - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } -#else - { - int result = PyObject_RichCompareBool(x, Py_False, Py_LT); - if (unlikely(result < 0)) - return (long) -1; - if (unlikely(result == 1)) - goto raise_neg_overflow; - } -#endif - if (sizeof(long) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) -#endif - } - } else { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (long) 0; - case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0])) - case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0]) - case -2: - if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 2: - if (8 * sizeof(long) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case -3: - if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 3: - if (8 * sizeof(long) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case -4: - if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - case 4: - if (8 * sizeof(long) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); - } - } - break; - } -#endif - if (sizeof(long) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) -#endif - } - } - { -#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); -#else - long val; - PyObject *v = __Pyx_PyNumber_IntOrLong(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } -#endif - return (long) -1; - } - } else { - long val; - PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); - if (!tmp) return (long) -1; - val = __Pyx_PyInt_As_long(tmp); - Py_DECREF(tmp); - return val; - } -raise_overflow: - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to long"); - return (long) -1; -raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to long"); - return (long) -1; -} - -/* CIntFromPy */ -static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wconversion" -#endif - const int neg_one = (int) -1, const_zero = (int) 0; -#ifdef __Pyx_HAS_GCC_DIAGNOSTIC -#pragma GCC diagnostic pop -#endif - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - if (sizeof(int) < sizeof(long)) { - __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) - } else { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - goto raise_neg_overflow; - } - return (int) val; - } - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (int) 0; - case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0]) - case 2: - if (8 * sizeof(int) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) { - return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - case 3: - if (8 * sizeof(int) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) { - return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - case 4: - if (8 * sizeof(int) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) { - return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); - } - } - break; - } -#endif -#if CYTHON_COMPILING_IN_CPYTHON - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } -#else - { - int result = PyObject_RichCompareBool(x, Py_False, Py_LT); - if (unlikely(result < 0)) - return (int) -1; - if (unlikely(result == 1)) - goto raise_neg_overflow; - } -#endif - if (sizeof(int) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) -#endif - } - } else { -#if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)x)->ob_digit; - switch (Py_SIZE(x)) { - case 0: return (int) 0; - case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0])) - case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0]) - case -2: - if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 2: - if (8 * sizeof(int) > 1 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case -3: - if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 3: - if (8 * sizeof(int) > 2 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case -4: - if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { - return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - case 4: - if (8 * sizeof(int) > 3 * PyLong_SHIFT) { - if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) - } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { - return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); - } - } - break; - } -#endif - if (sizeof(int) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) -#ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { - __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) -#endif - } - } - { -#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); -#else - int val; - PyObject *v = __Pyx_PyNumber_IntOrLong(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } -#endif - return (int) -1; - } - } else { - int val; - PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); - if (!tmp) return (int) -1; - val = __Pyx_PyInt_As_int(tmp); - Py_DECREF(tmp); - return val; - } -raise_overflow: - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to int"); - return (int) -1; -raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to int"); - return (int) -1; -} - -/* FastTypeChecks */ -#if CYTHON_COMPILING_IN_CPYTHON -static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { - while (a) { - a = a->tp_base; - if (a == b) - return 1; - } - return b == &PyBaseObject_Type; -} -static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { - PyObject *mro; - if (a == b) return 1; - mro = a->tp_mro; - if (likely(mro)) { - Py_ssize_t i, n; - n = PyTuple_GET_SIZE(mro); - for (i = 0; i < n; i++) { - if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) - return 1; - } - return 0; - } - return __Pyx_InBases(a, b); -} -#if PY_MAJOR_VERSION == 2 -static int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject* exc_type2) { - PyObject *exception, *value, *tb; - int res; - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __Pyx_ErrFetch(&exception, &value, &tb); - res = exc_type1 ? PyObject_IsSubclass(err, exc_type1) : 0; - if (unlikely(res == -1)) { - PyErr_WriteUnraisable(err); - res = 0; - } - if (!res) { - res = PyObject_IsSubclass(err, exc_type2); - if (unlikely(res == -1)) { - PyErr_WriteUnraisable(err); - res = 0; - } - } - __Pyx_ErrRestore(exception, value, tb); - return res; -} -#else -static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { - int res = exc_type1 ? __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type1) : 0; - if (!res) { - res = __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); - } - return res; -} -#endif -static int __Pyx_PyErr_GivenExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { - Py_ssize_t i, n; - assert(PyExceptionClass_Check(exc_type)); - n = PyTuple_GET_SIZE(tuple); -#if PY_MAJOR_VERSION >= 3 - for (i=0; ip) { - #if PY_MAJOR_VERSION < 3 - if (t->is_unicode) { - *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); - } else if (t->intern) { - *t->p = PyString_InternFromString(t->s); - } else { - *t->p = PyString_FromStringAndSize(t->s, t->n - 1); - } - #else - if (t->is_unicode | t->is_str) { - if (t->intern) { - *t->p = PyUnicode_InternFromString(t->s); - } else if (t->encoding) { - *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); - } else { - *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); - } - } else { - *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); - } - #endif - if (!*t->p) - return -1; - if (PyObject_Hash(*t->p) == -1) - return -1; - ++t; - } - return 0; -} - -static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { - return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); -} -static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { - Py_ssize_t ignore; - return __Pyx_PyObject_AsStringAndSize(o, &ignore); -} -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT -#if !CYTHON_PEP393_ENABLED -static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { - char* defenc_c; - PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); - if (!defenc) return NULL; - defenc_c = PyBytes_AS_STRING(defenc); -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - { - char* end = defenc_c + PyBytes_GET_SIZE(defenc); - char* c; - for (c = defenc_c; c < end; c++) { - if ((unsigned char) (*c) >= 128) { - PyUnicode_AsASCIIString(o); - return NULL; - } - } - } -#endif - *length = PyBytes_GET_SIZE(defenc); - return defenc_c; -} -#else -static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { - if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - if (likely(PyUnicode_IS_ASCII(o))) { - *length = PyUnicode_GET_LENGTH(o); - return PyUnicode_AsUTF8(o); - } else { - PyUnicode_AsASCIIString(o); - return NULL; - } -#else - return PyUnicode_AsUTF8AndSize(o, length); -#endif -} -#endif -#endif -static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { -#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT - if ( -#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - __Pyx_sys_getdefaultencoding_not_ascii && -#endif - PyUnicode_Check(o)) { - return __Pyx_PyUnicode_AsStringAndSize(o, length); - } else -#endif -#if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) - if (PyByteArray_Check(o)) { - *length = PyByteArray_GET_SIZE(o); - return PyByteArray_AS_STRING(o); - } else -#endif - { - char* result; - int r = PyBytes_AsStringAndSize(o, &result, length); - if (unlikely(r < 0)) { - return NULL; - } else { - return result; - } - } -} -static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { - int is_true = x == Py_True; - if (is_true | (x == Py_False) | (x == Py_None)) return is_true; - else return PyObject_IsTrue(x); -} -static CYTHON_INLINE int __Pyx_PyObject_IsTrueAndDecref(PyObject* x) { - int retval; - if (unlikely(!x)) return -1; - retval = __Pyx_PyObject_IsTrue(x); - Py_DECREF(x); - return retval; -} -static PyObject* __Pyx_PyNumber_IntOrLongWrongResultType(PyObject* result, const char* type_name) { -#if PY_MAJOR_VERSION >= 3 - if (PyLong_Check(result)) { - if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, - "__int__ returned non-int (type %.200s). " - "The ability to return an instance of a strict subclass of int " - "is deprecated, and may be removed in a future version of Python.", - Py_TYPE(result)->tp_name)) { - Py_DECREF(result); - return NULL; - } - return result; - } -#endif - PyErr_Format(PyExc_TypeError, - "__%.4s__ returned non-%.4s (type %.200s)", - type_name, type_name, Py_TYPE(result)->tp_name); - Py_DECREF(result); - return NULL; -} -static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { -#if CYTHON_USE_TYPE_SLOTS - PyNumberMethods *m; -#endif - const char *name = NULL; - PyObject *res = NULL; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x) || PyLong_Check(x))) -#else - if (likely(PyLong_Check(x))) -#endif - return __Pyx_NewRef(x); -#if CYTHON_USE_TYPE_SLOTS - m = Py_TYPE(x)->tp_as_number; - #if PY_MAJOR_VERSION < 3 - if (m && m->nb_int) { - name = "int"; - res = m->nb_int(x); - } - else if (m && m->nb_long) { - name = "long"; - res = m->nb_long(x); - } - #else - if (likely(m && m->nb_int)) { - name = "int"; - res = m->nb_int(x); - } - #endif -#else - if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { - res = PyNumber_Int(x); - } -#endif - if (likely(res)) { -#if PY_MAJOR_VERSION < 3 - if (unlikely(!PyInt_Check(res) && !PyLong_Check(res))) { -#else - if (unlikely(!PyLong_CheckExact(res))) { -#endif - return __Pyx_PyNumber_IntOrLongWrongResultType(res, name); - } - } - else if (!PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, - "an integer is required"); - } - return res; -} -static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { - Py_ssize_t ival; - PyObject *x; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_CheckExact(b))) { - if (sizeof(Py_ssize_t) >= sizeof(long)) - return PyInt_AS_LONG(b); - else - return PyInt_AsSsize_t(b); - } -#endif - if (likely(PyLong_CheckExact(b))) { - #if CYTHON_USE_PYLONG_INTERNALS - const digit* digits = ((PyLongObject*)b)->ob_digit; - const Py_ssize_t size = Py_SIZE(b); - if (likely(__Pyx_sst_abs(size) <= 1)) { - ival = likely(size) ? digits[0] : 0; - if (size == -1) ival = -ival; - return ival; - } else { - switch (size) { - case 2: - if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { - return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -2: - if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case 3: - if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { - return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -3: - if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case 4: - if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { - return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - case -4: - if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { - return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); - } - break; - } - } - #endif - return PyLong_AsSsize_t(b); - } - x = PyNumber_Index(b); - if (!x) return -1; - ival = PyInt_AsSsize_t(x); - Py_DECREF(x); - return ival; -} -static CYTHON_INLINE PyObject * __Pyx_PyBool_FromLong(long b) { - return b ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False); -} -static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { - return PyInt_FromSize_t(ival); -} - - -#endif /* Py_PYTHON_H */ diff --git a/.venv/Lib/site-packages/aiohttp/_websocket.cp38-win_amd64.pyd b/.venv/Lib/site-packages/aiohttp/_websocket.cp38-win_amd64.pyd deleted file mode 100644 index 018f13f..0000000 Binary files a/.venv/Lib/site-packages/aiohttp/_websocket.cp38-win_amd64.pyd and /dev/null differ diff --git a/.venv/Lib/site-packages/aiohttp/_websocket.pyx b/.venv/Lib/site-packages/aiohttp/_websocket.pyx deleted file mode 100644 index 94318d2..0000000 --- a/.venv/Lib/site-packages/aiohttp/_websocket.pyx +++ /dev/null @@ -1,56 +0,0 @@ -from cpython cimport PyBytes_AsString - - -#from cpython cimport PyByteArray_AsString # cython still not exports that -cdef extern from "Python.h": - char* PyByteArray_AsString(bytearray ba) except NULL - -from libc.stdint cimport uint32_t, uint64_t, uintmax_t - - -def _websocket_mask_cython(object mask, object data): - """Note, this function mutates its `data` argument - """ - cdef: - Py_ssize_t data_len, i - # bit operations on signed integers are implementation-specific - unsigned char * in_buf - const unsigned char * mask_buf - uint32_t uint32_msk - uint64_t uint64_msk - - assert len(mask) == 4 - - if not isinstance(mask, bytes): - mask = bytes(mask) - - if isinstance(data, bytearray): - data = data - else: - data = bytearray(data) - - data_len = len(data) - in_buf = PyByteArray_AsString(data) - mask_buf = PyBytes_AsString(mask) - uint32_msk = (mask_buf)[0] - - # TODO: align in_data ptr to achieve even faster speeds - # does it need in python ?! malloc() always aligns to sizeof(long) bytes - - if sizeof(size_t) >= 8: - uint64_msk = uint32_msk - uint64_msk = (uint64_msk << 32) | uint32_msk - - while data_len >= 8: - (in_buf)[0] ^= uint64_msk - in_buf += 8 - data_len -= 8 - - - while data_len >= 4: - (in_buf)[0] ^= uint32_msk - in_buf += 4 - data_len -= 4 - - for i in range(0, data_len): - in_buf[i] ^= mask_buf[i] diff --git a/.venv/Lib/site-packages/aiohttp/abc.py b/.venv/Lib/site-packages/aiohttp/abc.py deleted file mode 100644 index 06fc831..0000000 --- a/.venv/Lib/site-packages/aiohttp/abc.py +++ /dev/null @@ -1,207 +0,0 @@ -import asyncio -import logging -from abc import ABC, abstractmethod -from collections.abc import Sized -from http.cookies import BaseCookie, Morsel -from typing import ( - TYPE_CHECKING, - Any, - Awaitable, - Callable, - Dict, - Generator, - Iterable, - List, - Optional, - Tuple, -) - -from multidict import CIMultiDict -from yarl import URL - -from .helpers import get_running_loop -from .typedefs import LooseCookies - -if TYPE_CHECKING: # pragma: no cover - from .web_app import Application - from .web_exceptions import HTTPException - from .web_request import BaseRequest, Request - from .web_response import StreamResponse -else: - BaseRequest = Request = Application = StreamResponse = None - HTTPException = None - - -class AbstractRouter(ABC): - def __init__(self) -> None: - self._frozen = False - - def post_init(self, app: Application) -> None: - """Post init stage. - - Not an abstract method for sake of backward compatibility, - but if the router wants to be aware of the application - it can override this. - """ - - @property - def frozen(self) -> bool: - return self._frozen - - def freeze(self) -> None: - """Freeze router.""" - self._frozen = True - - @abstractmethod - async def resolve(self, request: Request) -> "AbstractMatchInfo": - """Return MATCH_INFO for given request""" - - -class AbstractMatchInfo(ABC): - @property # pragma: no branch - @abstractmethod - def handler(self) -> Callable[[Request], Awaitable[StreamResponse]]: - """Execute matched request handler""" - - @property - @abstractmethod - def expect_handler(self) -> Callable[[Request], Awaitable[None]]: - """Expect handler for 100-continue processing""" - - @property # pragma: no branch - @abstractmethod - def http_exception(self) -> Optional[HTTPException]: - """HTTPException instance raised on router's resolving, or None""" - - @abstractmethod # pragma: no branch - def get_info(self) -> Dict[str, Any]: - """Return a dict with additional info useful for introspection""" - - @property # pragma: no branch - @abstractmethod - def apps(self) -> Tuple[Application, ...]: - """Stack of nested applications. - - Top level application is left-most element. - - """ - - @abstractmethod - def add_app(self, app: Application) -> None: - """Add application to the nested apps stack.""" - - @abstractmethod - def freeze(self) -> None: - """Freeze the match info. - - The method is called after route resolution. - - After the call .add_app() is forbidden. - - """ - - -class AbstractView(ABC): - """Abstract class based view.""" - - def __init__(self, request: Request) -> None: - self._request = request - - @property - def request(self) -> Request: - """Request instance.""" - return self._request - - @abstractmethod - def __await__(self) -> Generator[Any, None, StreamResponse]: - """Execute the view handler.""" - - -class AbstractResolver(ABC): - """Abstract DNS resolver.""" - - @abstractmethod - async def resolve(self, host: str, port: int, family: int) -> List[Dict[str, Any]]: - """Return IP address for given hostname""" - - @abstractmethod - async def close(self) -> None: - """Release resolver""" - - -if TYPE_CHECKING: # pragma: no cover - IterableBase = Iterable[Morsel[str]] -else: - IterableBase = Iterable - - -ClearCookiePredicate = Callable[["Morsel[str]"], bool] - - -class AbstractCookieJar(Sized, IterableBase): - """Abstract Cookie Jar.""" - - def __init__(self, *, loop: Optional[asyncio.AbstractEventLoop] = None) -> None: - self._loop = get_running_loop(loop) - - @abstractmethod - def clear(self, predicate: Optional[ClearCookiePredicate] = None) -> None: - """Clear all cookies if no predicate is passed.""" - - @abstractmethod - def clear_domain(self, domain: str) -> None: - """Clear all cookies for domain and all subdomains.""" - - @abstractmethod - def update_cookies(self, cookies: LooseCookies, response_url: URL = URL()) -> None: - """Update cookies.""" - - @abstractmethod - def filter_cookies(self, request_url: URL) -> "BaseCookie[str]": - """Return the jar's cookies filtered by their attributes.""" - - -class AbstractStreamWriter(ABC): - """Abstract stream writer.""" - - buffer_size = 0 - output_size = 0 - length = 0 # type: Optional[int] - - @abstractmethod - async def write(self, chunk: bytes) -> None: - """Write chunk into stream.""" - - @abstractmethod - async def write_eof(self, chunk: bytes = b"") -> None: - """Write last chunk.""" - - @abstractmethod - async def drain(self) -> None: - """Flush the write buffer.""" - - @abstractmethod - def enable_compression(self, encoding: str = "deflate") -> None: - """Enable HTTP body compression""" - - @abstractmethod - def enable_chunking(self) -> None: - """Enable HTTP chunked mode""" - - @abstractmethod - async def write_headers( - self, status_line: str, headers: "CIMultiDict[str]" - ) -> None: - """Write HTTP headers""" - - -class AbstractAccessLogger(ABC): - """Abstract writer to access log.""" - - def __init__(self, logger: logging.Logger, log_format: str) -> None: - self.logger = logger - self.log_format = log_format - - @abstractmethod - def log(self, request: BaseRequest, response: StreamResponse, time: float) -> None: - """Emit log to logger.""" diff --git a/.venv/Lib/site-packages/aiohttp/base_protocol.py b/.venv/Lib/site-packages/aiohttp/base_protocol.py deleted file mode 100644 index fff4610..0000000 --- a/.venv/Lib/site-packages/aiohttp/base_protocol.py +++ /dev/null @@ -1,87 +0,0 @@ -import asyncio -from typing import Optional, cast - -from .tcp_helpers import tcp_nodelay - - -class BaseProtocol(asyncio.Protocol): - __slots__ = ( - "_loop", - "_paused", - "_drain_waiter", - "_connection_lost", - "_reading_paused", - "transport", - ) - - def __init__(self, loop: asyncio.AbstractEventLoop) -> None: - self._loop = loop # type: asyncio.AbstractEventLoop - self._paused = False - self._drain_waiter = None # type: Optional[asyncio.Future[None]] - self._connection_lost = False - self._reading_paused = False - - self.transport = None # type: Optional[asyncio.Transport] - - def pause_writing(self) -> None: - assert not self._paused - self._paused = True - - def resume_writing(self) -> None: - assert self._paused - self._paused = False - - waiter = self._drain_waiter - if waiter is not None: - self._drain_waiter = None - if not waiter.done(): - waiter.set_result(None) - - def pause_reading(self) -> None: - if not self._reading_paused and self.transport is not None: - try: - self.transport.pause_reading() - except (AttributeError, NotImplementedError, RuntimeError): - pass - self._reading_paused = True - - def resume_reading(self) -> None: - if self._reading_paused and self.transport is not None: - try: - self.transport.resume_reading() - except (AttributeError, NotImplementedError, RuntimeError): - pass - self._reading_paused = False - - def connection_made(self, transport: asyncio.BaseTransport) -> None: - tr = cast(asyncio.Transport, transport) - tcp_nodelay(tr, True) - self.transport = tr - - def connection_lost(self, exc: Optional[BaseException]) -> None: - self._connection_lost = True - # Wake up the writer if currently paused. - self.transport = None - if not self._paused: - return - waiter = self._drain_waiter - if waiter is None: - return - self._drain_waiter = None - if waiter.done(): - return - if exc is None: - waiter.set_result(None) - else: - waiter.set_exception(exc) - - async def _drain_helper(self) -> None: - if self._connection_lost: - raise ConnectionResetError("Connection lost") - if not self._paused: - return - waiter = self._drain_waiter - if waiter is None: - waiter = self._loop.create_future() - self._drain_waiter = waiter - await asyncio.shield(waiter) diff --git a/.venv/Lib/site-packages/aiohttp/client.py b/.venv/Lib/site-packages/aiohttp/client.py deleted file mode 100644 index c6e4a76..0000000 --- a/.venv/Lib/site-packages/aiohttp/client.py +++ /dev/null @@ -1,1302 +0,0 @@ -"""HTTP Client for asyncio.""" - -import asyncio -import base64 -import hashlib -import json -import os -import sys -import traceback -import warnings -from contextlib import suppress -from types import SimpleNamespace, TracebackType -from typing import ( - Any, - Awaitable, - Callable, - Coroutine, - FrozenSet, - Generator, - Generic, - Iterable, - List, - Mapping, - Optional, - Set, - Tuple, - Type, - TypeVar, - Union, -) - -import attr -from multidict import CIMultiDict, MultiDict, MultiDictProxy, istr -from yarl import URL - -from . import hdrs, http, payload -from .abc import AbstractCookieJar -from .client_exceptions import ( - ClientConnectionError as ClientConnectionError, - ClientConnectorCertificateError as ClientConnectorCertificateError, - ClientConnectorError as ClientConnectorError, - ClientConnectorSSLError as ClientConnectorSSLError, - ClientError as ClientError, - ClientHttpProxyError as ClientHttpProxyError, - ClientOSError as ClientOSError, - ClientPayloadError as ClientPayloadError, - ClientProxyConnectionError as ClientProxyConnectionError, - ClientResponseError as ClientResponseError, - ClientSSLError as ClientSSLError, - ContentTypeError as ContentTypeError, - InvalidURL as InvalidURL, - ServerConnectionError as ServerConnectionError, - ServerDisconnectedError as ServerDisconnectedError, - ServerFingerprintMismatch as ServerFingerprintMismatch, - ServerTimeoutError as ServerTimeoutError, - TooManyRedirects as TooManyRedirects, - WSServerHandshakeError as WSServerHandshakeError, -) -from .client_reqrep import ( - ClientRequest as ClientRequest, - ClientResponse as ClientResponse, - Fingerprint as Fingerprint, - RequestInfo as RequestInfo, - _merge_ssl_params, -) -from .client_ws import ClientWebSocketResponse as ClientWebSocketResponse -from .connector import ( - BaseConnector as BaseConnector, - NamedPipeConnector as NamedPipeConnector, - TCPConnector as TCPConnector, - UnixConnector as UnixConnector, -) -from .cookiejar import CookieJar -from .helpers import ( - DEBUG, - PY_36, - BasicAuth, - TimeoutHandle, - ceil_timeout, - get_env_proxy_for_url, - get_running_loop, - sentinel, - strip_auth_from_url, -) -from .http import WS_KEY, HttpVersion, WebSocketReader, WebSocketWriter -from .http_websocket import WSHandshakeError, WSMessage, ws_ext_gen, ws_ext_parse -from .streams import FlowControlDataQueue -from .tracing import Trace, TraceConfig -from .typedefs import Final, JSONEncoder, LooseCookies, LooseHeaders, StrOrURL - -__all__ = ( - # client_exceptions - "ClientConnectionError", - "ClientConnectorCertificateError", - "ClientConnectorError", - "ClientConnectorSSLError", - "ClientError", - "ClientHttpProxyError", - "ClientOSError", - "ClientPayloadError", - "ClientProxyConnectionError", - "ClientResponseError", - "ClientSSLError", - "ContentTypeError", - "InvalidURL", - "ServerConnectionError", - "ServerDisconnectedError", - "ServerFingerprintMismatch", - "ServerTimeoutError", - "TooManyRedirects", - "WSServerHandshakeError", - # client_reqrep - "ClientRequest", - "ClientResponse", - "Fingerprint", - "RequestInfo", - # connector - "BaseConnector", - "TCPConnector", - "UnixConnector", - "NamedPipeConnector", - # client_ws - "ClientWebSocketResponse", - # client - "ClientSession", - "ClientTimeout", - "request", -) - - -try: - from ssl import SSLContext -except ImportError: # pragma: no cover - SSLContext = object # type: ignore[misc,assignment] - - -@attr.s(auto_attribs=True, frozen=True, slots=True) -class ClientTimeout: - total: Optional[float] = None - connect: Optional[float] = None - sock_read: Optional[float] = None - sock_connect: Optional[float] = None - - # pool_queue_timeout: Optional[float] = None - # dns_resolution_timeout: Optional[float] = None - # socket_connect_timeout: Optional[float] = None - # connection_acquiring_timeout: Optional[float] = None - # new_connection_timeout: Optional[float] = None - # http_header_timeout: Optional[float] = None - # response_body_timeout: Optional[float] = None - - # to create a timeout specific for a single request, either - # - create a completely new one to overwrite the default - # - or use http://www.attrs.org/en/stable/api.html#attr.evolve - # to overwrite the defaults - - -# 5 Minute default read timeout -DEFAULT_TIMEOUT: Final[ClientTimeout] = ClientTimeout(total=5 * 60) - -_RetType = TypeVar("_RetType") - - -class ClientSession: - """First-class interface for making HTTP requests.""" - - ATTRS = frozenset( - [ - "_base_url", - "_source_traceback", - "_connector", - "requote_redirect_url", - "_loop", - "_cookie_jar", - "_connector_owner", - "_default_auth", - "_version", - "_json_serialize", - "_requote_redirect_url", - "_timeout", - "_raise_for_status", - "_auto_decompress", - "_trust_env", - "_default_headers", - "_skip_auto_headers", - "_request_class", - "_response_class", - "_ws_response_class", - "_trace_configs", - "_read_bufsize", - ] - ) - - _source_traceback = None - - def __init__( - self, - base_url: Optional[StrOrURL] = None, - *, - connector: Optional[BaseConnector] = None, - loop: Optional[asyncio.AbstractEventLoop] = None, - cookies: Optional[LooseCookies] = None, - headers: Optional[LooseHeaders] = None, - skip_auto_headers: Optional[Iterable[str]] = None, - auth: Optional[BasicAuth] = None, - json_serialize: JSONEncoder = json.dumps, - request_class: Type[ClientRequest] = ClientRequest, - response_class: Type[ClientResponse] = ClientResponse, - ws_response_class: Type[ClientWebSocketResponse] = ClientWebSocketResponse, - version: HttpVersion = http.HttpVersion11, - cookie_jar: Optional[AbstractCookieJar] = None, - connector_owner: bool = True, - raise_for_status: bool = False, - read_timeout: Union[float, object] = sentinel, - conn_timeout: Optional[float] = None, - timeout: Union[object, ClientTimeout] = sentinel, - auto_decompress: bool = True, - trust_env: bool = False, - requote_redirect_url: bool = True, - trace_configs: Optional[List[TraceConfig]] = None, - read_bufsize: int = 2 ** 16, - ) -> None: - if loop is None: - if connector is not None: - loop = connector._loop - - loop = get_running_loop(loop) - - if base_url is None or isinstance(base_url, URL): - self._base_url: Optional[URL] = base_url - else: - self._base_url = URL(base_url) - assert ( - self._base_url.origin() == self._base_url - ), "Only absolute URLs without path part are supported" - - if connector is None: - connector = TCPConnector(loop=loop) - - if connector._loop is not loop: - raise RuntimeError("Session and connector has to use same event loop") - - self._loop = loop - - if loop.get_debug(): - self._source_traceback = traceback.extract_stack(sys._getframe(1)) - - if cookie_jar is None: - cookie_jar = CookieJar(loop=loop) - self._cookie_jar = cookie_jar - - if cookies is not None: - self._cookie_jar.update_cookies(cookies) - - self._connector = connector # type: Optional[BaseConnector] - self._connector_owner = connector_owner - self._default_auth = auth - self._version = version - self._json_serialize = json_serialize - if timeout is sentinel: - self._timeout = DEFAULT_TIMEOUT - if read_timeout is not sentinel: - warnings.warn( - "read_timeout is deprecated, " "use timeout argument instead", - DeprecationWarning, - stacklevel=2, - ) - self._timeout = attr.evolve(self._timeout, total=read_timeout) - if conn_timeout is not None: - self._timeout = attr.evolve(self._timeout, connect=conn_timeout) - warnings.warn( - "conn_timeout is deprecated, " "use timeout argument instead", - DeprecationWarning, - stacklevel=2, - ) - else: - self._timeout = timeout # type: ignore[assignment] - if read_timeout is not sentinel: - raise ValueError( - "read_timeout and timeout parameters " - "conflict, please setup " - "timeout.read" - ) - if conn_timeout is not None: - raise ValueError( - "conn_timeout and timeout parameters " - "conflict, please setup " - "timeout.connect" - ) - self._raise_for_status = raise_for_status - self._auto_decompress = auto_decompress - self._trust_env = trust_env - self._requote_redirect_url = requote_redirect_url - self._read_bufsize = read_bufsize - - # Convert to list of tuples - if headers: - real_headers = CIMultiDict(headers) # type: CIMultiDict[str] - else: - real_headers = CIMultiDict() - self._default_headers = real_headers # type: CIMultiDict[str] - if skip_auto_headers is not None: - self._skip_auto_headers = frozenset(istr(i) for i in skip_auto_headers) - else: - self._skip_auto_headers = frozenset() - - self._request_class = request_class - self._response_class = response_class - self._ws_response_class = ws_response_class - - self._trace_configs = trace_configs or [] - for trace_config in self._trace_configs: - trace_config.freeze() - - def __init_subclass__(cls: Type["ClientSession"]) -> None: - warnings.warn( - "Inheritance class {} from ClientSession " - "is discouraged".format(cls.__name__), - DeprecationWarning, - stacklevel=2, - ) - - if DEBUG: - - def __setattr__(self, name: str, val: Any) -> None: - if name not in self.ATTRS: - warnings.warn( - "Setting custom ClientSession.{} attribute " - "is discouraged".format(name), - DeprecationWarning, - stacklevel=2, - ) - super().__setattr__(name, val) - - def __del__(self, _warnings: Any = warnings) -> None: - if not self.closed: - if PY_36: - kwargs = {"source": self} - else: - kwargs = {} - _warnings.warn( - f"Unclosed client session {self!r}", ResourceWarning, **kwargs - ) - context = {"client_session": self, "message": "Unclosed client session"} - if self._source_traceback is not None: - context["source_traceback"] = self._source_traceback - self._loop.call_exception_handler(context) - - def request( - self, method: str, url: StrOrURL, **kwargs: Any - ) -> "_RequestContextManager": - """Perform HTTP request.""" - return _RequestContextManager(self._request(method, url, **kwargs)) - - def _build_url(self, str_or_url: StrOrURL) -> URL: - url = URL(str_or_url) - if self._base_url is None: - return url - else: - assert not url.is_absolute() and url.path.startswith("/") - return self._base_url.join(url) - - async def _request( - self, - method: str, - str_or_url: StrOrURL, - *, - params: Optional[Mapping[str, str]] = None, - data: Any = None, - json: Any = None, - cookies: Optional[LooseCookies] = None, - headers: Optional[LooseHeaders] = None, - skip_auto_headers: Optional[Iterable[str]] = None, - auth: Optional[BasicAuth] = None, - allow_redirects: bool = True, - max_redirects: int = 10, - compress: Optional[str] = None, - chunked: Optional[bool] = None, - expect100: bool = False, - raise_for_status: Optional[bool] = None, - read_until_eof: bool = True, - proxy: Optional[StrOrURL] = None, - proxy_auth: Optional[BasicAuth] = None, - timeout: Union[ClientTimeout, object] = sentinel, - verify_ssl: Optional[bool] = None, - fingerprint: Optional[bytes] = None, - ssl_context: Optional[SSLContext] = None, - ssl: Optional[Union[SSLContext, bool, Fingerprint]] = None, - proxy_headers: Optional[LooseHeaders] = None, - trace_request_ctx: Optional[SimpleNamespace] = None, - read_bufsize: Optional[int] = None, - ) -> ClientResponse: - - # NOTE: timeout clamps existing connect and read timeouts. We cannot - # set the default to None because we need to detect if the user wants - # to use the existing timeouts by setting timeout to None. - - if self.closed: - raise RuntimeError("Session is closed") - - ssl = _merge_ssl_params(ssl, verify_ssl, ssl_context, fingerprint) - - if data is not None and json is not None: - raise ValueError( - "data and json parameters can not be used at the same time" - ) - elif json is not None: - data = payload.JsonPayload(json, dumps=self._json_serialize) - - if not isinstance(chunked, bool) and chunked is not None: - warnings.warn("Chunk size is deprecated #1615", DeprecationWarning) - - redirects = 0 - history = [] - version = self._version - - # Merge with default headers and transform to CIMultiDict - headers = self._prepare_headers(headers) - proxy_headers = self._prepare_headers(proxy_headers) - - try: - url = self._build_url(str_or_url) - except ValueError as e: - raise InvalidURL(str_or_url) from e - - skip_headers = set(self._skip_auto_headers) - if skip_auto_headers is not None: - for i in skip_auto_headers: - skip_headers.add(istr(i)) - - if proxy is not None: - try: - proxy = URL(proxy) - except ValueError as e: - raise InvalidURL(proxy) from e - - if timeout is sentinel: - real_timeout = self._timeout # type: ClientTimeout - else: - if not isinstance(timeout, ClientTimeout): - real_timeout = ClientTimeout(total=timeout) # type: ignore[arg-type] - else: - real_timeout = timeout - # timeout is cumulative for all request operations - # (request, redirects, responses, data consuming) - tm = TimeoutHandle(self._loop, real_timeout.total) - handle = tm.start() - - if read_bufsize is None: - read_bufsize = self._read_bufsize - - traces = [ - Trace( - self, - trace_config, - trace_config.trace_config_ctx(trace_request_ctx=trace_request_ctx), - ) - for trace_config in self._trace_configs - ] - - for trace in traces: - await trace.send_request_start(method, url.update_query(params), headers) - - timer = tm.timer() - try: - with timer: - while True: - url, auth_from_url = strip_auth_from_url(url) - if auth and auth_from_url: - raise ValueError( - "Cannot combine AUTH argument with " - "credentials encoded in URL" - ) - - if auth is None: - auth = auth_from_url - if auth is None: - auth = self._default_auth - # It would be confusing if we support explicit - # Authorization header with auth argument - if ( - headers is not None - and auth is not None - and hdrs.AUTHORIZATION in headers - ): - raise ValueError( - "Cannot combine AUTHORIZATION header " - "with AUTH argument or credentials " - "encoded in URL" - ) - - all_cookies = self._cookie_jar.filter_cookies(url) - - if cookies is not None: - tmp_cookie_jar = CookieJar() - tmp_cookie_jar.update_cookies(cookies) - req_cookies = tmp_cookie_jar.filter_cookies(url) - if req_cookies: - all_cookies.load(req_cookies) - - if proxy is not None: - proxy = URL(proxy) - elif self._trust_env: - with suppress(LookupError): - proxy, proxy_auth = get_env_proxy_for_url(url) - - req = self._request_class( - method, - url, - params=params, - headers=headers, - skip_auto_headers=skip_headers, - data=data, - cookies=all_cookies, - auth=auth, - version=version, - compress=compress, - chunked=chunked, - expect100=expect100, - loop=self._loop, - response_class=self._response_class, - proxy=proxy, - proxy_auth=proxy_auth, - timer=timer, - session=self, - ssl=ssl, - proxy_headers=proxy_headers, - traces=traces, - ) - - # connection timeout - try: - async with ceil_timeout(real_timeout.connect): - assert self._connector is not None - conn = await self._connector.connect( - req, traces=traces, timeout=real_timeout - ) - except asyncio.TimeoutError as exc: - raise ServerTimeoutError( - "Connection timeout " "to host {}".format(url) - ) from exc - - assert conn.transport is not None - - assert conn.protocol is not None - conn.protocol.set_response_params( - timer=timer, - skip_payload=method.upper() == "HEAD", - read_until_eof=read_until_eof, - auto_decompress=self._auto_decompress, - read_timeout=real_timeout.sock_read, - read_bufsize=read_bufsize, - ) - - try: - try: - resp = await req.send(conn) - try: - await resp.start(conn) - except BaseException: - resp.close() - raise - except BaseException: - conn.close() - raise - except ClientError: - raise - except OSError as exc: - raise ClientOSError(*exc.args) from exc - - self._cookie_jar.update_cookies(resp.cookies, resp.url) - - # redirects - if resp.status in (301, 302, 303, 307, 308) and allow_redirects: - - for trace in traces: - await trace.send_request_redirect( - method, url.update_query(params), headers, resp - ) - - redirects += 1 - history.append(resp) - if max_redirects and redirects >= max_redirects: - resp.close() - raise TooManyRedirects( - history[0].request_info, tuple(history) - ) - - # For 301 and 302, mimic IE, now changed in RFC - # https://github.com/kennethreitz/requests/pull/269 - if (resp.status == 303 and resp.method != hdrs.METH_HEAD) or ( - resp.status in (301, 302) and resp.method == hdrs.METH_POST - ): - method = hdrs.METH_GET - data = None - if headers.get(hdrs.CONTENT_LENGTH): - headers.pop(hdrs.CONTENT_LENGTH) - - r_url = resp.headers.get(hdrs.LOCATION) or resp.headers.get( - hdrs.URI - ) - if r_url is None: - # see github.com/aio-libs/aiohttp/issues/2022 - break - else: - # reading from correct redirection - # response is forbidden - resp.release() - - try: - parsed_url = URL( - r_url, encoded=not self._requote_redirect_url - ) - - except ValueError as e: - raise InvalidURL(r_url) from e - - scheme = parsed_url.scheme - if scheme not in ("http", "https", ""): - resp.close() - raise ValueError("Can redirect only to http or https") - elif not scheme: - parsed_url = url.join(parsed_url) - - if url.origin() != parsed_url.origin(): - auth = None - headers.pop(hdrs.AUTHORIZATION, None) - - url = parsed_url - params = None - resp.release() - continue - - break - - # check response status - if raise_for_status is None: - raise_for_status = self._raise_for_status - if raise_for_status: - resp.raise_for_status() - - # register connection - if handle is not None: - if resp.connection is not None: - resp.connection.add_callback(handle.cancel) - else: - handle.cancel() - - resp._history = tuple(history) - - for trace in traces: - await trace.send_request_end( - method, url.update_query(params), headers, resp - ) - return resp - - except BaseException as e: - # cleanup timer - tm.close() - if handle: - handle.cancel() - handle = None - - for trace in traces: - await trace.send_request_exception( - method, url.update_query(params), headers, e - ) - raise - - def ws_connect( - self, - url: StrOrURL, - *, - method: str = hdrs.METH_GET, - protocols: Iterable[str] = (), - timeout: float = 10.0, - receive_timeout: Optional[float] = None, - autoclose: bool = True, - autoping: bool = True, - heartbeat: Optional[float] = None, - auth: Optional[BasicAuth] = None, - origin: Optional[str] = None, - params: Optional[Mapping[str, str]] = None, - headers: Optional[LooseHeaders] = None, - proxy: Optional[StrOrURL] = None, - proxy_auth: Optional[BasicAuth] = None, - ssl: Union[SSLContext, bool, None, Fingerprint] = None, - verify_ssl: Optional[bool] = None, - fingerprint: Optional[bytes] = None, - ssl_context: Optional[SSLContext] = None, - proxy_headers: Optional[LooseHeaders] = None, - compress: int = 0, - max_msg_size: int = 4 * 1024 * 1024, - ) -> "_WSRequestContextManager": - """Initiate websocket connection.""" - return _WSRequestContextManager( - self._ws_connect( - url, - method=method, - protocols=protocols, - timeout=timeout, - receive_timeout=receive_timeout, - autoclose=autoclose, - autoping=autoping, - heartbeat=heartbeat, - auth=auth, - origin=origin, - params=params, - headers=headers, - proxy=proxy, - proxy_auth=proxy_auth, - ssl=ssl, - verify_ssl=verify_ssl, - fingerprint=fingerprint, - ssl_context=ssl_context, - proxy_headers=proxy_headers, - compress=compress, - max_msg_size=max_msg_size, - ) - ) - - async def _ws_connect( - self, - url: StrOrURL, - *, - method: str = hdrs.METH_GET, - protocols: Iterable[str] = (), - timeout: float = 10.0, - receive_timeout: Optional[float] = None, - autoclose: bool = True, - autoping: bool = True, - heartbeat: Optional[float] = None, - auth: Optional[BasicAuth] = None, - origin: Optional[str] = None, - params: Optional[Mapping[str, str]] = None, - headers: Optional[LooseHeaders] = None, - proxy: Optional[StrOrURL] = None, - proxy_auth: Optional[BasicAuth] = None, - ssl: Union[SSLContext, bool, None, Fingerprint] = None, - verify_ssl: Optional[bool] = None, - fingerprint: Optional[bytes] = None, - ssl_context: Optional[SSLContext] = None, - proxy_headers: Optional[LooseHeaders] = None, - compress: int = 0, - max_msg_size: int = 4 * 1024 * 1024, - ) -> ClientWebSocketResponse: - - if headers is None: - real_headers = CIMultiDict() # type: CIMultiDict[str] - else: - real_headers = CIMultiDict(headers) - - default_headers = { - hdrs.UPGRADE: "websocket", - hdrs.CONNECTION: "upgrade", - hdrs.SEC_WEBSOCKET_VERSION: "13", - } - - for key, value in default_headers.items(): - real_headers.setdefault(key, value) - - sec_key = base64.b64encode(os.urandom(16)) - real_headers[hdrs.SEC_WEBSOCKET_KEY] = sec_key.decode() - - if protocols: - real_headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = ",".join(protocols) - if origin is not None: - real_headers[hdrs.ORIGIN] = origin - if compress: - extstr = ws_ext_gen(compress=compress) - real_headers[hdrs.SEC_WEBSOCKET_EXTENSIONS] = extstr - - ssl = _merge_ssl_params(ssl, verify_ssl, ssl_context, fingerprint) - - # send request - resp = await self.request( - method, - url, - params=params, - headers=real_headers, - read_until_eof=False, - auth=auth, - proxy=proxy, - proxy_auth=proxy_auth, - ssl=ssl, - proxy_headers=proxy_headers, - ) - - try: - # check handshake - if resp.status != 101: - raise WSServerHandshakeError( - resp.request_info, - resp.history, - message="Invalid response status", - status=resp.status, - headers=resp.headers, - ) - - if resp.headers.get(hdrs.UPGRADE, "").lower() != "websocket": - raise WSServerHandshakeError( - resp.request_info, - resp.history, - message="Invalid upgrade header", - status=resp.status, - headers=resp.headers, - ) - - if resp.headers.get(hdrs.CONNECTION, "").lower() != "upgrade": - raise WSServerHandshakeError( - resp.request_info, - resp.history, - message="Invalid connection header", - status=resp.status, - headers=resp.headers, - ) - - # key calculation - r_key = resp.headers.get(hdrs.SEC_WEBSOCKET_ACCEPT, "") - match = base64.b64encode(hashlib.sha1(sec_key + WS_KEY).digest()).decode() - if r_key != match: - raise WSServerHandshakeError( - resp.request_info, - resp.history, - message="Invalid challenge response", - status=resp.status, - headers=resp.headers, - ) - - # websocket protocol - protocol = None - if protocols and hdrs.SEC_WEBSOCKET_PROTOCOL in resp.headers: - resp_protocols = [ - proto.strip() - for proto in resp.headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(",") - ] - - for proto in resp_protocols: - if proto in protocols: - protocol = proto - break - - # websocket compress - notakeover = False - if compress: - compress_hdrs = resp.headers.get(hdrs.SEC_WEBSOCKET_EXTENSIONS) - if compress_hdrs: - try: - compress, notakeover = ws_ext_parse(compress_hdrs) - except WSHandshakeError as exc: - raise WSServerHandshakeError( - resp.request_info, - resp.history, - message=exc.args[0], - status=resp.status, - headers=resp.headers, - ) from exc - else: - compress = 0 - notakeover = False - - conn = resp.connection - assert conn is not None - conn_proto = conn.protocol - assert conn_proto is not None - transport = conn.transport - assert transport is not None - reader = FlowControlDataQueue( - conn_proto, 2 ** 16, loop=self._loop - ) # type: FlowControlDataQueue[WSMessage] - conn_proto.set_parser(WebSocketReader(reader, max_msg_size), reader) - writer = WebSocketWriter( - conn_proto, - transport, - use_mask=True, - compress=compress, - notakeover=notakeover, - ) - except BaseException: - resp.close() - raise - else: - return self._ws_response_class( - reader, - writer, - protocol, - resp, - timeout, - autoclose, - autoping, - self._loop, - receive_timeout=receive_timeout, - heartbeat=heartbeat, - compress=compress, - client_notakeover=notakeover, - ) - - def _prepare_headers(self, headers: Optional[LooseHeaders]) -> "CIMultiDict[str]": - """Add default headers and transform it to CIMultiDict""" - # Convert headers to MultiDict - result = CIMultiDict(self._default_headers) - if headers: - if not isinstance(headers, (MultiDictProxy, MultiDict)): - headers = CIMultiDict(headers) - added_names = set() # type: Set[str] - for key, value in headers.items(): - if key in added_names: - result.add(key, value) - else: - result[key] = value - added_names.add(key) - return result - - def get( - self, url: StrOrURL, *, allow_redirects: bool = True, **kwargs: Any - ) -> "_RequestContextManager": - """Perform HTTP GET request.""" - return _RequestContextManager( - self._request(hdrs.METH_GET, url, allow_redirects=allow_redirects, **kwargs) - ) - - def options( - self, url: StrOrURL, *, allow_redirects: bool = True, **kwargs: Any - ) -> "_RequestContextManager": - """Perform HTTP OPTIONS request.""" - return _RequestContextManager( - self._request( - hdrs.METH_OPTIONS, url, allow_redirects=allow_redirects, **kwargs - ) - ) - - def head( - self, url: StrOrURL, *, allow_redirects: bool = False, **kwargs: Any - ) -> "_RequestContextManager": - """Perform HTTP HEAD request.""" - return _RequestContextManager( - self._request( - hdrs.METH_HEAD, url, allow_redirects=allow_redirects, **kwargs - ) - ) - - def post( - self, url: StrOrURL, *, data: Any = None, **kwargs: Any - ) -> "_RequestContextManager": - """Perform HTTP POST request.""" - return _RequestContextManager( - self._request(hdrs.METH_POST, url, data=data, **kwargs) - ) - - def put( - self, url: StrOrURL, *, data: Any = None, **kwargs: Any - ) -> "_RequestContextManager": - """Perform HTTP PUT request.""" - return _RequestContextManager( - self._request(hdrs.METH_PUT, url, data=data, **kwargs) - ) - - def patch( - self, url: StrOrURL, *, data: Any = None, **kwargs: Any - ) -> "_RequestContextManager": - """Perform HTTP PATCH request.""" - return _RequestContextManager( - self._request(hdrs.METH_PATCH, url, data=data, **kwargs) - ) - - def delete(self, url: StrOrURL, **kwargs: Any) -> "_RequestContextManager": - """Perform HTTP DELETE request.""" - return _RequestContextManager(self._request(hdrs.METH_DELETE, url, **kwargs)) - - async def close(self) -> None: - """Close underlying connector. - - Release all acquired resources. - """ - if not self.closed: - if self._connector is not None and self._connector_owner: - await self._connector.close() - self._connector = None - - @property - def closed(self) -> bool: - """Is client session closed. - - A readonly property. - """ - return self._connector is None or self._connector.closed - - @property - def connector(self) -> Optional[BaseConnector]: - """Connector instance used for the session.""" - return self._connector - - @property - def cookie_jar(self) -> AbstractCookieJar: - """The session cookies.""" - return self._cookie_jar - - @property - def version(self) -> Tuple[int, int]: - """The session HTTP protocol version.""" - return self._version - - @property - def requote_redirect_url(self) -> bool: - """Do URL requoting on redirection handling.""" - return self._requote_redirect_url - - @requote_redirect_url.setter - def requote_redirect_url(self, val: bool) -> None: - """Do URL requoting on redirection handling.""" - warnings.warn( - "session.requote_redirect_url modification " "is deprecated #2778", - DeprecationWarning, - stacklevel=2, - ) - self._requote_redirect_url = val - - @property - def loop(self) -> asyncio.AbstractEventLoop: - """Session's loop.""" - warnings.warn( - "client.loop property is deprecated", DeprecationWarning, stacklevel=2 - ) - return self._loop - - @property - def timeout(self) -> Union[object, ClientTimeout]: - """Timeout for the session.""" - return self._timeout - - @property - def headers(self) -> "CIMultiDict[str]": - """The default headers of the client session.""" - return self._default_headers - - @property - def skip_auto_headers(self) -> FrozenSet[istr]: - """Headers for which autogeneration should be skipped""" - return self._skip_auto_headers - - @property - def auth(self) -> Optional[BasicAuth]: - """An object that represents HTTP Basic Authorization""" - return self._default_auth - - @property - def json_serialize(self) -> JSONEncoder: - """Json serializer callable""" - return self._json_serialize - - @property - def connector_owner(self) -> bool: - """Should connector be closed on session closing""" - return self._connector_owner - - @property - def raise_for_status( - self, - ) -> Union[bool, Callable[[ClientResponse], Awaitable[None]]]: - """Should `ClientResponse.raise_for_status()` be called for each response.""" - return self._raise_for_status - - @property - def auto_decompress(self) -> bool: - """Should the body response be automatically decompressed.""" - return self._auto_decompress - - @property - def trust_env(self) -> bool: - """ - Should proxies information from environment or netrc be trusted. - - Information is from HTTP_PROXY / HTTPS_PROXY environment variables - or ~/.netrc file if present. - """ - return self._trust_env - - @property - def trace_configs(self) -> List[TraceConfig]: - """A list of TraceConfig instances used for client tracing""" - return self._trace_configs - - def detach(self) -> None: - """Detach connector from session without closing the former. - - Session is switched to closed state anyway. - """ - self._connector = None - - def __enter__(self) -> None: - raise TypeError("Use async with instead") - - def __exit__( - self, - exc_type: Optional[Type[BaseException]], - exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType], - ) -> None: - # __exit__ should exist in pair with __enter__ but never executed - pass # pragma: no cover - - async def __aenter__(self) -> "ClientSession": - return self - - async def __aexit__( - self, - exc_type: Optional[Type[BaseException]], - exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType], - ) -> None: - await self.close() - - -class _BaseRequestContextManager(Coroutine[Any, Any, _RetType], Generic[_RetType]): - - __slots__ = ("_coro", "_resp") - - def __init__(self, coro: Coroutine["asyncio.Future[Any]", None, _RetType]) -> None: - self._coro = coro - - def send(self, arg: None) -> "asyncio.Future[Any]": - return self._coro.send(arg) - - def throw(self, arg: BaseException) -> None: # type: ignore[arg-type,override] - self._coro.throw(arg) - - def close(self) -> None: - return self._coro.close() - - def __await__(self) -> Generator[Any, None, _RetType]: - ret = self._coro.__await__() - return ret - - def __iter__(self) -> Generator[Any, None, _RetType]: - return self.__await__() - - async def __aenter__(self) -> _RetType: - self._resp = await self._coro - return self._resp - - -class _RequestContextManager(_BaseRequestContextManager[ClientResponse]): - __slots__ = () - - async def __aexit__( - self, - exc_type: Optional[Type[BaseException]], - exc: Optional[BaseException], - tb: Optional[TracebackType], - ) -> None: - # We're basing behavior on the exception as it can be caused by - # user code unrelated to the status of the connection. If you - # would like to close a connection you must do that - # explicitly. Otherwise connection error handling should kick in - # and close/recycle the connection as required. - self._resp.release() - - -class _WSRequestContextManager(_BaseRequestContextManager[ClientWebSocketResponse]): - __slots__ = () - - async def __aexit__( - self, - exc_type: Optional[Type[BaseException]], - exc: Optional[BaseException], - tb: Optional[TracebackType], - ) -> None: - await self._resp.close() - - -class _SessionRequestContextManager: - - __slots__ = ("_coro", "_resp", "_session") - - def __init__( - self, - coro: Coroutine["asyncio.Future[Any]", None, ClientResponse], - session: ClientSession, - ) -> None: - self._coro = coro - self._resp = None # type: Optional[ClientResponse] - self._session = session - - async def __aenter__(self) -> ClientResponse: - try: - self._resp = await self._coro - except BaseException: - await self._session.close() - raise - else: - return self._resp - - async def __aexit__( - self, - exc_type: Optional[Type[BaseException]], - exc: Optional[BaseException], - tb: Optional[TracebackType], - ) -> None: - assert self._resp is not None - self._resp.close() - await self._session.close() - - -def request( - method: str, - url: StrOrURL, - *, - params: Optional[Mapping[str, str]] = None, - data: Any = None, - json: Any = None, - headers: Optional[LooseHeaders] = None, - skip_auto_headers: Optional[Iterable[str]] = None, - auth: Optional[BasicAuth] = None, - allow_redirects: bool = True, - max_redirects: int = 10, - compress: Optional[str] = None, - chunked: Optional[bool] = None, - expect100: bool = False, - raise_for_status: Optional[bool] = None, - read_until_eof: bool = True, - proxy: Optional[StrOrURL] = None, - proxy_auth: Optional[BasicAuth] = None, - timeout: Union[ClientTimeout, object] = sentinel, - cookies: Optional[LooseCookies] = None, - version: HttpVersion = http.HttpVersion11, - connector: Optional[BaseConnector] = None, - read_bufsize: Optional[int] = None, - loop: Optional[asyncio.AbstractEventLoop] = None, -) -> _SessionRequestContextManager: - """Constructs and sends a request. - - Returns response object. - method - HTTP method - url - request url - params - (optional) Dictionary or bytes to be sent in the query - string of the new request - data - (optional) Dictionary, bytes, or file-like object to - send in the body of the request - json - (optional) Any json compatible python object - headers - (optional) Dictionary of HTTP Headers to send with - the request - cookies - (optional) Dict object to send with the request - auth - (optional) BasicAuth named tuple represent HTTP Basic Auth - auth - aiohttp.helpers.BasicAuth - allow_redirects - (optional) If set to False, do not follow - redirects - version - Request HTTP version. - compress - Set to True if request has to be compressed - with deflate encoding. - chunked - Set to chunk size for chunked transfer encoding. - expect100 - Expect 100-continue response from server. - connector - BaseConnector sub-class instance to support - connection pooling. - read_until_eof - Read response until eof if response - does not have Content-Length header. - loop - Optional event loop. - timeout - Optional ClientTimeout settings structure, 5min - total timeout by default. - Usage:: - >>> import aiohttp - >>> resp = await aiohttp.request('GET', 'http://python.org/') - >>> resp - - >>> data = await resp.read() - """ - connector_owner = False - if connector is None: - connector_owner = True - connector = TCPConnector(loop=loop, force_close=True) - - session = ClientSession( - loop=loop, - cookies=cookies, - version=version, - timeout=timeout, - connector=connector, - connector_owner=connector_owner, - ) - - return _SessionRequestContextManager( - session._request( - method, - url, - params=params, - data=data, - json=json, - headers=headers, - skip_auto_headers=skip_auto_headers, - auth=auth, - allow_redirects=allow_redirects, - max_redirects=max_redirects, - compress=compress, - chunked=chunked, - expect100=expect100, - raise_for_status=raise_for_status, - read_until_eof=read_until_eof, - proxy=proxy, - proxy_auth=proxy_auth, - read_bufsize=read_bufsize, - ), - session, - ) diff --git a/.venv/Lib/site-packages/aiohttp/client_exceptions.py b/.venv/Lib/site-packages/aiohttp/client_exceptions.py deleted file mode 100644 index dd55321..0000000 --- a/.venv/Lib/site-packages/aiohttp/client_exceptions.py +++ /dev/null @@ -1,342 +0,0 @@ -"""HTTP related errors.""" - -import asyncio -import warnings -from typing import TYPE_CHECKING, Any, Optional, Tuple, Union - -from .http_parser import RawResponseMessage -from .typedefs import LooseHeaders - -try: - import ssl - - SSLContext = ssl.SSLContext -except ImportError: # pragma: no cover - ssl = SSLContext = None # type: ignore[assignment] - - -if TYPE_CHECKING: # pragma: no cover - from .client_reqrep import ClientResponse, ConnectionKey, Fingerprint, RequestInfo -else: - RequestInfo = ClientResponse = ConnectionKey = None - -__all__ = ( - "ClientError", - "ClientConnectionError", - "ClientOSError", - "ClientConnectorError", - "ClientProxyConnectionError", - "ClientSSLError", - "ClientConnectorSSLError", - "ClientConnectorCertificateError", - "ServerConnectionError", - "ServerTimeoutError", - "ServerDisconnectedError", - "ServerFingerprintMismatch", - "ClientResponseError", - "ClientHttpProxyError", - "WSServerHandshakeError", - "ContentTypeError", - "ClientPayloadError", - "InvalidURL", -) - - -class ClientError(Exception): - """Base class for client connection errors.""" - - -class ClientResponseError(ClientError): - """Connection error during reading response. - - request_info: instance of RequestInfo - """ - - def __init__( - self, - request_info: RequestInfo, - history: Tuple[ClientResponse, ...], - *, - code: Optional[int] = None, - status: Optional[int] = None, - message: str = "", - headers: Optional[LooseHeaders] = None, - ) -> None: - self.request_info = request_info - if code is not None: - if status is not None: - raise ValueError( - "Both code and status arguments are provided; " - "code is deprecated, use status instead" - ) - warnings.warn( - "code argument is deprecated, use status instead", - DeprecationWarning, - stacklevel=2, - ) - if status is not None: - self.status = status - elif code is not None: - self.status = code - else: - self.status = 0 - self.message = message - self.headers = headers - self.history = history - self.args = (request_info, history) - - def __str__(self) -> str: - return "{}, message={!r}, url={!r}".format( - self.status, - self.message, - self.request_info.real_url, - ) - - def __repr__(self) -> str: - args = f"{self.request_info!r}, {self.history!r}" - if self.status != 0: - args += f", status={self.status!r}" - if self.message != "": - args += f", message={self.message!r}" - if self.headers is not None: - args += f", headers={self.headers!r}" - return f"{type(self).__name__}({args})" - - @property - def code(self) -> int: - warnings.warn( - "code property is deprecated, use status instead", - DeprecationWarning, - stacklevel=2, - ) - return self.status - - @code.setter - def code(self, value: int) -> None: - warnings.warn( - "code property is deprecated, use status instead", - DeprecationWarning, - stacklevel=2, - ) - self.status = value - - -class ContentTypeError(ClientResponseError): - """ContentType found is not valid.""" - - -class WSServerHandshakeError(ClientResponseError): - """websocket server handshake error.""" - - -class ClientHttpProxyError(ClientResponseError): - """HTTP proxy error. - - Raised in :class:`aiohttp.connector.TCPConnector` if - proxy responds with status other than ``200 OK`` - on ``CONNECT`` request. - """ - - -class TooManyRedirects(ClientResponseError): - """Client was redirected too many times.""" - - -class ClientConnectionError(ClientError): - """Base class for client socket errors.""" - - -class ClientOSError(ClientConnectionError, OSError): - """OSError error.""" - - -class ClientConnectorError(ClientOSError): - """Client connector error. - - Raised in :class:`aiohttp.connector.TCPConnector` if - connection to proxy can not be established. - """ - - def __init__(self, connection_key: ConnectionKey, os_error: OSError) -> None: - self._conn_key = connection_key - self._os_error = os_error - super().__init__(os_error.errno, os_error.strerror) - self.args = (connection_key, os_error) - - @property - def os_error(self) -> OSError: - return self._os_error - - @property - def host(self) -> str: - return self._conn_key.host - - @property - def port(self) -> Optional[int]: - return self._conn_key.port - - @property - def ssl(self) -> Union[SSLContext, None, bool, "Fingerprint"]: - return self._conn_key.ssl - - def __str__(self) -> str: - return "Cannot connect to host {0.host}:{0.port} ssl:{1} [{2}]".format( - self, self.ssl if self.ssl is not None else "default", self.strerror - ) - - # OSError.__reduce__ does too much black magick - __reduce__ = BaseException.__reduce__ - - -class ClientProxyConnectionError(ClientConnectorError): - """Proxy connection error. - - Raised in :class:`aiohttp.connector.TCPConnector` if - connection to proxy can not be established. - """ - - -class UnixClientConnectorError(ClientConnectorError): - """Unix connector error. - - Raised in :py:class:`aiohttp.connector.UnixConnector` - if connection to unix socket can not be established. - """ - - def __init__( - self, path: str, connection_key: ConnectionKey, os_error: OSError - ) -> None: - self._path = path - super().__init__(connection_key, os_error) - - @property - def path(self) -> str: - return self._path - - def __str__(self) -> str: - return "Cannot connect to unix socket {0.path} ssl:{1} [{2}]".format( - self, self.ssl if self.ssl is not None else "default", self.strerror - ) - - -class ServerConnectionError(ClientConnectionError): - """Server connection errors.""" - - -class ServerDisconnectedError(ServerConnectionError): - """Server disconnected.""" - - def __init__(self, message: Union[RawResponseMessage, str, None] = None) -> None: - if message is None: - message = "Server disconnected" - - self.args = (message,) - self.message = message - - -class ServerTimeoutError(ServerConnectionError, asyncio.TimeoutError): - """Server timeout error.""" - - -class ServerFingerprintMismatch(ServerConnectionError): - """SSL certificate does not match expected fingerprint.""" - - def __init__(self, expected: bytes, got: bytes, host: str, port: int) -> None: - self.expected = expected - self.got = got - self.host = host - self.port = port - self.args = (expected, got, host, port) - - def __repr__(self) -> str: - return "<{} expected={!r} got={!r} host={!r} port={!r}>".format( - self.__class__.__name__, self.expected, self.got, self.host, self.port - ) - - -class ClientPayloadError(ClientError): - """Response payload error.""" - - -class InvalidURL(ClientError, ValueError): - """Invalid URL. - - URL used for fetching is malformed, e.g. it doesn't contains host - part. - """ - - # Derive from ValueError for backward compatibility - - def __init__(self, url: Any) -> None: - # The type of url is not yarl.URL because the exception can be raised - # on URL(url) call - super().__init__(url) - - @property - def url(self) -> Any: - return self.args[0] - - def __repr__(self) -> str: - return f"<{self.__class__.__name__} {self.url}>" - - -class ClientSSLError(ClientConnectorError): - """Base error for ssl.*Errors.""" - - -if ssl is not None: - cert_errors = (ssl.CertificateError,) - cert_errors_bases = ( - ClientSSLError, - ssl.CertificateError, - ) - - ssl_errors = (ssl.SSLError,) - ssl_error_bases = (ClientSSLError, ssl.SSLError) -else: # pragma: no cover - cert_errors = tuple() - cert_errors_bases = ( - ClientSSLError, - ValueError, - ) - - ssl_errors = tuple() - ssl_error_bases = (ClientSSLError,) - - -class ClientConnectorSSLError(*ssl_error_bases): # type: ignore[misc] - """Response ssl error.""" - - -class ClientConnectorCertificateError(*cert_errors_bases): # type: ignore[misc] - """Response certificate error.""" - - def __init__( - self, connection_key: ConnectionKey, certificate_error: Exception - ) -> None: - self._conn_key = connection_key - self._certificate_error = certificate_error - self.args = (connection_key, certificate_error) - - @property - def certificate_error(self) -> Exception: - return self._certificate_error - - @property - def host(self) -> str: - return self._conn_key.host - - @property - def port(self) -> Optional[int]: - return self._conn_key.port - - @property - def ssl(self) -> bool: - return self._conn_key.is_ssl - - def __str__(self) -> str: - return ( - "Cannot connect to host {0.host}:{0.port} ssl:{0.ssl} " - "[{0.certificate_error.__class__.__name__}: " - "{0.certificate_error.args}]".format(self) - ) diff --git a/.venv/Lib/site-packages/aiohttp/client_proto.py b/.venv/Lib/site-packages/aiohttp/client_proto.py deleted file mode 100644 index f36863b..0000000 --- a/.venv/Lib/site-packages/aiohttp/client_proto.py +++ /dev/null @@ -1,251 +0,0 @@ -import asyncio -from contextlib import suppress -from typing import Any, Optional, Tuple - -from .base_protocol import BaseProtocol -from .client_exceptions import ( - ClientOSError, - ClientPayloadError, - ServerDisconnectedError, - ServerTimeoutError, -) -from .helpers import BaseTimerContext -from .http import HttpResponseParser, RawResponseMessage -from .streams import EMPTY_PAYLOAD, DataQueue, StreamReader - - -class ResponseHandler(BaseProtocol, DataQueue[Tuple[RawResponseMessage, StreamReader]]): - """Helper class to adapt between Protocol and StreamReader.""" - - def __init__(self, loop: asyncio.AbstractEventLoop) -> None: - BaseProtocol.__init__(self, loop=loop) - DataQueue.__init__(self, loop) - - self._should_close = False - - self._payload: Optional[StreamReader] = None - self._skip_payload = False - self._payload_parser = None - - self._timer = None - - self._tail = b"" - self._upgraded = False - self._parser = None # type: Optional[HttpResponseParser] - - self._read_timeout = None # type: Optional[float] - self._read_timeout_handle = None # type: Optional[asyncio.TimerHandle] - - @property - def upgraded(self) -> bool: - return self._upgraded - - @property - def should_close(self) -> bool: - if self._payload is not None and not self._payload.is_eof() or self._upgraded: - return True - - return ( - self._should_close - or self._upgraded - or self.exception() is not None - or self._payload_parser is not None - or len(self) > 0 - or bool(self._tail) - ) - - def force_close(self) -> None: - self._should_close = True - - def close(self) -> None: - transport = self.transport - if transport is not None: - transport.close() - self.transport = None - self._payload = None - self._drop_timeout() - - def is_connected(self) -> bool: - return self.transport is not None and not self.transport.is_closing() - - def connection_lost(self, exc: Optional[BaseException]) -> None: - self._drop_timeout() - - if self._payload_parser is not None: - with suppress(Exception): - self._payload_parser.feed_eof() - - uncompleted = None - if self._parser is not None: - try: - uncompleted = self._parser.feed_eof() - except Exception: - if self._payload is not None: - self._payload.set_exception( - ClientPayloadError("Response payload is not completed") - ) - - if not self.is_eof(): - if isinstance(exc, OSError): - exc = ClientOSError(*exc.args) - if exc is None: - exc = ServerDisconnectedError(uncompleted) - # assigns self._should_close to True as side effect, - # we do it anyway below - self.set_exception(exc) - - self._should_close = True - self._parser = None - self._payload = None - self._payload_parser = None - self._reading_paused = False - - super().connection_lost(exc) - - def eof_received(self) -> None: - # should call parser.feed_eof() most likely - self._drop_timeout() - - def pause_reading(self) -> None: - super().pause_reading() - self._drop_timeout() - - def resume_reading(self) -> None: - super().resume_reading() - self._reschedule_timeout() - - def set_exception(self, exc: BaseException) -> None: - self._should_close = True - self._drop_timeout() - super().set_exception(exc) - - def set_parser(self, parser: Any, payload: Any) -> None: - # TODO: actual types are: - # parser: WebSocketReader - # payload: FlowControlDataQueue - # but they are not generi enough - # Need an ABC for both types - self._payload = payload - self._payload_parser = parser - - self._drop_timeout() - - if self._tail: - data, self._tail = self._tail, b"" - self.data_received(data) - - def set_response_params( - self, - *, - timer: Optional[BaseTimerContext] = None, - skip_payload: bool = False, - read_until_eof: bool = False, - auto_decompress: bool = True, - read_timeout: Optional[float] = None, - read_bufsize: int = 2 ** 16, - ) -> None: - self._skip_payload = skip_payload - - self._read_timeout = read_timeout - self._reschedule_timeout() - - self._parser = HttpResponseParser( - self, - self._loop, - read_bufsize, - timer=timer, - payload_exception=ClientPayloadError, - response_with_body=not skip_payload, - read_until_eof=read_until_eof, - auto_decompress=auto_decompress, - ) - - if self._tail: - data, self._tail = self._tail, b"" - self.data_received(data) - - def _drop_timeout(self) -> None: - if self._read_timeout_handle is not None: - self._read_timeout_handle.cancel() - self._read_timeout_handle = None - - def _reschedule_timeout(self) -> None: - timeout = self._read_timeout - if self._read_timeout_handle is not None: - self._read_timeout_handle.cancel() - - if timeout: - self._read_timeout_handle = self._loop.call_later( - timeout, self._on_read_timeout - ) - else: - self._read_timeout_handle = None - - def _on_read_timeout(self) -> None: - exc = ServerTimeoutError("Timeout on reading data from socket") - self.set_exception(exc) - if self._payload is not None: - self._payload.set_exception(exc) - - def data_received(self, data: bytes) -> None: - self._reschedule_timeout() - - if not data: - return - - # custom payload parser - if self._payload_parser is not None: - eof, tail = self._payload_parser.feed_data(data) - if eof: - self._payload = None - self._payload_parser = None - - if tail: - self.data_received(tail) - return - else: - if self._upgraded or self._parser is None: - # i.e. websocket connection, websocket parser is not set yet - self._tail += data - else: - # parse http messages - try: - messages, upgraded, tail = self._parser.feed_data(data) - except BaseException as exc: - if self.transport is not None: - # connection.release() could be called BEFORE - # data_received(), the transport is already - # closed in this case - self.transport.close() - # should_close is True after the call - self.set_exception(exc) - return - - self._upgraded = upgraded - - payload: Optional[StreamReader] = None - for message, payload in messages: - if message.should_close: - self._should_close = True - - self._payload = payload - - if self._skip_payload or message.code in (204, 304): - self.feed_data((message, EMPTY_PAYLOAD), 0) - else: - self.feed_data((message, payload), 0) - if payload is not None: - # new message(s) was processed - # register timeout handler unsubscribing - # either on end-of-stream or immediately for - # EMPTY_PAYLOAD - if payload is not EMPTY_PAYLOAD: - payload.on_eof(self._drop_timeout) - else: - self._drop_timeout() - - if tail: - if upgraded: - self.data_received(tail) - else: - self._tail = tail diff --git a/.venv/Lib/site-packages/aiohttp/client_reqrep.py b/.venv/Lib/site-packages/aiohttp/client_reqrep.py deleted file mode 100644 index 3430025..0000000 --- a/.venv/Lib/site-packages/aiohttp/client_reqrep.py +++ /dev/null @@ -1,1133 +0,0 @@ -import asyncio -import codecs -import functools -import io -import re -import sys -import traceback -import warnings -from hashlib import md5, sha1, sha256 -from http.cookies import CookieError, Morsel, SimpleCookie -from types import MappingProxyType, TracebackType -from typing import ( - TYPE_CHECKING, - Any, - Dict, - Iterable, - List, - Mapping, - Optional, - Tuple, - Type, - Union, - cast, -) - -import attr -from multidict import CIMultiDict, CIMultiDictProxy, MultiDict, MultiDictProxy -from yarl import URL - -from . import hdrs, helpers, http, multipart, payload -from .abc import AbstractStreamWriter -from .client_exceptions import ( - ClientConnectionError, - ClientOSError, - ClientResponseError, - ContentTypeError, - InvalidURL, - ServerFingerprintMismatch, -) -from .formdata import FormData -from .helpers import ( - PY_36, - BaseTimerContext, - BasicAuth, - HeadersMixin, - TimerNoop, - noop, - reify, - set_result, -) -from .http import SERVER_SOFTWARE, HttpVersion10, HttpVersion11, StreamWriter -from .log import client_logger -from .streams import StreamReader -from .typedefs import ( - DEFAULT_JSON_DECODER, - JSONDecoder, - LooseCookies, - LooseHeaders, - RawHeaders, -) - -try: - import ssl - from ssl import SSLContext -except ImportError: # pragma: no cover - ssl = None # type: ignore[assignment] - SSLContext = object # type: ignore[misc,assignment] - -try: - import cchardet as chardet -except ImportError: # pragma: no cover - import charset_normalizer as chardet # type: ignore[no-redef] - - -__all__ = ("ClientRequest", "ClientResponse", "RequestInfo", "Fingerprint") - - -if TYPE_CHECKING: # pragma: no cover - from .client import ClientSession - from .connector import Connection - from .tracing import Trace - - -json_re = re.compile(r"^application/(?:[\w.+-]+?\+)?json") - - -@attr.s(auto_attribs=True, frozen=True, slots=True) -class ContentDisposition: - type: Optional[str] - parameters: "MappingProxyType[str, str]" - filename: Optional[str] - - -@attr.s(auto_attribs=True, frozen=True, slots=True) -class RequestInfo: - url: URL - method: str - headers: "CIMultiDictProxy[str]" - real_url: URL = attr.ib() - - @real_url.default - def real_url_default(self) -> URL: - return self.url - - -class Fingerprint: - HASHFUNC_BY_DIGESTLEN = { - 16: md5, - 20: sha1, - 32: sha256, - } - - def __init__(self, fingerprint: bytes) -> None: - digestlen = len(fingerprint) - hashfunc = self.HASHFUNC_BY_DIGESTLEN.get(digestlen) - if not hashfunc: - raise ValueError("fingerprint has invalid length") - elif hashfunc is md5 or hashfunc is sha1: - raise ValueError( - "md5 and sha1 are insecure and " "not supported. Use sha256." - ) - self._hashfunc = hashfunc - self._fingerprint = fingerprint - - @property - def fingerprint(self) -> bytes: - return self._fingerprint - - def check(self, transport: asyncio.Transport) -> None: - if not transport.get_extra_info("sslcontext"): - return - sslobj = transport.get_extra_info("ssl_object") - cert = sslobj.getpeercert(binary_form=True) - got = self._hashfunc(cert).digest() - if got != self._fingerprint: - host, port, *_ = transport.get_extra_info("peername") - raise ServerFingerprintMismatch(self._fingerprint, got, host, port) - - -if ssl is not None: - SSL_ALLOWED_TYPES = (ssl.SSLContext, bool, Fingerprint, type(None)) -else: # pragma: no cover - SSL_ALLOWED_TYPES = type(None) - - -def _merge_ssl_params( - ssl: Union["SSLContext", bool, Fingerprint, None], - verify_ssl: Optional[bool], - ssl_context: Optional["SSLContext"], - fingerprint: Optional[bytes], -) -> Union["SSLContext", bool, Fingerprint, None]: - if verify_ssl is not None and not verify_ssl: - warnings.warn( - "verify_ssl is deprecated, use ssl=False instead", - DeprecationWarning, - stacklevel=3, - ) - if ssl is not None: - raise ValueError( - "verify_ssl, ssl_context, fingerprint and ssl " - "parameters are mutually exclusive" - ) - else: - ssl = False - if ssl_context is not None: - warnings.warn( - "ssl_context is deprecated, use ssl=context instead", - DeprecationWarning, - stacklevel=3, - ) - if ssl is not None: - raise ValueError( - "verify_ssl, ssl_context, fingerprint and ssl " - "parameters are mutually exclusive" - ) - else: - ssl = ssl_context - if fingerprint is not None: - warnings.warn( - "fingerprint is deprecated, " "use ssl=Fingerprint(fingerprint) instead", - DeprecationWarning, - stacklevel=3, - ) - if ssl is not None: - raise ValueError( - "verify_ssl, ssl_context, fingerprint and ssl " - "parameters are mutually exclusive" - ) - else: - ssl = Fingerprint(fingerprint) - if not isinstance(ssl, SSL_ALLOWED_TYPES): - raise TypeError( - "ssl should be SSLContext, bool, Fingerprint or None, " - "got {!r} instead.".format(ssl) - ) - return ssl - - -@attr.s(auto_attribs=True, slots=True, frozen=True) -class ConnectionKey: - # the key should contain an information about used proxy / TLS - # to prevent reusing wrong connections from a pool - host: str - port: Optional[int] - is_ssl: bool - ssl: Union[SSLContext, None, bool, Fingerprint] - proxy: Optional[URL] - proxy_auth: Optional[BasicAuth] - proxy_headers_hash: Optional[int] # hash(CIMultiDict) - - -def _is_expected_content_type( - response_content_type: str, expected_content_type: str -) -> bool: - if expected_content_type == "application/json": - return json_re.match(response_content_type) is not None - return expected_content_type in response_content_type - - -class ClientRequest: - GET_METHODS = { - hdrs.METH_GET, - hdrs.METH_HEAD, - hdrs.METH_OPTIONS, - hdrs.METH_TRACE, - } - POST_METHODS = {hdrs.METH_PATCH, hdrs.METH_POST, hdrs.METH_PUT} - ALL_METHODS = GET_METHODS.union(POST_METHODS).union({hdrs.METH_DELETE}) - - DEFAULT_HEADERS = { - hdrs.ACCEPT: "*/*", - hdrs.ACCEPT_ENCODING: "gzip, deflate", - } - - body = b"" - auth = None - response = None - - _writer = None # async task for streaming data - _continue = None # waiter future for '100 Continue' response - - # N.B. - # Adding __del__ method with self._writer closing doesn't make sense - # because _writer is instance method, thus it keeps a reference to self. - # Until writer has finished finalizer will not be called. - - def __init__( - self, - method: str, - url: URL, - *, - params: Optional[Mapping[str, str]] = None, - headers: Optional[LooseHeaders] = None, - skip_auto_headers: Iterable[str] = frozenset(), - data: Any = None, - cookies: Optional[LooseCookies] = None, - auth: Optional[BasicAuth] = None, - version: http.HttpVersion = http.HttpVersion11, - compress: Optional[str] = None, - chunked: Optional[bool] = None, - expect100: bool = False, - loop: Optional[asyncio.AbstractEventLoop] = None, - response_class: Optional[Type["ClientResponse"]] = None, - proxy: Optional[URL] = None, - proxy_auth: Optional[BasicAuth] = None, - timer: Optional[BaseTimerContext] = None, - session: Optional["ClientSession"] = None, - ssl: Union[SSLContext, bool, Fingerprint, None] = None, - proxy_headers: Optional[LooseHeaders] = None, - traces: Optional[List["Trace"]] = None, - ): - - if loop is None: - loop = asyncio.get_event_loop() - - assert isinstance(url, URL), url - assert isinstance(proxy, (URL, type(None))), proxy - # FIXME: session is None in tests only, need to fix tests - # assert session is not None - self._session = cast("ClientSession", session) - if params: - q = MultiDict(url.query) - url2 = url.with_query(params) - q.extend(url2.query) - url = url.with_query(q) - self.original_url = url - self.url = url.with_fragment(None) - self.method = method.upper() - self.chunked = chunked - self.compress = compress - self.loop = loop - self.length = None - if response_class is None: - real_response_class = ClientResponse - else: - real_response_class = response_class - self.response_class = real_response_class # type: Type[ClientResponse] - self._timer = timer if timer is not None else TimerNoop() - self._ssl = ssl - - if loop.get_debug(): - self._source_traceback = traceback.extract_stack(sys._getframe(1)) - - self.update_version(version) - self.update_host(url) - self.update_headers(headers) - self.update_auto_headers(skip_auto_headers) - self.update_cookies(cookies) - self.update_content_encoding(data) - self.update_auth(auth) - self.update_proxy(proxy, proxy_auth, proxy_headers) - - self.update_body_from_data(data) - if data is not None or self.method not in self.GET_METHODS: - self.update_transfer_encoding() - self.update_expect_continue(expect100) - if traces is None: - traces = [] - self._traces = traces - - def is_ssl(self) -> bool: - return self.url.scheme in ("https", "wss") - - @property - def ssl(self) -> Union["SSLContext", None, bool, Fingerprint]: - return self._ssl - - @property - def connection_key(self) -> ConnectionKey: - proxy_headers = self.proxy_headers - if proxy_headers: - h = hash( - tuple((k, v) for k, v in proxy_headers.items()) - ) # type: Optional[int] - else: - h = None - return ConnectionKey( - self.host, - self.port, - self.is_ssl(), - self.ssl, - self.proxy, - self.proxy_auth, - h, - ) - - @property - def host(self) -> str: - ret = self.url.raw_host - assert ret is not None - return ret - - @property - def port(self) -> Optional[int]: - return self.url.port - - @property - def request_info(self) -> RequestInfo: - headers = CIMultiDictProxy(self.headers) # type: CIMultiDictProxy[str] - return RequestInfo(self.url, self.method, headers, self.original_url) - - def update_host(self, url: URL) -> None: - """Update destination host, port and connection type (ssl).""" - # get host/port - if not url.raw_host: - raise InvalidURL(url) - - # basic auth info - username, password = url.user, url.password - if username: - self.auth = helpers.BasicAuth(username, password or "") - - def update_version(self, version: Union[http.HttpVersion, str]) -> None: - """Convert request version to two elements tuple. - - parser HTTP version '1.1' => (1, 1) - """ - if isinstance(version, str): - v = [part.strip() for part in version.split(".", 1)] - try: - version = http.HttpVersion(int(v[0]), int(v[1])) - except ValueError: - raise ValueError( - f"Can not parse http version number: {version}" - ) from None - self.version = version - - def update_headers(self, headers: Optional[LooseHeaders]) -> None: - """Update request headers.""" - self.headers = CIMultiDict() # type: CIMultiDict[str] - - # add host - netloc = cast(str, self.url.raw_host) - if helpers.is_ipv6_address(netloc): - netloc = f"[{netloc}]" - if self.url.port is not None and not self.url.is_default_port(): - netloc += ":" + str(self.url.port) - self.headers[hdrs.HOST] = netloc - - if headers: - if isinstance(headers, (dict, MultiDictProxy, MultiDict)): - headers = headers.items() # type: ignore[assignment] - - for key, value in headers: # type: ignore[misc] - # A special case for Host header - if key.lower() == "host": - self.headers[key] = value - else: - self.headers.add(key, value) - - def update_auto_headers(self, skip_auto_headers: Iterable[str]) -> None: - self.skip_auto_headers = CIMultiDict( - (hdr, None) for hdr in sorted(skip_auto_headers) - ) - used_headers = self.headers.copy() - used_headers.extend(self.skip_auto_headers) # type: ignore[arg-type] - - for hdr, val in self.DEFAULT_HEADERS.items(): - if hdr not in used_headers: - self.headers.add(hdr, val) - - if hdrs.USER_AGENT not in used_headers: - self.headers[hdrs.USER_AGENT] = SERVER_SOFTWARE - - def update_cookies(self, cookies: Optional[LooseCookies]) -> None: - """Update request cookies header.""" - if not cookies: - return - - c = SimpleCookie() # type: SimpleCookie[str] - if hdrs.COOKIE in self.headers: - c.load(self.headers.get(hdrs.COOKIE, "")) - del self.headers[hdrs.COOKIE] - - if isinstance(cookies, Mapping): - iter_cookies = cookies.items() - else: - iter_cookies = cookies # type: ignore[assignment] - for name, value in iter_cookies: - if isinstance(value, Morsel): - # Preserve coded_value - mrsl_val = value.get(value.key, Morsel()) - mrsl_val.set(value.key, value.value, value.coded_value) - c[name] = mrsl_val - else: - c[name] = value # type: ignore[assignment] - - self.headers[hdrs.COOKIE] = c.output(header="", sep=";").strip() - - def update_content_encoding(self, data: Any) -> None: - """Set request content encoding.""" - if data is None: - return - - enc = self.headers.get(hdrs.CONTENT_ENCODING, "").lower() - if enc: - if self.compress: - raise ValueError( - "compress can not be set " "if Content-Encoding header is set" - ) - elif self.compress: - if not isinstance(self.compress, str): - self.compress = "deflate" - self.headers[hdrs.CONTENT_ENCODING] = self.compress - self.chunked = True # enable chunked, no need to deal with length - - def update_transfer_encoding(self) -> None: - """Analyze transfer-encoding header.""" - te = self.headers.get(hdrs.TRANSFER_ENCODING, "").lower() - - if "chunked" in te: - if self.chunked: - raise ValueError( - "chunked can not be set " - 'if "Transfer-Encoding: chunked" header is set' - ) - - elif self.chunked: - if hdrs.CONTENT_LENGTH in self.headers: - raise ValueError( - "chunked can not be set " "if Content-Length header is set" - ) - - self.headers[hdrs.TRANSFER_ENCODING] = "chunked" - else: - if hdrs.CONTENT_LENGTH not in self.headers: - self.headers[hdrs.CONTENT_LENGTH] = str(len(self.body)) - - def update_auth(self, auth: Optional[BasicAuth]) -> None: - """Set basic auth.""" - if auth is None: - auth = self.auth - if auth is None: - return - - if not isinstance(auth, helpers.BasicAuth): - raise TypeError("BasicAuth() tuple is required instead") - - self.headers[hdrs.AUTHORIZATION] = auth.encode() - - def update_body_from_data(self, body: Any) -> None: - if body is None: - return - - # FormData - if isinstance(body, FormData): - body = body() - - try: - body = payload.PAYLOAD_REGISTRY.get(body, disposition=None) - except payload.LookupError: - body = FormData(body)() - - self.body = body - - # enable chunked encoding if needed - if not self.chunked: - if hdrs.CONTENT_LENGTH not in self.headers: - size = body.size - if size is None: - self.chunked = True - else: - if hdrs.CONTENT_LENGTH not in self.headers: - self.headers[hdrs.CONTENT_LENGTH] = str(size) - - # copy payload headers - assert body.headers - for (key, value) in body.headers.items(): - if key in self.headers: - continue - if key in self.skip_auto_headers: - continue - self.headers[key] = value - - def update_expect_continue(self, expect: bool = False) -> None: - if expect: - self.headers[hdrs.EXPECT] = "100-continue" - elif self.headers.get(hdrs.EXPECT, "").lower() == "100-continue": - expect = True - - if expect: - self._continue = self.loop.create_future() - - def update_proxy( - self, - proxy: Optional[URL], - proxy_auth: Optional[BasicAuth], - proxy_headers: Optional[LooseHeaders], - ) -> None: - if proxy_auth and not isinstance(proxy_auth, helpers.BasicAuth): - raise ValueError("proxy_auth must be None or BasicAuth() tuple") - self.proxy = proxy - self.proxy_auth = proxy_auth - self.proxy_headers = proxy_headers - - def keep_alive(self) -> bool: - if self.version < HttpVersion10: - # keep alive not supported at all - return False - if self.version == HttpVersion10: - if self.headers.get(hdrs.CONNECTION) == "keep-alive": - return True - else: # no headers means we close for Http 1.0 - return False - elif self.headers.get(hdrs.CONNECTION) == "close": - return False - - return True - - async def write_bytes( - self, writer: AbstractStreamWriter, conn: "Connection" - ) -> None: - """Support coroutines that yields bytes objects.""" - # 100 response - if self._continue is not None: - await writer.drain() - await self._continue - - protocol = conn.protocol - assert protocol is not None - try: - if isinstance(self.body, payload.Payload): - await self.body.write(writer) - else: - if isinstance(self.body, (bytes, bytearray)): - self.body = (self.body,) # type: ignore[assignment] - - for chunk in self.body: - await writer.write(chunk) # type: ignore[arg-type] - - await writer.write_eof() - except OSError as exc: - new_exc = ClientOSError( - exc.errno, "Can not write request body for %s" % self.url - ) - new_exc.__context__ = exc - new_exc.__cause__ = exc - protocol.set_exception(new_exc) - except asyncio.CancelledError as exc: - if not conn.closed: - protocol.set_exception(exc) - except Exception as exc: - protocol.set_exception(exc) - finally: - self._writer = None - - async def send(self, conn: "Connection") -> "ClientResponse": - # Specify request target: - # - CONNECT request must send authority form URI - # - not CONNECT proxy must send absolute form URI - # - most common is origin form URI - if self.method == hdrs.METH_CONNECT: - connect_host = self.url.raw_host - assert connect_host is not None - if helpers.is_ipv6_address(connect_host): - connect_host = f"[{connect_host}]" - path = f"{connect_host}:{self.url.port}" - elif self.proxy and not self.is_ssl(): - path = str(self.url) - else: - path = self.url.raw_path - if self.url.raw_query_string: - path += "?" + self.url.raw_query_string - - protocol = conn.protocol - assert protocol is not None - writer = StreamWriter( - protocol, - self.loop, - on_chunk_sent=functools.partial( - self._on_chunk_request_sent, self.method, self.url - ), - on_headers_sent=functools.partial( - self._on_headers_request_sent, self.method, self.url - ), - ) - - if self.compress: - writer.enable_compression(self.compress) - - if self.chunked is not None: - writer.enable_chunking() - - # set default content-type - if ( - self.method in self.POST_METHODS - and hdrs.CONTENT_TYPE not in self.skip_auto_headers - and hdrs.CONTENT_TYPE not in self.headers - ): - self.headers[hdrs.CONTENT_TYPE] = "application/octet-stream" - - # set the connection header - connection = self.headers.get(hdrs.CONNECTION) - if not connection: - if self.keep_alive(): - if self.version == HttpVersion10: - connection = "keep-alive" - else: - if self.version == HttpVersion11: - connection = "close" - - if connection is not None: - self.headers[hdrs.CONNECTION] = connection - - # status + headers - status_line = "{0} {1} HTTP/{2[0]}.{2[1]}".format( - self.method, path, self.version - ) - await writer.write_headers(status_line, self.headers) - - self._writer = self.loop.create_task(self.write_bytes(writer, conn)) - - response_class = self.response_class - assert response_class is not None - self.response = response_class( - self.method, - self.original_url, - writer=self._writer, - continue100=self._continue, - timer=self._timer, - request_info=self.request_info, - traces=self._traces, - loop=self.loop, - session=self._session, - ) - return self.response - - async def close(self) -> None: - if self._writer is not None: - try: - await self._writer - finally: - self._writer = None - - def terminate(self) -> None: - if self._writer is not None: - if not self.loop.is_closed(): - self._writer.cancel() - self._writer = None - - async def _on_chunk_request_sent(self, method: str, url: URL, chunk: bytes) -> None: - for trace in self._traces: - await trace.send_request_chunk_sent(method, url, chunk) - - async def _on_headers_request_sent( - self, method: str, url: URL, headers: "CIMultiDict[str]" - ) -> None: - for trace in self._traces: - await trace.send_request_headers(method, url, headers) - - -class ClientResponse(HeadersMixin): - - # from the Status-Line of the response - version = None # HTTP-Version - status = None # type: int # Status-Code - reason = None # Reason-Phrase - - content = None # type: StreamReader # Payload stream - _headers = None # type: CIMultiDictProxy[str] # Response headers - _raw_headers = None # type: RawHeaders # Response raw headers - - _connection = None # current connection - _source_traceback = None - # setted up by ClientRequest after ClientResponse object creation - # post-init stage allows to not change ctor signature - _closed = True # to allow __del__ for non-initialized properly response - _released = False - - def __init__( - self, - method: str, - url: URL, - *, - writer: "asyncio.Task[None]", - continue100: Optional["asyncio.Future[bool]"], - timer: BaseTimerContext, - request_info: RequestInfo, - traces: List["Trace"], - loop: asyncio.AbstractEventLoop, - session: "ClientSession", - ) -> None: - assert isinstance(url, URL) - - self.method = method - self.cookies = SimpleCookie() # type: SimpleCookie[str] - - self._real_url = url - self._url = url.with_fragment(None) - self._body = None # type: Any - self._writer = writer # type: Optional[asyncio.Task[None]] - self._continue = continue100 # None by default - self._closed = True - self._history = () # type: Tuple[ClientResponse, ...] - self._request_info = request_info - self._timer = timer if timer is not None else TimerNoop() - self._cache = {} # type: Dict[str, Any] - self._traces = traces - self._loop = loop - # store a reference to session #1985 - self._session = session # type: Optional[ClientSession] - if loop.get_debug(): - self._source_traceback = traceback.extract_stack(sys._getframe(1)) - - @reify - def url(self) -> URL: - return self._url - - @reify - def url_obj(self) -> URL: - warnings.warn("Deprecated, use .url #1654", DeprecationWarning, stacklevel=2) - return self._url - - @reify - def real_url(self) -> URL: - return self._real_url - - @reify - def host(self) -> str: - assert self._url.host is not None - return self._url.host - - @reify - def headers(self) -> "CIMultiDictProxy[str]": - return self._headers - - @reify - def raw_headers(self) -> RawHeaders: - return self._raw_headers - - @reify - def request_info(self) -> RequestInfo: - return self._request_info - - @reify - def content_disposition(self) -> Optional[ContentDisposition]: - raw = self._headers.get(hdrs.CONTENT_DISPOSITION) - if raw is None: - return None - disposition_type, params_dct = multipart.parse_content_disposition(raw) - params = MappingProxyType(params_dct) - filename = multipart.content_disposition_filename(params) - return ContentDisposition(disposition_type, params, filename) - - def __del__(self, _warnings: Any = warnings) -> None: - if self._closed: - return - - if self._connection is not None: - self._connection.release() - self._cleanup_writer() - - if self._loop.get_debug(): - if PY_36: - kwargs = {"source": self} - else: - kwargs = {} - _warnings.warn(f"Unclosed response {self!r}", ResourceWarning, **kwargs) - context = {"client_response": self, "message": "Unclosed response"} - if self._source_traceback: - context["source_traceback"] = self._source_traceback - self._loop.call_exception_handler(context) - - def __repr__(self) -> str: - out = io.StringIO() - ascii_encodable_url = str(self.url) - if self.reason: - ascii_encodable_reason = self.reason.encode( - "ascii", "backslashreplace" - ).decode("ascii") - else: - ascii_encodable_reason = self.reason - print( - "".format( - ascii_encodable_url, self.status, ascii_encodable_reason - ), - file=out, - ) - print(self.headers, file=out) - return out.getvalue() - - @property - def connection(self) -> Optional["Connection"]: - return self._connection - - @reify - def history(self) -> Tuple["ClientResponse", ...]: - """A sequence of of responses, if redirects occurred.""" - return self._history - - @reify - def links(self) -> "MultiDictProxy[MultiDictProxy[Union[str, URL]]]": - links_str = ", ".join(self.headers.getall("link", [])) - - if not links_str: - return MultiDictProxy(MultiDict()) - - links = MultiDict() # type: MultiDict[MultiDictProxy[Union[str, URL]]] - - for val in re.split(r",(?=\s*<)", links_str): - match = re.match(r"\s*<(.*)>(.*)", val) - if match is None: # pragma: no cover - # the check exists to suppress mypy error - continue - url, params_str = match.groups() - params = params_str.split(";")[1:] - - link = MultiDict() # type: MultiDict[Union[str, URL]] - - for param in params: - match = re.match(r"^\s*(\S*)\s*=\s*(['\"]?)(.*?)(\2)\s*$", param, re.M) - if match is None: # pragma: no cover - # the check exists to suppress mypy error - continue - key, _, value, _ = match.groups() - - link.add(key, value) - - key = link.get("rel", url) # type: ignore[assignment] - - link.add("url", self.url.join(URL(url))) - - links.add(key, MultiDictProxy(link)) - - return MultiDictProxy(links) - - async def start(self, connection: "Connection") -> "ClientResponse": - """Start response processing.""" - self._closed = False - self._protocol = connection.protocol - self._connection = connection - - with self._timer: - while True: - # read response - try: - protocol = self._protocol - message, payload = await protocol.read() # type: ignore[union-attr] - except http.HttpProcessingError as exc: - raise ClientResponseError( - self.request_info, - self.history, - status=exc.code, - message=exc.message, - headers=exc.headers, - ) from exc - - if message.code < 100 or message.code > 199 or message.code == 101: - break - - if self._continue is not None: - set_result(self._continue, True) - self._continue = None - - # payload eof handler - payload.on_eof(self._response_eof) - - # response status - self.version = message.version - self.status = message.code - self.reason = message.reason - - # headers - self._headers = message.headers # type is CIMultiDictProxy - self._raw_headers = message.raw_headers # type is Tuple[bytes, bytes] - - # payload - self.content = payload - - # cookies - for hdr in self.headers.getall(hdrs.SET_COOKIE, ()): - try: - self.cookies.load(hdr) - except CookieError as exc: - client_logger.warning("Can not load response cookies: %s", exc) - return self - - def _response_eof(self) -> None: - if self._closed: - return - - if self._connection is not None: - # websocket, protocol could be None because - # connection could be detached - if ( - self._connection.protocol is not None - and self._connection.protocol.upgraded - ): - return - - self._connection.release() - self._connection = None - - self._closed = True - self._cleanup_writer() - - @property - def closed(self) -> bool: - return self._closed - - def close(self) -> None: - if not self._released: - self._notify_content() - if self._closed: - return - - self._closed = True - if self._loop is None or self._loop.is_closed(): - return - - if self._connection is not None: - self._connection.close() - self._connection = None - self._cleanup_writer() - - def release(self) -> Any: - if not self._released: - self._notify_content() - if self._closed: - return noop() - - self._closed = True - if self._connection is not None: - self._connection.release() - self._connection = None - - self._cleanup_writer() - return noop() - - @property - def ok(self) -> bool: - """Returns ``True`` if ``status`` is less than ``400``, ``False`` if not. - - This is **not** a check for ``200 OK`` but a check that the response - status is under 400. - """ - return 400 > self.status - - def raise_for_status(self) -> None: - if not self.ok: - # reason should always be not None for a started response - assert self.reason is not None - self.release() - raise ClientResponseError( - self.request_info, - self.history, - status=self.status, - message=self.reason, - headers=self.headers, - ) - - def _cleanup_writer(self) -> None: - if self._writer is not None: - self._writer.cancel() - self._writer = None - self._session = None - - def _notify_content(self) -> None: - content = self.content - if content and content.exception() is None: - content.set_exception(ClientConnectionError("Connection closed")) - self._released = True - - async def wait_for_close(self) -> None: - if self._writer is not None: - try: - await self._writer - finally: - self._writer = None - self.release() - - async def read(self) -> bytes: - """Read response payload.""" - if self._body is None: - try: - self._body = await self.content.read() - for trace in self._traces: - await trace.send_response_chunk_received( - self.method, self.url, self._body - ) - except BaseException: - self.close() - raise - elif self._released: - raise ClientConnectionError("Connection closed") - - return self._body # type: ignore[no-any-return] - - def get_encoding(self) -> str: - ctype = self.headers.get(hdrs.CONTENT_TYPE, "").lower() - mimetype = helpers.parse_mimetype(ctype) - - encoding = mimetype.parameters.get("charset") - if encoding: - try: - codecs.lookup(encoding) - except LookupError: - encoding = None - if not encoding: - if mimetype.type == "application" and ( - mimetype.subtype == "json" or mimetype.subtype == "rdap" - ): - # RFC 7159 states that the default encoding is UTF-8. - # RFC 7483 defines application/rdap+json - encoding = "utf-8" - elif self._body is None: - raise RuntimeError( - "Cannot guess the encoding of " "a not yet read body" - ) - else: - encoding = chardet.detect(self._body)["encoding"] - if not encoding: - encoding = "utf-8" - - return encoding - - async def text(self, encoding: Optional[str] = None, errors: str = "strict") -> str: - """Read response payload and decode.""" - if self._body is None: - await self.read() - - if encoding is None: - encoding = self.get_encoding() - - return self._body.decode( # type: ignore[no-any-return,union-attr] - encoding, errors=errors - ) - - async def json( - self, - *, - encoding: Optional[str] = None, - loads: JSONDecoder = DEFAULT_JSON_DECODER, - content_type: Optional[str] = "application/json", - ) -> Any: - """Read and decodes JSON response.""" - if self._body is None: - await self.read() - - if content_type: - ctype = self.headers.get(hdrs.CONTENT_TYPE, "").lower() - if not _is_expected_content_type(ctype, content_type): - raise ContentTypeError( - self.request_info, - self.history, - message=( - "Attempt to decode JSON with " "unexpected mimetype: %s" % ctype - ), - headers=self.headers, - ) - - stripped = self._body.strip() # type: ignore[union-attr] - if not stripped: - return None - - if encoding is None: - encoding = self.get_encoding() - - return loads(stripped.decode(encoding)) - - async def __aenter__(self) -> "ClientResponse": - return self - - async def __aexit__( - self, - exc_type: Optional[Type[BaseException]], - exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType], - ) -> None: - # similar to _RequestContextManager, we do not need to check - # for exceptions, response object can close connection - # if state is broken - self.release() diff --git a/.venv/Lib/site-packages/aiohttp/client_ws.py b/.venv/Lib/site-packages/aiohttp/client_ws.py deleted file mode 100644 index 7c8121f..0000000 --- a/.venv/Lib/site-packages/aiohttp/client_ws.py +++ /dev/null @@ -1,300 +0,0 @@ -"""WebSocket client for asyncio.""" - -import asyncio -from typing import Any, Optional, cast - -import async_timeout - -from .client_exceptions import ClientError -from .client_reqrep import ClientResponse -from .helpers import call_later, set_result -from .http import ( - WS_CLOSED_MESSAGE, - WS_CLOSING_MESSAGE, - WebSocketError, - WSCloseCode, - WSMessage, - WSMsgType, -) -from .http_websocket import WebSocketWriter # WSMessage -from .streams import EofStream, FlowControlDataQueue -from .typedefs import ( - DEFAULT_JSON_DECODER, - DEFAULT_JSON_ENCODER, - JSONDecoder, - JSONEncoder, -) - - -class ClientWebSocketResponse: - def __init__( - self, - reader: "FlowControlDataQueue[WSMessage]", - writer: WebSocketWriter, - protocol: Optional[str], - response: ClientResponse, - timeout: float, - autoclose: bool, - autoping: bool, - loop: asyncio.AbstractEventLoop, - *, - receive_timeout: Optional[float] = None, - heartbeat: Optional[float] = None, - compress: int = 0, - client_notakeover: bool = False, - ) -> None: - self._response = response - self._conn = response.connection - - self._writer = writer - self._reader = reader - self._protocol = protocol - self._closed = False - self._closing = False - self._close_code = None # type: Optional[int] - self._timeout = timeout - self._receive_timeout = receive_timeout - self._autoclose = autoclose - self._autoping = autoping - self._heartbeat = heartbeat - self._heartbeat_cb: Optional[asyncio.TimerHandle] = None - if heartbeat is not None: - self._pong_heartbeat = heartbeat / 2.0 - self._pong_response_cb: Optional[asyncio.TimerHandle] = None - self._loop = loop - self._waiting = None # type: Optional[asyncio.Future[bool]] - self._exception = None # type: Optional[BaseException] - self._compress = compress - self._client_notakeover = client_notakeover - - self._reset_heartbeat() - - def _cancel_heartbeat(self) -> None: - if self._pong_response_cb is not None: - self._pong_response_cb.cancel() - self._pong_response_cb = None - - if self._heartbeat_cb is not None: - self._heartbeat_cb.cancel() - self._heartbeat_cb = None - - def _reset_heartbeat(self) -> None: - self._cancel_heartbeat() - - if self._heartbeat is not None: - self._heartbeat_cb = call_later( - self._send_heartbeat, self._heartbeat, self._loop - ) - - def _send_heartbeat(self) -> None: - if self._heartbeat is not None and not self._closed: - # fire-and-forget a task is not perfect but maybe ok for - # sending ping. Otherwise we need a long-living heartbeat - # task in the class. - self._loop.create_task(self._writer.ping()) - - if self._pong_response_cb is not None: - self._pong_response_cb.cancel() - self._pong_response_cb = call_later( - self._pong_not_received, self._pong_heartbeat, self._loop - ) - - def _pong_not_received(self) -> None: - if not self._closed: - self._closed = True - self._close_code = WSCloseCode.ABNORMAL_CLOSURE - self._exception = asyncio.TimeoutError() - self._response.close() - - @property - def closed(self) -> bool: - return self._closed - - @property - def close_code(self) -> Optional[int]: - return self._close_code - - @property - def protocol(self) -> Optional[str]: - return self._protocol - - @property - def compress(self) -> int: - return self._compress - - @property - def client_notakeover(self) -> bool: - return self._client_notakeover - - def get_extra_info(self, name: str, default: Any = None) -> Any: - """extra info from connection transport""" - conn = self._response.connection - if conn is None: - return default - transport = conn.transport - if transport is None: - return default - return transport.get_extra_info(name, default) - - def exception(self) -> Optional[BaseException]: - return self._exception - - async def ping(self, message: bytes = b"") -> None: - await self._writer.ping(message) - - async def pong(self, message: bytes = b"") -> None: - await self._writer.pong(message) - - async def send_str(self, data: str, compress: Optional[int] = None) -> None: - if not isinstance(data, str): - raise TypeError("data argument must be str (%r)" % type(data)) - await self._writer.send(data, binary=False, compress=compress) - - async def send_bytes(self, data: bytes, compress: Optional[int] = None) -> None: - if not isinstance(data, (bytes, bytearray, memoryview)): - raise TypeError("data argument must be byte-ish (%r)" % type(data)) - await self._writer.send(data, binary=True, compress=compress) - - async def send_json( - self, - data: Any, - compress: Optional[int] = None, - *, - dumps: JSONEncoder = DEFAULT_JSON_ENCODER, - ) -> None: - await self.send_str(dumps(data), compress=compress) - - async def close(self, *, code: int = WSCloseCode.OK, message: bytes = b"") -> bool: - # we need to break `receive()` cycle first, - # `close()` may be called from different task - if self._waiting is not None and not self._closed: - self._reader.feed_data(WS_CLOSING_MESSAGE, 0) - await self._waiting - - if not self._closed: - self._cancel_heartbeat() - self._closed = True - try: - await self._writer.close(code, message) - except asyncio.CancelledError: - self._close_code = WSCloseCode.ABNORMAL_CLOSURE - self._response.close() - raise - except Exception as exc: - self._close_code = WSCloseCode.ABNORMAL_CLOSURE - self._exception = exc - self._response.close() - return True - - if self._closing: - self._response.close() - return True - - while True: - try: - async with async_timeout.timeout(self._timeout): - msg = await self._reader.read() - except asyncio.CancelledError: - self._close_code = WSCloseCode.ABNORMAL_CLOSURE - self._response.close() - raise - except Exception as exc: - self._close_code = WSCloseCode.ABNORMAL_CLOSURE - self._exception = exc - self._response.close() - return True - - if msg.type == WSMsgType.CLOSE: - self._close_code = msg.data - self._response.close() - return True - else: - return False - - async def receive(self, timeout: Optional[float] = None) -> WSMessage: - while True: - if self._waiting is not None: - raise RuntimeError("Concurrent call to receive() is not allowed") - - if self._closed: - return WS_CLOSED_MESSAGE - elif self._closing: - await self.close() - return WS_CLOSED_MESSAGE - - try: - self._waiting = self._loop.create_future() - try: - async with async_timeout.timeout(timeout or self._receive_timeout): - msg = await self._reader.read() - self._reset_heartbeat() - finally: - waiter = self._waiting - self._waiting = None - set_result(waiter, True) - except (asyncio.CancelledError, asyncio.TimeoutError): - self._close_code = WSCloseCode.ABNORMAL_CLOSURE - raise - except EofStream: - self._close_code = WSCloseCode.OK - await self.close() - return WSMessage(WSMsgType.CLOSED, None, None) - except ClientError: - self._closed = True - self._close_code = WSCloseCode.ABNORMAL_CLOSURE - return WS_CLOSED_MESSAGE - except WebSocketError as exc: - self._close_code = exc.code - await self.close(code=exc.code) - return WSMessage(WSMsgType.ERROR, exc, None) - except Exception as exc: - self._exception = exc - self._closing = True - self._close_code = WSCloseCode.ABNORMAL_CLOSURE - await self.close() - return WSMessage(WSMsgType.ERROR, exc, None) - - if msg.type == WSMsgType.CLOSE: - self._closing = True - self._close_code = msg.data - if not self._closed and self._autoclose: - await self.close() - elif msg.type == WSMsgType.CLOSING: - self._closing = True - elif msg.type == WSMsgType.PING and self._autoping: - await self.pong(msg.data) - continue - elif msg.type == WSMsgType.PONG and self._autoping: - continue - - return msg - - async def receive_str(self, *, timeout: Optional[float] = None) -> str: - msg = await self.receive(timeout) - if msg.type != WSMsgType.TEXT: - raise TypeError(f"Received message {msg.type}:{msg.data!r} is not str") - return cast(str, msg.data) - - async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes: - msg = await self.receive(timeout) - if msg.type != WSMsgType.BINARY: - raise TypeError(f"Received message {msg.type}:{msg.data!r} is not bytes") - return cast(bytes, msg.data) - - async def receive_json( - self, - *, - loads: JSONDecoder = DEFAULT_JSON_DECODER, - timeout: Optional[float] = None, - ) -> Any: - data = await self.receive_str(timeout=timeout) - return loads(data) - - def __aiter__(self) -> "ClientWebSocketResponse": - return self - - async def __anext__(self) -> WSMessage: - msg = await self.receive() - if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED): - raise StopAsyncIteration - return msg diff --git a/.venv/Lib/site-packages/aiohttp/connector.py b/.venv/Lib/site-packages/aiohttp/connector.py deleted file mode 100644 index 08dc496..0000000 --- a/.venv/Lib/site-packages/aiohttp/connector.py +++ /dev/null @@ -1,1449 +0,0 @@ -import asyncio -import functools -import random -import sys -import traceback -import warnings -from collections import defaultdict, deque -from contextlib import suppress -from http.cookies import SimpleCookie -from itertools import cycle, islice -from time import monotonic -from types import TracebackType -from typing import ( - TYPE_CHECKING, - Any, - Awaitable, - Callable, - DefaultDict, - Dict, - Iterator, - List, - Optional, - Set, - Tuple, - Type, - Union, - cast, -) - -import attr - -from . import hdrs, helpers -from .abc import AbstractResolver -from .client_exceptions import ( - ClientConnectionError, - ClientConnectorCertificateError, - ClientConnectorError, - ClientConnectorSSLError, - ClientHttpProxyError, - ClientProxyConnectionError, - ServerFingerprintMismatch, - UnixClientConnectorError, - cert_errors, - ssl_errors, -) -from .client_proto import ResponseHandler -from .client_reqrep import ClientRequest, Fingerprint, _merge_ssl_params -from .helpers import ( - PY_36, - ceil_timeout, - get_running_loop, - is_ip_address, - noop, - sentinel, -) -from .http import RESPONSES -from .locks import EventResultOrError -from .resolver import DefaultResolver - -try: - import ssl - - SSLContext = ssl.SSLContext -except ImportError: # pragma: no cover - ssl = None # type: ignore[assignment] - SSLContext = object # type: ignore[misc,assignment] - - -__all__ = ("BaseConnector", "TCPConnector", "UnixConnector", "NamedPipeConnector") - - -if TYPE_CHECKING: # pragma: no cover - from .client import ClientTimeout - from .client_reqrep import ConnectionKey - from .tracing import Trace - - -class _DeprecationWaiter: - __slots__ = ("_awaitable", "_awaited") - - def __init__(self, awaitable: Awaitable[Any]) -> None: - self._awaitable = awaitable - self._awaited = False - - def __await__(self) -> Any: - self._awaited = True - return self._awaitable.__await__() - - def __del__(self) -> None: - if not self._awaited: - warnings.warn( - "Connector.close() is a coroutine, " - "please use await connector.close()", - DeprecationWarning, - ) - - -class Connection: - - _source_traceback = None - _transport = None - - def __init__( - self, - connector: "BaseConnector", - key: "ConnectionKey", - protocol: ResponseHandler, - loop: asyncio.AbstractEventLoop, - ) -> None: - self._key = key - self._connector = connector - self._loop = loop - self._protocol = protocol # type: Optional[ResponseHandler] - self._callbacks = [] # type: List[Callable[[], None]] - - if loop.get_debug(): - self._source_traceback = traceback.extract_stack(sys._getframe(1)) - - def __repr__(self) -> str: - return f"Connection<{self._key}>" - - def __del__(self, _warnings: Any = warnings) -> None: - if self._protocol is not None: - if PY_36: - kwargs = {"source": self} - else: - kwargs = {} - _warnings.warn(f"Unclosed connection {self!r}", ResourceWarning, **kwargs) - if self._loop.is_closed(): - return - - self._connector._release(self._key, self._protocol, should_close=True) - - context = {"client_connection": self, "message": "Unclosed connection"} - if self._source_traceback is not None: - context["source_traceback"] = self._source_traceback - self._loop.call_exception_handler(context) - - @property - def loop(self) -> asyncio.AbstractEventLoop: - warnings.warn( - "connector.loop property is deprecated", DeprecationWarning, stacklevel=2 - ) - return self._loop - - @property - def transport(self) -> Optional[asyncio.Transport]: - if self._protocol is None: - return None - return self._protocol.transport - - @property - def protocol(self) -> Optional[ResponseHandler]: - return self._protocol - - def add_callback(self, callback: Callable[[], None]) -> None: - if callback is not None: - self._callbacks.append(callback) - - def _notify_release(self) -> None: - callbacks, self._callbacks = self._callbacks[:], [] - - for cb in callbacks: - with suppress(Exception): - cb() - - def close(self) -> None: - self._notify_release() - - if self._protocol is not None: - self._connector._release(self._key, self._protocol, should_close=True) - self._protocol = None - - def release(self) -> None: - self._notify_release() - - if self._protocol is not None: - self._connector._release( - self._key, self._protocol, should_close=self._protocol.should_close - ) - self._protocol = None - - @property - def closed(self) -> bool: - return self._protocol is None or not self._protocol.is_connected() - - -class _TransportPlaceholder: - """placeholder for BaseConnector.connect function""" - - def close(self) -> None: - pass - - -class BaseConnector: - """Base connector class. - - keepalive_timeout - (optional) Keep-alive timeout. - force_close - Set to True to force close and do reconnect - after each request (and between redirects). - limit - The total number of simultaneous connections. - limit_per_host - Number of simultaneous connections to one host. - enable_cleanup_closed - Enables clean-up closed ssl transports. - Disabled by default. - loop - Optional event loop. - """ - - _closed = True # prevent AttributeError in __del__ if ctor was failed - _source_traceback = None - - # abort transport after 2 seconds (cleanup broken connections) - _cleanup_closed_period = 2.0 - - def __init__( - self, - *, - keepalive_timeout: Union[object, None, float] = sentinel, - force_close: bool = False, - limit: int = 100, - limit_per_host: int = 0, - enable_cleanup_closed: bool = False, - loop: Optional[asyncio.AbstractEventLoop] = None, - ) -> None: - - if force_close: - if keepalive_timeout is not None and keepalive_timeout is not sentinel: - raise ValueError( - "keepalive_timeout cannot " "be set if force_close is True" - ) - else: - if keepalive_timeout is sentinel: - keepalive_timeout = 15.0 - - loop = get_running_loop(loop) - - self._closed = False - if loop.get_debug(): - self._source_traceback = traceback.extract_stack(sys._getframe(1)) - - self._conns = ( - {} - ) # type: Dict[ConnectionKey, List[Tuple[ResponseHandler, float]]] - self._limit = limit - self._limit_per_host = limit_per_host - self._acquired = set() # type: Set[ResponseHandler] - self._acquired_per_host = defaultdict( - set - ) # type: DefaultDict[ConnectionKey, Set[ResponseHandler]] - self._keepalive_timeout = cast(float, keepalive_timeout) - self._force_close = force_close - - # {host_key: FIFO list of waiters} - self._waiters = defaultdict(deque) # type: ignore[var-annotated] - - self._loop = loop - self._factory = functools.partial(ResponseHandler, loop=loop) - - self.cookies = SimpleCookie() # type: SimpleCookie[str] - - # start keep-alive connection cleanup task - self._cleanup_handle: Optional[asyncio.TimerHandle] = None - - # start cleanup closed transports task - self._cleanup_closed_handle: Optional[asyncio.TimerHandle] = None - self._cleanup_closed_disabled = not enable_cleanup_closed - self._cleanup_closed_transports = [] # type: List[Optional[asyncio.Transport]] - self._cleanup_closed() - - def __del__(self, _warnings: Any = warnings) -> None: - if self._closed: - return - if not self._conns: - return - - conns = [repr(c) for c in self._conns.values()] - - self._close() - - if PY_36: - kwargs = {"source": self} - else: - kwargs = {} - _warnings.warn(f"Unclosed connector {self!r}", ResourceWarning, **kwargs) - context = { - "connector": self, - "connections": conns, - "message": "Unclosed connector", - } - if self._source_traceback is not None: - context["source_traceback"] = self._source_traceback - self._loop.call_exception_handler(context) - - def __enter__(self) -> "BaseConnector": - warnings.warn( - '"witn Connector():" is deprecated, ' - 'use "async with Connector():" instead', - DeprecationWarning, - ) - return self - - def __exit__(self, *exc: Any) -> None: - self.close() - - async def __aenter__(self) -> "BaseConnector": - return self - - async def __aexit__( - self, - exc_type: Optional[Type[BaseException]] = None, - exc_value: Optional[BaseException] = None, - exc_traceback: Optional[TracebackType] = None, - ) -> None: - await self.close() - - @property - def force_close(self) -> bool: - """Ultimately close connection on releasing if True.""" - return self._force_close - - @property - def limit(self) -> int: - """The total number for simultaneous connections. - - If limit is 0 the connector has no limit. - The default limit size is 100. - """ - return self._limit - - @property - def limit_per_host(self) -> int: - """The limit for simultaneous connections to the same endpoint. - - Endpoints are the same if they are have equal - (host, port, is_ssl) triple. - """ - return self._limit_per_host - - def _cleanup(self) -> None: - """Cleanup unused transports.""" - if self._cleanup_handle: - self._cleanup_handle.cancel() - # _cleanup_handle should be unset, otherwise _release() will not - # recreate it ever! - self._cleanup_handle = None - - now = self._loop.time() - timeout = self._keepalive_timeout - - if self._conns: - connections = {} - deadline = now - timeout - for key, conns in self._conns.items(): - alive = [] - for proto, use_time in conns: - if proto.is_connected(): - if use_time - deadline < 0: - transport = proto.transport - proto.close() - if key.is_ssl and not self._cleanup_closed_disabled: - self._cleanup_closed_transports.append(transport) - else: - alive.append((proto, use_time)) - else: - transport = proto.transport - proto.close() - if key.is_ssl and not self._cleanup_closed_disabled: - self._cleanup_closed_transports.append(transport) - - if alive: - connections[key] = alive - - self._conns = connections - - if self._conns: - self._cleanup_handle = helpers.weakref_handle( - self, "_cleanup", timeout, self._loop - ) - - def _drop_acquired_per_host( - self, key: "ConnectionKey", val: ResponseHandler - ) -> None: - acquired_per_host = self._acquired_per_host - if key not in acquired_per_host: - return - conns = acquired_per_host[key] - conns.remove(val) - if not conns: - del self._acquired_per_host[key] - - def _cleanup_closed(self) -> None: - """Double confirmation for transport close. - - Some broken ssl servers may leave socket open without proper close. - """ - if self._cleanup_closed_handle: - self._cleanup_closed_handle.cancel() - - for transport in self._cleanup_closed_transports: - if transport is not None: - transport.abort() - - self._cleanup_closed_transports = [] - - if not self._cleanup_closed_disabled: - self._cleanup_closed_handle = helpers.weakref_handle( - self, "_cleanup_closed", self._cleanup_closed_period, self._loop - ) - - def close(self) -> Awaitable[None]: - """Close all opened transports.""" - self._close() - return _DeprecationWaiter(noop()) - - def _close(self) -> None: - if self._closed: - return - - self._closed = True - - try: - if self._loop.is_closed(): - return - - # cancel cleanup task - if self._cleanup_handle: - self._cleanup_handle.cancel() - - # cancel cleanup close task - if self._cleanup_closed_handle: - self._cleanup_closed_handle.cancel() - - for data in self._conns.values(): - for proto, t0 in data: - proto.close() - - for proto in self._acquired: - proto.close() - - for transport in self._cleanup_closed_transports: - if transport is not None: - transport.abort() - - finally: - self._conns.clear() - self._acquired.clear() - self._waiters.clear() - self._cleanup_handle = None - self._cleanup_closed_transports.clear() - self._cleanup_closed_handle = None - - @property - def closed(self) -> bool: - """Is connector closed. - - A readonly property. - """ - return self._closed - - def _available_connections(self, key: "ConnectionKey") -> int: - """ - Return number of available connections. - - The limit, limit_per_host and the connection key are taken into account. - - If it returns less than 1 means that there are no connections - available. - """ - if self._limit: - # total calc available connections - available = self._limit - len(self._acquired) - - # check limit per host - if ( - self._limit_per_host - and available > 0 - and key in self._acquired_per_host - ): - acquired = self._acquired_per_host.get(key) - assert acquired is not None - available = self._limit_per_host - len(acquired) - - elif self._limit_per_host and key in self._acquired_per_host: - # check limit per host - acquired = self._acquired_per_host.get(key) - assert acquired is not None - available = self._limit_per_host - len(acquired) - else: - available = 1 - - return available - - async def connect( - self, req: "ClientRequest", traces: List["Trace"], timeout: "ClientTimeout" - ) -> Connection: - """Get from pool or create new connection.""" - key = req.connection_key - available = self._available_connections(key) - - # Wait if there are no available connections or if there are/were - # waiters (i.e. don't steal connection from a waiter about to wake up) - if available <= 0 or key in self._waiters: - fut = self._loop.create_future() - - # This connection will now count towards the limit. - self._waiters[key].append(fut) - - if traces: - for trace in traces: - await trace.send_connection_queued_start() - - try: - await fut - except BaseException as e: - if key in self._waiters: - # remove a waiter even if it was cancelled, normally it's - # removed when it's notified - try: - self._waiters[key].remove(fut) - except ValueError: # fut may no longer be in list - pass - - raise e - finally: - if key in self._waiters and not self._waiters[key]: - del self._waiters[key] - - if traces: - for trace in traces: - await trace.send_connection_queued_end() - - proto = self._get(key) - if proto is None: - placeholder = cast(ResponseHandler, _TransportPlaceholder()) - self._acquired.add(placeholder) - self._acquired_per_host[key].add(placeholder) - - if traces: - for trace in traces: - await trace.send_connection_create_start() - - try: - proto = await self._create_connection(req, traces, timeout) - if self._closed: - proto.close() - raise ClientConnectionError("Connector is closed.") - except BaseException: - if not self._closed: - self._acquired.remove(placeholder) - self._drop_acquired_per_host(key, placeholder) - self._release_waiter() - raise - else: - if not self._closed: - self._acquired.remove(placeholder) - self._drop_acquired_per_host(key, placeholder) - - if traces: - for trace in traces: - await trace.send_connection_create_end() - else: - if traces: - # Acquire the connection to prevent race conditions with limits - placeholder = cast(ResponseHandler, _TransportPlaceholder()) - self._acquired.add(placeholder) - self._acquired_per_host[key].add(placeholder) - for trace in traces: - await trace.send_connection_reuseconn() - self._acquired.remove(placeholder) - self._drop_acquired_per_host(key, placeholder) - - self._acquired.add(proto) - self._acquired_per_host[key].add(proto) - return Connection(self, key, proto, self._loop) - - def _get(self, key: "ConnectionKey") -> Optional[ResponseHandler]: - try: - conns = self._conns[key] - except KeyError: - return None - - t1 = self._loop.time() - while conns: - proto, t0 = conns.pop() - if proto.is_connected(): - if t1 - t0 > self._keepalive_timeout: - transport = proto.transport - proto.close() - # only for SSL transports - if key.is_ssl and not self._cleanup_closed_disabled: - self._cleanup_closed_transports.append(transport) - else: - if not conns: - # The very last connection was reclaimed: drop the key - del self._conns[key] - return proto - else: - transport = proto.transport - proto.close() - if key.is_ssl and not self._cleanup_closed_disabled: - self._cleanup_closed_transports.append(transport) - - # No more connections: drop the key - del self._conns[key] - return None - - def _release_waiter(self) -> None: - """ - Iterates over all waiters until one to be released is found. - - The one to be released is not finsihed and - belongs to a host that has available connections. - """ - if not self._waiters: - return - - # Having the dict keys ordered this avoids to iterate - # at the same order at each call. - queues = list(self._waiters.keys()) - random.shuffle(queues) - - for key in queues: - if self._available_connections(key) < 1: - continue - - waiters = self._waiters[key] - while waiters: - waiter = waiters.popleft() - if not waiter.done(): - waiter.set_result(None) - return - - def _release_acquired(self, key: "ConnectionKey", proto: ResponseHandler) -> None: - if self._closed: - # acquired connection is already released on connector closing - return - - try: - self._acquired.remove(proto) - self._drop_acquired_per_host(key, proto) - except KeyError: # pragma: no cover - # this may be result of undetermenistic order of objects - # finalization due garbage collection. - pass - else: - self._release_waiter() - - def _release( - self, - key: "ConnectionKey", - protocol: ResponseHandler, - *, - should_close: bool = False, - ) -> None: - if self._closed: - # acquired connection is already released on connector closing - return - - self._release_acquired(key, protocol) - - if self._force_close: - should_close = True - - if should_close or protocol.should_close: - transport = protocol.transport - protocol.close() - - if key.is_ssl and not self._cleanup_closed_disabled: - self._cleanup_closed_transports.append(transport) - else: - conns = self._conns.get(key) - if conns is None: - conns = self._conns[key] = [] - conns.append((protocol, self._loop.time())) - - if self._cleanup_handle is None: - self._cleanup_handle = helpers.weakref_handle( - self, "_cleanup", self._keepalive_timeout, self._loop - ) - - async def _create_connection( - self, req: "ClientRequest", traces: List["Trace"], timeout: "ClientTimeout" - ) -> ResponseHandler: - raise NotImplementedError() - - -class _DNSCacheTable: - def __init__(self, ttl: Optional[float] = None) -> None: - self._addrs_rr = ( - {} - ) # type: Dict[Tuple[str, int], Tuple[Iterator[Dict[str, Any]], int]] - self._timestamps = {} # type: Dict[Tuple[str, int], float] - self._ttl = ttl - - def __contains__(self, host: object) -> bool: - return host in self._addrs_rr - - def add(self, key: Tuple[str, int], addrs: List[Dict[str, Any]]) -> None: - self._addrs_rr[key] = (cycle(addrs), len(addrs)) - - if self._ttl: - self._timestamps[key] = monotonic() - - def remove(self, key: Tuple[str, int]) -> None: - self._addrs_rr.pop(key, None) - - if self._ttl: - self._timestamps.pop(key, None) - - def clear(self) -> None: - self._addrs_rr.clear() - self._timestamps.clear() - - def next_addrs(self, key: Tuple[str, int]) -> List[Dict[str, Any]]: - loop, length = self._addrs_rr[key] - addrs = list(islice(loop, length)) - # Consume one more element to shift internal state of `cycle` - next(loop) - return addrs - - def expired(self, key: Tuple[str, int]) -> bool: - if self._ttl is None: - return False - - return self._timestamps[key] + self._ttl < monotonic() - - -class TCPConnector(BaseConnector): - """TCP connector. - - verify_ssl - Set to True to check ssl certifications. - fingerprint - Pass the binary sha256 - digest of the expected certificate in DER format to verify - that the certificate the server presents matches. See also - https://en.wikipedia.org/wiki/Transport_Layer_Security#Certificate_pinning - resolver - Enable DNS lookups and use this - resolver - use_dns_cache - Use memory cache for DNS lookups. - ttl_dns_cache - Max seconds having cached a DNS entry, None forever. - family - socket address family - local_addr - local tuple of (host, port) to bind socket to - - keepalive_timeout - (optional) Keep-alive timeout. - force_close - Set to True to force close and do reconnect - after each request (and between redirects). - limit - The total number of simultaneous connections. - limit_per_host - Number of simultaneous connections to one host. - enable_cleanup_closed - Enables clean-up closed ssl transports. - Disabled by default. - loop - Optional event loop. - """ - - def __init__( - self, - *, - verify_ssl: bool = True, - fingerprint: Optional[bytes] = None, - use_dns_cache: bool = True, - ttl_dns_cache: Optional[int] = 10, - family: int = 0, - ssl_context: Optional[SSLContext] = None, - ssl: Union[None, bool, Fingerprint, SSLContext] = None, - local_addr: Optional[Tuple[str, int]] = None, - resolver: Optional[AbstractResolver] = None, - keepalive_timeout: Union[None, float, object] = sentinel, - force_close: bool = False, - limit: int = 100, - limit_per_host: int = 0, - enable_cleanup_closed: bool = False, - loop: Optional[asyncio.AbstractEventLoop] = None, - ): - super().__init__( - keepalive_timeout=keepalive_timeout, - force_close=force_close, - limit=limit, - limit_per_host=limit_per_host, - enable_cleanup_closed=enable_cleanup_closed, - loop=loop, - ) - - self._ssl = _merge_ssl_params(ssl, verify_ssl, ssl_context, fingerprint) - if resolver is None: - resolver = DefaultResolver(loop=self._loop) - self._resolver = resolver - - self._use_dns_cache = use_dns_cache - self._cached_hosts = _DNSCacheTable(ttl=ttl_dns_cache) - self._throttle_dns_events = ( - {} - ) # type: Dict[Tuple[str, int], EventResultOrError] - self._family = family - self._local_addr = local_addr - - def close(self) -> Awaitable[None]: - """Close all ongoing DNS calls.""" - for ev in self._throttle_dns_events.values(): - ev.cancel() - - return super().close() - - @property - def family(self) -> int: - """Socket family like AF_INET.""" - return self._family - - @property - def use_dns_cache(self) -> bool: - """True if local DNS caching is enabled.""" - return self._use_dns_cache - - def clear_dns_cache( - self, host: Optional[str] = None, port: Optional[int] = None - ) -> None: - """Remove specified host/port or clear all dns local cache.""" - if host is not None and port is not None: - self._cached_hosts.remove((host, port)) - elif host is not None or port is not None: - raise ValueError("either both host and port " "or none of them are allowed") - else: - self._cached_hosts.clear() - - async def _resolve_host( - self, host: str, port: int, traces: Optional[List["Trace"]] = None - ) -> List[Dict[str, Any]]: - if is_ip_address(host): - return [ - { - "hostname": host, - "host": host, - "port": port, - "family": self._family, - "proto": 0, - "flags": 0, - } - ] - - if not self._use_dns_cache: - - if traces: - for trace in traces: - await trace.send_dns_resolvehost_start(host) - - res = await self._resolver.resolve(host, port, family=self._family) - - if traces: - for trace in traces: - await trace.send_dns_resolvehost_end(host) - - return res - - key = (host, port) - - if (key in self._cached_hosts) and (not self._cached_hosts.expired(key)): - # get result early, before any await (#4014) - result = self._cached_hosts.next_addrs(key) - - if traces: - for trace in traces: - await trace.send_dns_cache_hit(host) - return result - - if key in self._throttle_dns_events: - # get event early, before any await (#4014) - event = self._throttle_dns_events[key] - if traces: - for trace in traces: - await trace.send_dns_cache_hit(host) - await event.wait() - else: - # update dict early, before any await (#4014) - self._throttle_dns_events[key] = EventResultOrError(self._loop) - if traces: - for trace in traces: - await trace.send_dns_cache_miss(host) - try: - - if traces: - for trace in traces: - await trace.send_dns_resolvehost_start(host) - - addrs = await self._resolver.resolve(host, port, family=self._family) - if traces: - for trace in traces: - await trace.send_dns_resolvehost_end(host) - - self._cached_hosts.add(key, addrs) - self._throttle_dns_events[key].set() - except BaseException as e: - # any DNS exception, independently of the implementation - # is set for the waiters to raise the same exception. - self._throttle_dns_events[key].set(exc=e) - raise - finally: - self._throttle_dns_events.pop(key) - - return self._cached_hosts.next_addrs(key) - - async def _create_connection( - self, req: "ClientRequest", traces: List["Trace"], timeout: "ClientTimeout" - ) -> ResponseHandler: - """Create connection. - - Has same keyword arguments as BaseEventLoop.create_connection. - """ - if req.proxy: - _, proto = await self._create_proxy_connection(req, traces, timeout) - else: - _, proto = await self._create_direct_connection(req, traces, timeout) - - return proto - - @staticmethod - @functools.lru_cache(None) - def _make_ssl_context(verified: bool) -> SSLContext: - if verified: - return ssl.create_default_context() - else: - sslcontext = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) - sslcontext.options |= ssl.OP_NO_SSLv2 - sslcontext.options |= ssl.OP_NO_SSLv3 - sslcontext.check_hostname = False - sslcontext.verify_mode = ssl.CERT_NONE - try: - sslcontext.options |= ssl.OP_NO_COMPRESSION - except AttributeError as attr_err: - warnings.warn( - "{!s}: The Python interpreter is compiled " - "against OpenSSL < 1.0.0. Ref: " - "https://docs.python.org/3/library/ssl.html" - "#ssl.OP_NO_COMPRESSION".format(attr_err), - ) - sslcontext.set_default_verify_paths() - return sslcontext - - def _get_ssl_context(self, req: "ClientRequest") -> Optional[SSLContext]: - """Logic to get the correct SSL context - - 0. if req.ssl is false, return None - - 1. if ssl_context is specified in req, use it - 2. if _ssl_context is specified in self, use it - 3. otherwise: - 1. if verify_ssl is not specified in req, use self.ssl_context - (will generate a default context according to self.verify_ssl) - 2. if verify_ssl is True in req, generate a default SSL context - 3. if verify_ssl is False in req, generate a SSL context that - won't verify - """ - if req.is_ssl(): - if ssl is None: # pragma: no cover - raise RuntimeError("SSL is not supported.") - sslcontext = req.ssl - if isinstance(sslcontext, ssl.SSLContext): - return sslcontext - if sslcontext is not None: - # not verified or fingerprinted - return self._make_ssl_context(False) - sslcontext = self._ssl - if isinstance(sslcontext, ssl.SSLContext): - return sslcontext - if sslcontext is not None: - # not verified or fingerprinted - return self._make_ssl_context(False) - return self._make_ssl_context(True) - else: - return None - - def _get_fingerprint(self, req: "ClientRequest") -> Optional["Fingerprint"]: - ret = req.ssl - if isinstance(ret, Fingerprint): - return ret - ret = self._ssl - if isinstance(ret, Fingerprint): - return ret - return None - - async def _wrap_create_connection( - self, - *args: Any, - req: "ClientRequest", - timeout: "ClientTimeout", - client_error: Type[Exception] = ClientConnectorError, - **kwargs: Any, - ) -> Tuple[asyncio.Transport, ResponseHandler]: - try: - async with ceil_timeout(timeout.sock_connect): - return await self._loop.create_connection(*args, **kwargs) # type: ignore[return-value] # noqa - except cert_errors as exc: - raise ClientConnectorCertificateError(req.connection_key, exc) from exc - except ssl_errors as exc: - raise ClientConnectorSSLError(req.connection_key, exc) from exc - except OSError as exc: - raise client_error(req.connection_key, exc) from exc - - def _fail_on_no_start_tls(self, req: "ClientRequest") -> None: - """Raise a :py:exc:`RuntimeError` on missing ``start_tls()``. - - One case is that :py:meth:`asyncio.loop.start_tls` is not yet - implemented under Python 3.6. It is necessary for TLS-in-TLS so - that it is possible to send HTTPS queries through HTTPS proxies. - - This doesn't affect regular HTTP requests, though. - """ - if not req.is_ssl(): - return - - proxy_url = req.proxy - assert proxy_url is not None - if proxy_url.scheme != "https": - return - - self._check_loop_for_start_tls() - - def _check_loop_for_start_tls(self) -> None: - try: - self._loop.start_tls - except AttributeError as attr_exc: - raise RuntimeError( - "An HTTPS request is being sent through an HTTPS proxy. " - "This needs support for TLS in TLS but it is not implemented " - "in your runtime for the stdlib asyncio.\n\n" - "Please upgrade to Python 3.7 or higher. For more details, " - "please see:\n" - "* https://bugs.python.org/issue37179\n" - "* https://github.com/python/cpython/pull/28073\n" - "* https://docs.aiohttp.org/en/stable/" - "client_advanced.html#proxy-support\n" - "* https://github.com/aio-libs/aiohttp/discussions/6044\n", - ) from attr_exc - - def _loop_supports_start_tls(self) -> bool: - try: - self._check_loop_for_start_tls() - except RuntimeError: - return False - else: - return True - - def _warn_about_tls_in_tls( - self, - underlying_transport: asyncio.Transport, - req: "ClientRequest", - ) -> None: - """Issue a warning if the requested URL has HTTPS scheme.""" - if req.request_info.url.scheme != "https": - return - - asyncio_supports_tls_in_tls = getattr( - underlying_transport, - "_start_tls_compatible", - False, - ) - - if asyncio_supports_tls_in_tls: - return - - warnings.warn( - "An HTTPS request is being sent through an HTTPS proxy. " - "This support for TLS in TLS is known to be disabled " - "in the stdlib asyncio. This is why you'll probably see " - "an error in the log below.\n\n" - "It is possible to enable it via monkeypatching under " - "Python 3.7 or higher. For more details, see:\n" - "* https://bugs.python.org/issue37179\n" - "* https://github.com/python/cpython/pull/28073\n\n" - "You can temporarily patch this as follows:\n" - "* https://docs.aiohttp.org/en/stable/client_advanced.html#proxy-support\n" - "* https://github.com/aio-libs/aiohttp/discussions/6044\n", - RuntimeWarning, - source=self, - # Why `4`? At least 3 of the calls in the stack originate - # from the methods in this class. - stacklevel=3, - ) - - async def _start_tls_connection( - self, - underlying_transport: asyncio.Transport, - req: "ClientRequest", - timeout: "ClientTimeout", - client_error: Type[Exception] = ClientConnectorError, - ) -> Tuple[asyncio.BaseTransport, ResponseHandler]: - """Wrap the raw TCP transport with TLS.""" - tls_proto = self._factory() # Create a brand new proto for TLS - - # Safety of the `cast()` call here is based on the fact that - # internally `_get_ssl_context()` only returns `None` when - # `req.is_ssl()` evaluates to `False` which is never gonna happen - # in this code path. Of course, it's rather fragile - # maintainability-wise but this is to be solved separately. - sslcontext = cast(ssl.SSLContext, self._get_ssl_context(req)) - - try: - async with ceil_timeout(timeout.sock_connect): - try: - tls_transport = await self._loop.start_tls( - underlying_transport, - tls_proto, - sslcontext, - server_hostname=req.host, - ssl_handshake_timeout=timeout.total, - ) - except BaseException: - # We need to close the underlying transport since - # `start_tls()` probably failed before it had a - # chance to do this: - underlying_transport.close() - raise - except cert_errors as exc: - raise ClientConnectorCertificateError(req.connection_key, exc) from exc - except ssl_errors as exc: - raise ClientConnectorSSLError(req.connection_key, exc) from exc - except OSError as exc: - raise client_error(req.connection_key, exc) from exc - except TypeError as type_err: - # Example cause looks like this: - # TypeError: transport is not supported by start_tls() - - raise ClientConnectionError( - "Cannot initialize a TLS-in-TLS connection to host " - f"{req.host!s}:{req.port:d} through an underlying connection " - f"to an HTTPS proxy {req.proxy!s} ssl:{req.ssl or 'default'} " - f"[{type_err!s}]" - ) from type_err - else: - tls_proto.connection_made( - tls_transport - ) # Kick the state machine of the new TLS protocol - - return tls_transport, tls_proto - - async def _create_direct_connection( - self, - req: "ClientRequest", - traces: List["Trace"], - timeout: "ClientTimeout", - *, - client_error: Type[Exception] = ClientConnectorError, - ) -> Tuple[asyncio.Transport, ResponseHandler]: - sslcontext = self._get_ssl_context(req) - fingerprint = self._get_fingerprint(req) - - host = req.url.raw_host - assert host is not None - port = req.port - assert port is not None - host_resolved = asyncio.ensure_future( - self._resolve_host(host, port, traces=traces), loop=self._loop - ) - try: - # Cancelling this lookup should not cancel the underlying lookup - # or else the cancel event will get broadcast to all the waiters - # across all connections. - hosts = await asyncio.shield(host_resolved) - except asyncio.CancelledError: - - def drop_exception(fut: "asyncio.Future[List[Dict[str, Any]]]") -> None: - with suppress(Exception, asyncio.CancelledError): - fut.result() - - host_resolved.add_done_callback(drop_exception) - raise - except OSError as exc: - # in case of proxy it is not ClientProxyConnectionError - # it is problem of resolving proxy ip itself - raise ClientConnectorError(req.connection_key, exc) from exc - - last_exc = None # type: Optional[Exception] - - for hinfo in hosts: - host = hinfo["host"] - port = hinfo["port"] - - try: - transp, proto = await self._wrap_create_connection( - self._factory, - host, - port, - timeout=timeout, - ssl=sslcontext, - family=hinfo["family"], - proto=hinfo["proto"], - flags=hinfo["flags"], - server_hostname=hinfo["hostname"] if sslcontext else None, - local_addr=self._local_addr, - req=req, - client_error=client_error, - ) - except ClientConnectorError as exc: - last_exc = exc - continue - - if req.is_ssl() and fingerprint: - try: - fingerprint.check(transp) - except ServerFingerprintMismatch as exc: - transp.close() - if not self._cleanup_closed_disabled: - self._cleanup_closed_transports.append(transp) - last_exc = exc - continue - - return transp, proto - else: - assert last_exc is not None - raise last_exc - - async def _create_proxy_connection( - self, req: "ClientRequest", traces: List["Trace"], timeout: "ClientTimeout" - ) -> Tuple[asyncio.BaseTransport, ResponseHandler]: - self._fail_on_no_start_tls(req) - runtime_has_start_tls = self._loop_supports_start_tls() - - headers = {} # type: Dict[str, str] - if req.proxy_headers is not None: - headers = req.proxy_headers # type: ignore[assignment] - headers[hdrs.HOST] = req.headers[hdrs.HOST] - - url = req.proxy - assert url is not None - proxy_req = ClientRequest( - hdrs.METH_GET, - url, - headers=headers, - auth=req.proxy_auth, - loop=self._loop, - ssl=req.ssl, - ) - - # create connection to proxy server - transport, proto = await self._create_direct_connection( - proxy_req, [], timeout, client_error=ClientProxyConnectionError - ) - - # Many HTTP proxies has buggy keepalive support. Let's not - # reuse connection but close it after processing every - # response. - proto.force_close() - - auth = proxy_req.headers.pop(hdrs.AUTHORIZATION, None) - if auth is not None: - if not req.is_ssl(): - req.headers[hdrs.PROXY_AUTHORIZATION] = auth - else: - proxy_req.headers[hdrs.PROXY_AUTHORIZATION] = auth - - if req.is_ssl(): - if runtime_has_start_tls: - self._warn_about_tls_in_tls(transport, req) - - # For HTTPS requests over HTTP proxy - # we must notify proxy to tunnel connection - # so we send CONNECT command: - # CONNECT www.python.org:443 HTTP/1.1 - # Host: www.python.org - # - # next we must do TLS handshake and so on - # to do this we must wrap raw socket into secure one - # asyncio handles this perfectly - proxy_req.method = hdrs.METH_CONNECT - proxy_req.url = req.url - key = attr.evolve( - req.connection_key, proxy=None, proxy_auth=None, proxy_headers_hash=None - ) - conn = Connection(self, key, proto, self._loop) - proxy_resp = await proxy_req.send(conn) - try: - protocol = conn._protocol - assert protocol is not None - - # read_until_eof=True will ensure the connection isn't closed - # once the response is received and processed allowing - # START_TLS to work on the connection below. - protocol.set_response_params(read_until_eof=runtime_has_start_tls) - resp = await proxy_resp.start(conn) - except BaseException: - proxy_resp.close() - conn.close() - raise - else: - conn._protocol = None - conn._transport = None - try: - if resp.status != 200: - message = resp.reason - if message is None: - message = RESPONSES[resp.status][0] - raise ClientHttpProxyError( - proxy_resp.request_info, - resp.history, - status=resp.status, - message=message, - headers=resp.headers, - ) - if not runtime_has_start_tls: - rawsock = transport.get_extra_info("socket", default=None) - if rawsock is None: - raise RuntimeError( - "Transport does not expose socket instance" - ) - # Duplicate the socket, so now we can close proxy transport - rawsock = rawsock.dup() - except BaseException: - # It shouldn't be closed in `finally` because it's fed to - # `loop.start_tls()` and the docs say not to touch it after - # passing there. - transport.close() - raise - finally: - if not runtime_has_start_tls: - transport.close() - - if not runtime_has_start_tls: - # HTTP proxy with support for upgrade to HTTPS - sslcontext = self._get_ssl_context(req) - return await self._wrap_create_connection( - self._factory, - timeout=timeout, - ssl=sslcontext, - sock=rawsock, - server_hostname=req.host, - req=req, - ) - - return await self._start_tls_connection( - # Access the old transport for the last time before it's - # closed and forgotten forever: - transport, - req=req, - timeout=timeout, - ) - finally: - proxy_resp.close() - - return transport, proto - - -class UnixConnector(BaseConnector): - """Unix socket connector. - - path - Unix socket path. - keepalive_timeout - (optional) Keep-alive timeout. - force_close - Set to True to force close and do reconnect - after each request (and between redirects). - limit - The total number of simultaneous connections. - limit_per_host - Number of simultaneous connections to one host. - loop - Optional event loop. - """ - - def __init__( - self, - path: str, - force_close: bool = False, - keepalive_timeout: Union[object, float, None] = sentinel, - limit: int = 100, - limit_per_host: int = 0, - loop: Optional[asyncio.AbstractEventLoop] = None, - ) -> None: - super().__init__( - force_close=force_close, - keepalive_timeout=keepalive_timeout, - limit=limit, - limit_per_host=limit_per_host, - loop=loop, - ) - self._path = path - - @property - def path(self) -> str: - """Path to unix socket.""" - return self._path - - async def _create_connection( - self, req: "ClientRequest", traces: List["Trace"], timeout: "ClientTimeout" - ) -> ResponseHandler: - try: - async with ceil_timeout(timeout.sock_connect): - _, proto = await self._loop.create_unix_connection( - self._factory, self._path - ) - except OSError as exc: - raise UnixClientConnectorError(self.path, req.connection_key, exc) from exc - - return cast(ResponseHandler, proto) - - -class NamedPipeConnector(BaseConnector): - """Named pipe connector. - - Only supported by the proactor event loop. - See also: https://docs.python.org/3.7/library/asyncio-eventloop.html - - path - Windows named pipe path. - keepalive_timeout - (optional) Keep-alive timeout. - force_close - Set to True to force close and do reconnect - after each request (and between redirects). - limit - The total number of simultaneous connections. - limit_per_host - Number of simultaneous connections to one host. - loop - Optional event loop. - """ - - def __init__( - self, - path: str, - force_close: bool = False, - keepalive_timeout: Union[object, float, None] = sentinel, - limit: int = 100, - limit_per_host: int = 0, - loop: Optional[asyncio.AbstractEventLoop] = None, - ) -> None: - super().__init__( - force_close=force_close, - keepalive_timeout=keepalive_timeout, - limit=limit, - limit_per_host=limit_per_host, - loop=loop, - ) - if not isinstance( - self._loop, asyncio.ProactorEventLoop # type: ignore[attr-defined] - ): - raise RuntimeError( - "Named Pipes only available in proactor " "loop under windows" - ) - self._path = path - - @property - def path(self) -> str: - """Path to the named pipe.""" - return self._path - - async def _create_connection( - self, req: "ClientRequest", traces: List["Trace"], timeout: "ClientTimeout" - ) -> ResponseHandler: - try: - async with ceil_timeout(timeout.sock_connect): - _, proto = await self._loop.create_pipe_connection( # type: ignore[attr-defined] # noqa: E501 - self._factory, self._path - ) - # the drain is required so that the connection_made is called - # and transport is set otherwise it is not set before the - # `assert conn.transport is not None` - # in client.py's _request method - await asyncio.sleep(0) - # other option is to manually set transport like - # `proto.transport = trans` - except OSError as exc: - raise ClientConnectorError(req.connection_key, exc) from exc - - return cast(ResponseHandler, proto) diff --git a/.venv/Lib/site-packages/aiohttp/cookiejar.py b/.venv/Lib/site-packages/aiohttp/cookiejar.py deleted file mode 100644 index 0a26566..0000000 --- a/.venv/Lib/site-packages/aiohttp/cookiejar.py +++ /dev/null @@ -1,413 +0,0 @@ -import asyncio -import contextlib -import datetime -import os # noqa -import pathlib -import pickle -import re -from collections import defaultdict -from http.cookies import BaseCookie, Morsel, SimpleCookie -from typing import ( # noqa - DefaultDict, - Dict, - Iterable, - Iterator, - List, - Mapping, - Optional, - Set, - Tuple, - Union, - cast, -) - -from yarl import URL - -from .abc import AbstractCookieJar, ClearCookiePredicate -from .helpers import is_ip_address, next_whole_second -from .typedefs import LooseCookies, PathLike, StrOrURL - -__all__ = ("CookieJar", "DummyCookieJar") - - -CookieItem = Union[str, "Morsel[str]"] - - -class CookieJar(AbstractCookieJar): - """Implements cookie storage adhering to RFC 6265.""" - - DATE_TOKENS_RE = re.compile( - r"[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]*" - r"(?P[\x00-\x08\x0A-\x1F\d:a-zA-Z\x7F-\xFF]+)" - ) - - DATE_HMS_TIME_RE = re.compile(r"(\d{1,2}):(\d{1,2}):(\d{1,2})") - - DATE_DAY_OF_MONTH_RE = re.compile(r"(\d{1,2})") - - DATE_MONTH_RE = re.compile( - "(jan)|(feb)|(mar)|(apr)|(may)|(jun)|(jul)|" "(aug)|(sep)|(oct)|(nov)|(dec)", - re.I, - ) - - DATE_YEAR_RE = re.compile(r"(\d{2,4})") - - MAX_TIME = datetime.datetime.max.replace(tzinfo=datetime.timezone.utc) - - MAX_32BIT_TIME = datetime.datetime.utcfromtimestamp(2 ** 31 - 1) - - def __init__( - self, - *, - unsafe: bool = False, - quote_cookie: bool = True, - treat_as_secure_origin: Union[StrOrURL, List[StrOrURL], None] = None, - loop: Optional[asyncio.AbstractEventLoop] = None, - ) -> None: - super().__init__(loop=loop) - self._cookies = defaultdict( - SimpleCookie - ) # type: DefaultDict[str, SimpleCookie[str]] - self._host_only_cookies = set() # type: Set[Tuple[str, str]] - self._unsafe = unsafe - self._quote_cookie = quote_cookie - if treat_as_secure_origin is None: - treat_as_secure_origin = [] - elif isinstance(treat_as_secure_origin, URL): - treat_as_secure_origin = [treat_as_secure_origin.origin()] - elif isinstance(treat_as_secure_origin, str): - treat_as_secure_origin = [URL(treat_as_secure_origin).origin()] - else: - treat_as_secure_origin = [ - URL(url).origin() if isinstance(url, str) else url.origin() - for url in treat_as_secure_origin - ] - self._treat_as_secure_origin = treat_as_secure_origin - self._next_expiration = next_whole_second() - self._expirations = {} # type: Dict[Tuple[str, str], datetime.datetime] - # #4515: datetime.max may not be representable on 32-bit platforms - self._max_time = self.MAX_TIME - try: - self._max_time.timestamp() - except OverflowError: - self._max_time = self.MAX_32BIT_TIME - - def save(self, file_path: PathLike) -> None: - file_path = pathlib.Path(file_path) - with file_path.open(mode="wb") as f: - pickle.dump(self._cookies, f, pickle.HIGHEST_PROTOCOL) - - def load(self, file_path: PathLike) -> None: - file_path = pathlib.Path(file_path) - with file_path.open(mode="rb") as f: - self._cookies = pickle.load(f) - - def clear(self, predicate: Optional[ClearCookiePredicate] = None) -> None: - if predicate is None: - self._next_expiration = next_whole_second() - self._cookies.clear() - self._host_only_cookies.clear() - self._expirations.clear() - return - - to_del = [] - now = datetime.datetime.now(datetime.timezone.utc) - for domain, cookie in self._cookies.items(): - for name, morsel in cookie.items(): - key = (domain, name) - if ( - key in self._expirations and self._expirations[key] <= now - ) or predicate(morsel): - to_del.append(key) - - for domain, name in to_del: - key = (domain, name) - self._host_only_cookies.discard(key) - if key in self._expirations: - del self._expirations[(domain, name)] - self._cookies[domain].pop(name, None) - - next_expiration = min(self._expirations.values(), default=self._max_time) - try: - self._next_expiration = next_expiration.replace( - microsecond=0 - ) + datetime.timedelta(seconds=1) - except OverflowError: - self._next_expiration = self._max_time - - def clear_domain(self, domain: str) -> None: - self.clear(lambda x: self._is_domain_match(domain, x["domain"])) - - def __iter__(self) -> "Iterator[Morsel[str]]": - self._do_expiration() - for val in self._cookies.values(): - yield from val.values() - - def __len__(self) -> int: - return sum(1 for i in self) - - def _do_expiration(self) -> None: - self.clear(lambda x: False) - - def _expire_cookie(self, when: datetime.datetime, domain: str, name: str) -> None: - self._next_expiration = min(self._next_expiration, when) - self._expirations[(domain, name)] = when - - def update_cookies(self, cookies: LooseCookies, response_url: URL = URL()) -> None: - """Update cookies.""" - hostname = response_url.raw_host - - if not self._unsafe and is_ip_address(hostname): - # Don't accept cookies from IPs - return - - if isinstance(cookies, Mapping): - cookies = cookies.items() - - for name, cookie in cookies: - if not isinstance(cookie, Morsel): - tmp = SimpleCookie() # type: SimpleCookie[str] - tmp[name] = cookie # type: ignore[assignment] - cookie = tmp[name] - - domain = cookie["domain"] - - # ignore domains with trailing dots - if domain.endswith("."): - domain = "" - del cookie["domain"] - - if not domain and hostname is not None: - # Set the cookie's domain to the response hostname - # and set its host-only-flag - self._host_only_cookies.add((hostname, name)) - domain = cookie["domain"] = hostname - - if domain.startswith("."): - # Remove leading dot - domain = domain[1:] - cookie["domain"] = domain - - if hostname and not self._is_domain_match(domain, hostname): - # Setting cookies for different domains is not allowed - continue - - path = cookie["path"] - if not path or not path.startswith("/"): - # Set the cookie's path to the response path - path = response_url.path - if not path.startswith("/"): - path = "/" - else: - # Cut everything from the last slash to the end - path = "/" + path[1 : path.rfind("/")] - cookie["path"] = path - - max_age = cookie["max-age"] - if max_age: - try: - delta_seconds = int(max_age) - try: - max_age_expiration = datetime.datetime.now( - datetime.timezone.utc - ) + datetime.timedelta(seconds=delta_seconds) - except OverflowError: - max_age_expiration = self._max_time - self._expire_cookie(max_age_expiration, domain, name) - except ValueError: - cookie["max-age"] = "" - - else: - expires = cookie["expires"] - if expires: - expire_time = self._parse_date(expires) - if expire_time: - self._expire_cookie(expire_time, domain, name) - else: - cookie["expires"] = "" - - self._cookies[domain][name] = cookie - - self._do_expiration() - - def filter_cookies( - self, request_url: URL = URL() - ) -> Union["BaseCookie[str]", "SimpleCookie[str]"]: - """Returns this jar's cookies filtered by their attributes.""" - self._do_expiration() - request_url = URL(request_url) - filtered: Union["SimpleCookie[str]", "BaseCookie[str]"] = ( - SimpleCookie() if self._quote_cookie else BaseCookie() - ) - hostname = request_url.raw_host or "" - request_origin = URL() - with contextlib.suppress(ValueError): - request_origin = request_url.origin() - - is_not_secure = ( - request_url.scheme not in ("https", "wss") - and request_origin not in self._treat_as_secure_origin - ) - - for cookie in self: - name = cookie.key - domain = cookie["domain"] - - # Send shared cookies - if not domain: - filtered[name] = cookie.value - continue - - if not self._unsafe and is_ip_address(hostname): - continue - - if (domain, name) in self._host_only_cookies: - if domain != hostname: - continue - elif not self._is_domain_match(domain, hostname): - continue - - if not self._is_path_match(request_url.path, cookie["path"]): - continue - - if is_not_secure and cookie["secure"]: - continue - - # It's critical we use the Morsel so the coded_value - # (based on cookie version) is preserved - mrsl_val = cast("Morsel[str]", cookie.get(cookie.key, Morsel())) - mrsl_val.set(cookie.key, cookie.value, cookie.coded_value) - filtered[name] = mrsl_val - - return filtered - - @staticmethod - def _is_domain_match(domain: str, hostname: str) -> bool: - """Implements domain matching adhering to RFC 6265.""" - if hostname == domain: - return True - - if not hostname.endswith(domain): - return False - - non_matching = hostname[: -len(domain)] - - if not non_matching.endswith("."): - return False - - return not is_ip_address(hostname) - - @staticmethod - def _is_path_match(req_path: str, cookie_path: str) -> bool: - """Implements path matching adhering to RFC 6265.""" - if not req_path.startswith("/"): - req_path = "/" - - if req_path == cookie_path: - return True - - if not req_path.startswith(cookie_path): - return False - - if cookie_path.endswith("/"): - return True - - non_matching = req_path[len(cookie_path) :] - - return non_matching.startswith("/") - - @classmethod - def _parse_date(cls, date_str: str) -> Optional[datetime.datetime]: - """Implements date string parsing adhering to RFC 6265.""" - if not date_str: - return None - - found_time = False - found_day = False - found_month = False - found_year = False - - hour = minute = second = 0 - day = 0 - month = 0 - year = 0 - - for token_match in cls.DATE_TOKENS_RE.finditer(date_str): - - token = token_match.group("token") - - if not found_time: - time_match = cls.DATE_HMS_TIME_RE.match(token) - if time_match: - found_time = True - hour, minute, second = (int(s) for s in time_match.groups()) - continue - - if not found_day: - day_match = cls.DATE_DAY_OF_MONTH_RE.match(token) - if day_match: - found_day = True - day = int(day_match.group()) - continue - - if not found_month: - month_match = cls.DATE_MONTH_RE.match(token) - if month_match: - found_month = True - assert month_match.lastindex is not None - month = month_match.lastindex - continue - - if not found_year: - year_match = cls.DATE_YEAR_RE.match(token) - if year_match: - found_year = True - year = int(year_match.group()) - - if 70 <= year <= 99: - year += 1900 - elif 0 <= year <= 69: - year += 2000 - - if False in (found_day, found_month, found_year, found_time): - return None - - if not 1 <= day <= 31: - return None - - if year < 1601 or hour > 23 or minute > 59 or second > 59: - return None - - return datetime.datetime( - year, month, day, hour, minute, second, tzinfo=datetime.timezone.utc - ) - - -class DummyCookieJar(AbstractCookieJar): - """Implements a dummy cookie storage. - - It can be used with the ClientSession when no cookie processing is needed. - - """ - - def __init__(self, *, loop: Optional[asyncio.AbstractEventLoop] = None) -> None: - super().__init__(loop=loop) - - def __iter__(self) -> "Iterator[Morsel[str]]": - while False: - yield None - - def __len__(self) -> int: - return 0 - - def clear(self, predicate: Optional[ClearCookiePredicate] = None) -> None: - pass - - def clear_domain(self, domain: str) -> None: - pass - - def update_cookies(self, cookies: LooseCookies, response_url: URL = URL()) -> None: - pass - - def filter_cookies(self, request_url: URL) -> "BaseCookie[str]": - return SimpleCookie() diff --git a/.venv/Lib/site-packages/aiohttp/formdata.py b/.venv/Lib/site-packages/aiohttp/formdata.py deleted file mode 100644 index 4857c89..0000000 --- a/.venv/Lib/site-packages/aiohttp/formdata.py +++ /dev/null @@ -1,172 +0,0 @@ -import io -from typing import Any, Iterable, List, Optional -from urllib.parse import urlencode - -from multidict import MultiDict, MultiDictProxy - -from . import hdrs, multipart, payload -from .helpers import guess_filename -from .payload import Payload - -__all__ = ("FormData",) - - -class FormData: - """Helper class for form body generation. - - Supports multipart/form-data and application/x-www-form-urlencoded. - """ - - def __init__( - self, - fields: Iterable[Any] = (), - quote_fields: bool = True, - charset: Optional[str] = None, - ) -> None: - self._writer = multipart.MultipartWriter("form-data") - self._fields = [] # type: List[Any] - self._is_multipart = False - self._is_processed = False - self._quote_fields = quote_fields - self._charset = charset - - if isinstance(fields, dict): - fields = list(fields.items()) - elif not isinstance(fields, (list, tuple)): - fields = (fields,) - self.add_fields(*fields) - - @property - def is_multipart(self) -> bool: - return self._is_multipart - - def add_field( - self, - name: str, - value: Any, - *, - content_type: Optional[str] = None, - filename: Optional[str] = None, - content_transfer_encoding: Optional[str] = None, - ) -> None: - - if isinstance(value, io.IOBase): - self._is_multipart = True - elif isinstance(value, (bytes, bytearray, memoryview)): - if filename is None and content_transfer_encoding is None: - filename = name - - type_options = MultiDict({"name": name}) # type: MultiDict[str] - if filename is not None and not isinstance(filename, str): - raise TypeError( - "filename must be an instance of str. " "Got: %s" % filename - ) - if filename is None and isinstance(value, io.IOBase): - filename = guess_filename(value, name) - if filename is not None: - type_options["filename"] = filename - self._is_multipart = True - - headers = {} - if content_type is not None: - if not isinstance(content_type, str): - raise TypeError( - "content_type must be an instance of str. " "Got: %s" % content_type - ) - headers[hdrs.CONTENT_TYPE] = content_type - self._is_multipart = True - if content_transfer_encoding is not None: - if not isinstance(content_transfer_encoding, str): - raise TypeError( - "content_transfer_encoding must be an instance" - " of str. Got: %s" % content_transfer_encoding - ) - headers[hdrs.CONTENT_TRANSFER_ENCODING] = content_transfer_encoding - self._is_multipart = True - - self._fields.append((type_options, headers, value)) - - def add_fields(self, *fields: Any) -> None: - to_add = list(fields) - - while to_add: - rec = to_add.pop(0) - - if isinstance(rec, io.IOBase): - k = guess_filename(rec, "unknown") - self.add_field(k, rec) # type: ignore[arg-type] - - elif isinstance(rec, (MultiDictProxy, MultiDict)): - to_add.extend(rec.items()) - - elif isinstance(rec, (list, tuple)) and len(rec) == 2: - k, fp = rec - self.add_field(k, fp) # type: ignore[arg-type] - - else: - raise TypeError( - "Only io.IOBase, multidict and (name, file) " - "pairs allowed, use .add_field() for passing " - "more complex parameters, got {!r}".format(rec) - ) - - def _gen_form_urlencoded(self) -> payload.BytesPayload: - # form data (x-www-form-urlencoded) - data = [] - for type_options, _, value in self._fields: - data.append((type_options["name"], value)) - - charset = self._charset if self._charset is not None else "utf-8" - - if charset == "utf-8": - content_type = "application/x-www-form-urlencoded" - else: - content_type = "application/x-www-form-urlencoded; " "charset=%s" % charset - - return payload.BytesPayload( - urlencode(data, doseq=True, encoding=charset).encode(), - content_type=content_type, - ) - - def _gen_form_data(self) -> multipart.MultipartWriter: - """Encode a list of fields using the multipart/form-data MIME format""" - if self._is_processed: - raise RuntimeError("Form data has been processed already") - for dispparams, headers, value in self._fields: - try: - if hdrs.CONTENT_TYPE in headers: - part = payload.get_payload( - value, - content_type=headers[hdrs.CONTENT_TYPE], - headers=headers, - encoding=self._charset, - ) - else: - part = payload.get_payload( - value, headers=headers, encoding=self._charset - ) - except Exception as exc: - raise TypeError( - "Can not serialize value type: %r\n " - "headers: %r\n value: %r" % (type(value), headers, value) - ) from exc - - if dispparams: - part.set_content_disposition( - "form-data", quote_fields=self._quote_fields, **dispparams - ) - # FIXME cgi.FieldStorage doesn't likes body parts with - # Content-Length which were sent via chunked transfer encoding - assert part.headers is not None - part.headers.popall(hdrs.CONTENT_LENGTH, None) - - self._writer.append_payload(part) - - self._is_processed = True - return self._writer - - def __call__(self) -> Payload: - if self._is_multipart: - return self._gen_form_data() - else: - return self._gen_form_urlencoded() diff --git a/.venv/Lib/site-packages/aiohttp/hdrs.py b/.venv/Lib/site-packages/aiohttp/hdrs.py deleted file mode 100644 index a619f25..0000000 --- a/.venv/Lib/site-packages/aiohttp/hdrs.py +++ /dev/null @@ -1,114 +0,0 @@ -"""HTTP Headers constants.""" - -# After changing the file content call ./tools/gen.py -# to regenerate the headers parser -import sys -from typing import Set - -from multidict import istr - -if sys.version_info >= (3, 8): - from typing import Final -else: - from typing_extensions import Final - -METH_ANY: Final[str] = "*" -METH_CONNECT: Final[str] = "CONNECT" -METH_HEAD: Final[str] = "HEAD" -METH_GET: Final[str] = "GET" -METH_DELETE: Final[str] = "DELETE" -METH_OPTIONS: Final[str] = "OPTIONS" -METH_PATCH: Final[str] = "PATCH" -METH_POST: Final[str] = "POST" -METH_PUT: Final[str] = "PUT" -METH_TRACE: Final[str] = "TRACE" - -METH_ALL: Final[Set[str]] = { - METH_CONNECT, - METH_HEAD, - METH_GET, - METH_DELETE, - METH_OPTIONS, - METH_PATCH, - METH_POST, - METH_PUT, - METH_TRACE, -} - -ACCEPT: Final[istr] = istr("Accept") -ACCEPT_CHARSET: Final[istr] = istr("Accept-Charset") -ACCEPT_ENCODING: Final[istr] = istr("Accept-Encoding") -ACCEPT_LANGUAGE: Final[istr] = istr("Accept-Language") -ACCEPT_RANGES: Final[istr] = istr("Accept-Ranges") -ACCESS_CONTROL_MAX_AGE: Final[istr] = istr("Access-Control-Max-Age") -ACCESS_CONTROL_ALLOW_CREDENTIALS: Final[istr] = istr("Access-Control-Allow-Credentials") -ACCESS_CONTROL_ALLOW_HEADERS: Final[istr] = istr("Access-Control-Allow-Headers") -ACCESS_CONTROL_ALLOW_METHODS: Final[istr] = istr("Access-Control-Allow-Methods") -ACCESS_CONTROL_ALLOW_ORIGIN: Final[istr] = istr("Access-Control-Allow-Origin") -ACCESS_CONTROL_EXPOSE_HEADERS: Final[istr] = istr("Access-Control-Expose-Headers") -ACCESS_CONTROL_REQUEST_HEADERS: Final[istr] = istr("Access-Control-Request-Headers") -ACCESS_CONTROL_REQUEST_METHOD: Final[istr] = istr("Access-Control-Request-Method") -AGE: Final[istr] = istr("Age") -ALLOW: Final[istr] = istr("Allow") -AUTHORIZATION: Final[istr] = istr("Authorization") -CACHE_CONTROL: Final[istr] = istr("Cache-Control") -CONNECTION: Final[istr] = istr("Connection") -CONTENT_DISPOSITION: Final[istr] = istr("Content-Disposition") -CONTENT_ENCODING: Final[istr] = istr("Content-Encoding") -CONTENT_LANGUAGE: Final[istr] = istr("Content-Language") -CONTENT_LENGTH: Final[istr] = istr("Content-Length") -CONTENT_LOCATION: Final[istr] = istr("Content-Location") -CONTENT_MD5: Final[istr] = istr("Content-MD5") -CONTENT_RANGE: Final[istr] = istr("Content-Range") -CONTENT_TRANSFER_ENCODING: Final[istr] = istr("Content-Transfer-Encoding") -CONTENT_TYPE: Final[istr] = istr("Content-Type") -COOKIE: Final[istr] = istr("Cookie") -DATE: Final[istr] = istr("Date") -DESTINATION: Final[istr] = istr("Destination") -DIGEST: Final[istr] = istr("Digest") -ETAG: Final[istr] = istr("Etag") -EXPECT: Final[istr] = istr("Expect") -EXPIRES: Final[istr] = istr("Expires") -FORWARDED: Final[istr] = istr("Forwarded") -FROM: Final[istr] = istr("From") -HOST: Final[istr] = istr("Host") -IF_MATCH: Final[istr] = istr("If-Match") -IF_MODIFIED_SINCE: Final[istr] = istr("If-Modified-Since") -IF_NONE_MATCH: Final[istr] = istr("If-None-Match") -IF_RANGE: Final[istr] = istr("If-Range") -IF_UNMODIFIED_SINCE: Final[istr] = istr("If-Unmodified-Since") -KEEP_ALIVE: Final[istr] = istr("Keep-Alive") -LAST_EVENT_ID: Final[istr] = istr("Last-Event-ID") -LAST_MODIFIED: Final[istr] = istr("Last-Modified") -LINK: Final[istr] = istr("Link") -LOCATION: Final[istr] = istr("Location") -MAX_FORWARDS: Final[istr] = istr("Max-Forwards") -ORIGIN: Final[istr] = istr("Origin") -PRAGMA: Final[istr] = istr("Pragma") -PROXY_AUTHENTICATE: Final[istr] = istr("Proxy-Authenticate") -PROXY_AUTHORIZATION: Final[istr] = istr("Proxy-Authorization") -RANGE: Final[istr] = istr("Range") -REFERER: Final[istr] = istr("Referer") -RETRY_AFTER: Final[istr] = istr("Retry-After") -SEC_WEBSOCKET_ACCEPT: Final[istr] = istr("Sec-WebSocket-Accept") -SEC_WEBSOCKET_VERSION: Final[istr] = istr("Sec-WebSocket-Version") -SEC_WEBSOCKET_PROTOCOL: Final[istr] = istr("Sec-WebSocket-Protocol") -SEC_WEBSOCKET_EXTENSIONS: Final[istr] = istr("Sec-WebSocket-Extensions") -SEC_WEBSOCKET_KEY: Final[istr] = istr("Sec-WebSocket-Key") -SEC_WEBSOCKET_KEY1: Final[istr] = istr("Sec-WebSocket-Key1") -SERVER: Final[istr] = istr("Server") -SET_COOKIE: Final[istr] = istr("Set-Cookie") -TE: Final[istr] = istr("TE") -TRAILER: Final[istr] = istr("Trailer") -TRANSFER_ENCODING: Final[istr] = istr("Transfer-Encoding") -UPGRADE: Final[istr] = istr("Upgrade") -URI: Final[istr] = istr("URI") -USER_AGENT: Final[istr] = istr("User-Agent") -VARY: Final[istr] = istr("Vary") -VIA: Final[istr] = istr("Via") -WANT_DIGEST: Final[istr] = istr("Want-Digest") -WARNING: Final[istr] = istr("Warning") -WWW_AUTHENTICATE: Final[istr] = istr("WWW-Authenticate") -X_FORWARDED_FOR: Final[istr] = istr("X-Forwarded-For") -X_FORWARDED_HOST: Final[istr] = istr("X-Forwarded-Host") -X_FORWARDED_PROTO: Final[istr] = istr("X-Forwarded-Proto") diff --git a/.venv/Lib/site-packages/aiohttp/helpers.py b/.venv/Lib/site-packages/aiohttp/helpers.py deleted file mode 100644 index 536d219..0000000 --- a/.venv/Lib/site-packages/aiohttp/helpers.py +++ /dev/null @@ -1,875 +0,0 @@ -"""Various helper functions""" - -import asyncio -import base64 -import binascii -import cgi -import datetime -import functools -import inspect -import netrc -import os -import platform -import re -import sys -import time -import warnings -import weakref -from collections import namedtuple -from contextlib import suppress -from email.utils import parsedate -from math import ceil -from pathlib import Path -from types import TracebackType -from typing import ( - Any, - Callable, - ContextManager, - Dict, - Generator, - Generic, - Iterable, - Iterator, - List, - Mapping, - Optional, - Pattern, - Set, - Tuple, - Type, - TypeVar, - Union, - cast, -) -from urllib.parse import quote -from urllib.request import getproxies, proxy_bypass - -import async_timeout -import attr -from multidict import MultiDict, MultiDictProxy -from yarl import URL - -from . import hdrs -from .log import client_logger, internal_logger -from .typedefs import PathLike, Protocol # noqa - -__all__ = ("BasicAuth", "ChainMapProxy", "ETag") - -IS_MACOS = platform.system() == "Darwin" -IS_WINDOWS = platform.system() == "Windows" - -PY_36 = sys.version_info >= (3, 6) -PY_37 = sys.version_info >= (3, 7) -PY_38 = sys.version_info >= (3, 8) -PY_310 = sys.version_info >= (3, 10) - -if sys.version_info < (3, 7): - import idna_ssl - - idna_ssl.patch_match_hostname() - - def all_tasks( - loop: Optional[asyncio.AbstractEventLoop] = None, - ) -> Set["asyncio.Task[Any]"]: - tasks = list(asyncio.Task.all_tasks(loop)) - return {t for t in tasks if not t.done()} - - -else: - all_tasks = asyncio.all_tasks - - -_T = TypeVar("_T") -_S = TypeVar("_S") - - -sentinel = object() # type: Any -NO_EXTENSIONS = bool(os.environ.get("AIOHTTP_NO_EXTENSIONS")) # type: bool - -# N.B. sys.flags.dev_mode is available on Python 3.7+, use getattr -# for compatibility with older versions -DEBUG = getattr(sys.flags, "dev_mode", False) or ( - not sys.flags.ignore_environment and bool(os.environ.get("PYTHONASYNCIODEBUG")) -) # type: bool - - -CHAR = {chr(i) for i in range(0, 128)} -CTL = {chr(i) for i in range(0, 32)} | { - chr(127), -} -SEPARATORS = { - "(", - ")", - "<", - ">", - "@", - ",", - ";", - ":", - "\\", - '"', - "/", - "[", - "]", - "?", - "=", - "{", - "}", - " ", - chr(9), -} -TOKEN = CHAR ^ CTL ^ SEPARATORS - - -class noop: - def __await__(self) -> Generator[None, None, None]: - yield - - -class BasicAuth(namedtuple("BasicAuth", ["login", "password", "encoding"])): - """Http basic authentication helper.""" - - def __new__( - cls, login: str, password: str = "", encoding: str = "latin1" - ) -> "BasicAuth": - if login is None: - raise ValueError("None is not allowed as login value") - - if password is None: - raise ValueError("None is not allowed as password value") - - if ":" in login: - raise ValueError('A ":" is not allowed in login (RFC 1945#section-11.1)') - - return super().__new__(cls, login, password, encoding) - - @classmethod - def decode(cls, auth_header: str, encoding: str = "latin1") -> "BasicAuth": - """Create a BasicAuth object from an Authorization HTTP header.""" - try: - auth_type, encoded_credentials = auth_header.split(" ", 1) - except ValueError: - raise ValueError("Could not parse authorization header.") - - if auth_type.lower() != "basic": - raise ValueError("Unknown authorization method %s" % auth_type) - - try: - decoded = base64.b64decode( - encoded_credentials.encode("ascii"), validate=True - ).decode(encoding) - except binascii.Error: - raise ValueError("Invalid base64 encoding.") - - try: - # RFC 2617 HTTP Authentication - # https://www.ietf.org/rfc/rfc2617.txt - # the colon must be present, but the username and password may be - # otherwise blank. - username, password = decoded.split(":", 1) - except ValueError: - raise ValueError("Invalid credentials.") - - return cls(username, password, encoding=encoding) - - @classmethod - def from_url(cls, url: URL, *, encoding: str = "latin1") -> Optional["BasicAuth"]: - """Create BasicAuth from url.""" - if not isinstance(url, URL): - raise TypeError("url should be yarl.URL instance") - if url.user is None: - return None - return cls(url.user, url.password or "", encoding=encoding) - - def encode(self) -> str: - """Encode credentials.""" - creds = (f"{self.login}:{self.password}").encode(self.encoding) - return "Basic %s" % base64.b64encode(creds).decode(self.encoding) - - -def strip_auth_from_url(url: URL) -> Tuple[URL, Optional[BasicAuth]]: - auth = BasicAuth.from_url(url) - if auth is None: - return url, None - else: - return url.with_user(None), auth - - -def netrc_from_env() -> Optional[netrc.netrc]: - """Load netrc from file. - - Attempt to load it from the path specified by the env-var - NETRC or in the default location in the user's home directory. - - Returns None if it couldn't be found or fails to parse. - """ - netrc_env = os.environ.get("NETRC") - - if netrc_env is not None: - netrc_path = Path(netrc_env) - else: - try: - home_dir = Path.home() - except RuntimeError as e: # pragma: no cover - # if pathlib can't resolve home, it may raise a RuntimeError - client_logger.debug( - "Could not resolve home directory when " - "trying to look for .netrc file: %s", - e, - ) - return None - - netrc_path = home_dir / ("_netrc" if IS_WINDOWS else ".netrc") - - try: - return netrc.netrc(str(netrc_path)) - except netrc.NetrcParseError as e: - client_logger.warning("Could not parse .netrc file: %s", e) - except OSError as e: - # we couldn't read the file (doesn't exist, permissions, etc.) - if netrc_env or netrc_path.is_file(): - # only warn if the environment wanted us to load it, - # or it appears like the default file does actually exist - client_logger.warning("Could not read .netrc file: %s", e) - - return None - - -@attr.s(auto_attribs=True, frozen=True, slots=True) -class ProxyInfo: - proxy: URL - proxy_auth: Optional[BasicAuth] - - -def proxies_from_env() -> Dict[str, ProxyInfo]: - proxy_urls = { - k: URL(v) - for k, v in getproxies().items() - if k in ("http", "https", "ws", "wss") - } - netrc_obj = netrc_from_env() - stripped = {k: strip_auth_from_url(v) for k, v in proxy_urls.items()} - ret = {} - for proto, val in stripped.items(): - proxy, auth = val - if proxy.scheme in ("https", "wss"): - client_logger.warning( - "%s proxies %s are not supported, ignoring", proxy.scheme.upper(), proxy - ) - continue - if netrc_obj and auth is None: - auth_from_netrc = None - if proxy.host is not None: - auth_from_netrc = netrc_obj.authenticators(proxy.host) - if auth_from_netrc is not None: - # auth_from_netrc is a (`user`, `account`, `password`) tuple, - # `user` and `account` both can be username, - # if `user` is None, use `account` - *logins, password = auth_from_netrc - login = logins[0] if logins[0] else logins[-1] - auth = BasicAuth(cast(str, login), cast(str, password)) - ret[proto] = ProxyInfo(proxy, auth) - return ret - - -def current_task( - loop: Optional[asyncio.AbstractEventLoop] = None, -) -> "Optional[asyncio.Task[Any]]": - if sys.version_info >= (3, 7): - return asyncio.current_task(loop=loop) - else: - return asyncio.Task.current_task(loop=loop) - - -def get_running_loop( - loop: Optional[asyncio.AbstractEventLoop] = None, -) -> asyncio.AbstractEventLoop: - if loop is None: - loop = asyncio.get_event_loop() - if not loop.is_running(): - warnings.warn( - "The object should be created within an async function", - DeprecationWarning, - stacklevel=3, - ) - if loop.get_debug(): - internal_logger.warning( - "The object should be created within an async function", stack_info=True - ) - return loop - - -def isasyncgenfunction(obj: Any) -> bool: - func = getattr(inspect, "isasyncgenfunction", None) - if func is not None: - return func(obj) # type: ignore[no-any-return] - else: - return False - - -def get_env_proxy_for_url(url: URL) -> Tuple[URL, Optional[BasicAuth]]: - """Get a permitted proxy for the given URL from the env.""" - if url.host is not None and proxy_bypass(url.host): - raise LookupError(f"Proxying is disallowed for `{url.host!r}`") - - proxies_in_env = proxies_from_env() - try: - proxy_info = proxies_in_env[url.scheme] - except KeyError: - raise LookupError(f"No proxies found for `{url!s}` in the env") - else: - return proxy_info.proxy, proxy_info.proxy_auth - - -@attr.s(auto_attribs=True, frozen=True, slots=True) -class MimeType: - type: str - subtype: str - suffix: str - parameters: "MultiDictProxy[str]" - - -@functools.lru_cache(maxsize=56) -def parse_mimetype(mimetype: str) -> MimeType: - """Parses a MIME type into its components. - - mimetype is a MIME type string. - - Returns a MimeType object. - - Example: - - >>> parse_mimetype('text/html; charset=utf-8') - MimeType(type='text', subtype='html', suffix='', - parameters={'charset': 'utf-8'}) - - """ - if not mimetype: - return MimeType( - type="", subtype="", suffix="", parameters=MultiDictProxy(MultiDict()) - ) - - parts = mimetype.split(";") - params = MultiDict() # type: MultiDict[str] - for item in parts[1:]: - if not item: - continue - key, value = cast( - Tuple[str, str], item.split("=", 1) if "=" in item else (item, "") - ) - params.add(key.lower().strip(), value.strip(' "')) - - fulltype = parts[0].strip().lower() - if fulltype == "*": - fulltype = "*/*" - - mtype, stype = ( - cast(Tuple[str, str], fulltype.split("/", 1)) - if "/" in fulltype - else (fulltype, "") - ) - stype, suffix = ( - cast(Tuple[str, str], stype.split("+", 1)) if "+" in stype else (stype, "") - ) - - return MimeType( - type=mtype, subtype=stype, suffix=suffix, parameters=MultiDictProxy(params) - ) - - -def guess_filename(obj: Any, default: Optional[str] = None) -> Optional[str]: - name = getattr(obj, "name", None) - if name and isinstance(name, str) and name[0] != "<" and name[-1] != ">": - return Path(name).name - return default - - -not_qtext_re = re.compile(r"[^\041\043-\133\135-\176]") -QCONTENT = {chr(i) for i in range(0x20, 0x7F)} | {"\t"} - - -def quoted_string(content: str) -> str: - """Return 7-bit content as quoted-string. - - Format content into a quoted-string as defined in RFC5322 for - Internet Message Format. Notice that this is not the 8-bit HTTP - format, but the 7-bit email format. Content must be in usascii or - a ValueError is raised. - """ - if not (QCONTENT > set(content)): - raise ValueError(f"bad content for quoted-string {content!r}") - return not_qtext_re.sub(lambda x: "\\" + x.group(0), content) - - -def content_disposition_header( - disptype: str, quote_fields: bool = True, _charset: str = "utf-8", **params: str -) -> str: - """Sets ``Content-Disposition`` header for MIME. - - This is the MIME payload Content-Disposition header from RFC 2183 - and RFC 7579 section 4.2, not the HTTP Content-Disposition from - RFC 6266. - - disptype is a disposition type: inline, attachment, form-data. - Should be valid extension token (see RFC 2183) - - quote_fields performs value quoting to 7-bit MIME headers - according to RFC 7578. Set to quote_fields to False if recipient - can take 8-bit file names and field values. - - _charset specifies the charset to use when quote_fields is True. - - params is a dict with disposition params. - """ - if not disptype or not (TOKEN > set(disptype)): - raise ValueError("bad content disposition type {!r}" "".format(disptype)) - - value = disptype - if params: - lparams = [] - for key, val in params.items(): - if not key or not (TOKEN > set(key)): - raise ValueError( - "bad content disposition parameter" " {!r}={!r}".format(key, val) - ) - if quote_fields: - if key.lower() == "filename": - qval = quote(val, "", encoding=_charset) - lparams.append((key, '"%s"' % qval)) - else: - try: - qval = quoted_string(val) - except ValueError: - qval = "".join( - (_charset, "''", quote(val, "", encoding=_charset)) - ) - lparams.append((key + "*", qval)) - else: - lparams.append((key, '"%s"' % qval)) - else: - qval = val.replace("\\", "\\\\").replace('"', '\\"') - lparams.append((key, '"%s"' % qval)) - sparams = "; ".join("=".join(pair) for pair in lparams) - value = "; ".join((value, sparams)) - return value - - -class _TSelf(Protocol, Generic[_T]): - _cache: Dict[str, _T] - - -class reify(Generic[_T]): - """Use as a class method decorator. - - It operates almost exactly like - the Python `@property` decorator, but it puts the result of the - method it decorates into the instance dict after the first call, - effectively replacing the function it decorates with an instance - variable. It is, in Python parlance, a data descriptor. - """ - - def __init__(self, wrapped: Callable[..., _T]) -> None: - self.wrapped = wrapped - self.__doc__ = wrapped.__doc__ - self.name = wrapped.__name__ - - def __get__(self, inst: _TSelf[_T], owner: Optional[Type[Any]] = None) -> _T: - try: - try: - return inst._cache[self.name] - except KeyError: - val = self.wrapped(inst) - inst._cache[self.name] = val - return val - except AttributeError: - if inst is None: - return self - raise - - def __set__(self, inst: _TSelf[_T], value: _T) -> None: - raise AttributeError("reified property is read-only") - - -reify_py = reify - -try: - from ._helpers import reify as reify_c - - if not NO_EXTENSIONS: - reify = reify_c # type: ignore[misc,assignment] -except ImportError: - pass - -_ipv4_pattern = ( - r"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}" - r"(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$" -) -_ipv6_pattern = ( - r"^(?:(?:(?:[A-F0-9]{1,4}:){6}|(?=(?:[A-F0-9]{0,4}:){0,6}" - r"(?:[0-9]{1,3}\.){3}[0-9]{1,3}$)(([0-9A-F]{1,4}:){0,5}|:)" - r"((:[0-9A-F]{1,4}){1,5}:|:)|::(?:[A-F0-9]{1,4}:){5})" - r"(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}" - r"(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])|(?:[A-F0-9]{1,4}:){7}" - r"[A-F0-9]{1,4}|(?=(?:[A-F0-9]{0,4}:){0,7}[A-F0-9]{0,4}$)" - r"(([0-9A-F]{1,4}:){1,7}|:)((:[0-9A-F]{1,4}){1,7}|:)|(?:[A-F0-9]{1,4}:){7}" - r":|:(:[A-F0-9]{1,4}){7})$" -) -_ipv4_regex = re.compile(_ipv4_pattern) -_ipv6_regex = re.compile(_ipv6_pattern, flags=re.IGNORECASE) -_ipv4_regexb = re.compile(_ipv4_pattern.encode("ascii")) -_ipv6_regexb = re.compile(_ipv6_pattern.encode("ascii"), flags=re.IGNORECASE) - - -def _is_ip_address( - regex: Pattern[str], regexb: Pattern[bytes], host: Optional[Union[str, bytes]] -) -> bool: - if host is None: - return False - if isinstance(host, str): - return bool(regex.match(host)) - elif isinstance(host, (bytes, bytearray, memoryview)): - return bool(regexb.match(host)) - else: - raise TypeError(f"{host} [{type(host)}] is not a str or bytes") - - -is_ipv4_address = functools.partial(_is_ip_address, _ipv4_regex, _ipv4_regexb) -is_ipv6_address = functools.partial(_is_ip_address, _ipv6_regex, _ipv6_regexb) - - -def is_ip_address(host: Optional[Union[str, bytes, bytearray, memoryview]]) -> bool: - return is_ipv4_address(host) or is_ipv6_address(host) - - -def next_whole_second() -> datetime.datetime: - """Return current time rounded up to the next whole second.""" - return datetime.datetime.now(datetime.timezone.utc).replace( - microsecond=0 - ) + datetime.timedelta(seconds=0) - - -_cached_current_datetime = None # type: Optional[int] -_cached_formatted_datetime = "" - - -def rfc822_formatted_time() -> str: - global _cached_current_datetime - global _cached_formatted_datetime - - now = int(time.time()) - if now != _cached_current_datetime: - # Weekday and month names for HTTP date/time formatting; - # always English! - # Tuples are constants stored in codeobject! - _weekdayname = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") - _monthname = ( - "", # Dummy so we can use 1-based month numbers - "Jan", - "Feb", - "Mar", - "Apr", - "May", - "Jun", - "Jul", - "Aug", - "Sep", - "Oct", - "Nov", - "Dec", - ) - - year, month, day, hh, mm, ss, wd, *tail = time.gmtime(now) - _cached_formatted_datetime = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % ( - _weekdayname[wd], - day, - _monthname[month], - year, - hh, - mm, - ss, - ) - _cached_current_datetime = now - return _cached_formatted_datetime - - -def _weakref_handle(info: "Tuple[weakref.ref[object], str]") -> None: - ref, name = info - ob = ref() - if ob is not None: - with suppress(Exception): - getattr(ob, name)() - - -def weakref_handle( - ob: object, name: str, timeout: float, loop: asyncio.AbstractEventLoop -) -> Optional[asyncio.TimerHandle]: - if timeout is not None and timeout > 0: - when = loop.time() + timeout - if timeout >= 5: - when = ceil(when) - - return loop.call_at(when, _weakref_handle, (weakref.ref(ob), name)) - return None - - -def call_later( - cb: Callable[[], Any], timeout: float, loop: asyncio.AbstractEventLoop -) -> Optional[asyncio.TimerHandle]: - if timeout is not None and timeout > 0: - when = loop.time() + timeout - if timeout > 5: - when = ceil(when) - return loop.call_at(when, cb) - return None - - -class TimeoutHandle: - """Timeout handle""" - - def __init__( - self, loop: asyncio.AbstractEventLoop, timeout: Optional[float] - ) -> None: - self._timeout = timeout - self._loop = loop - self._callbacks = ( - [] - ) # type: List[Tuple[Callable[..., None], Tuple[Any, ...], Dict[str, Any]]] - - def register( - self, callback: Callable[..., None], *args: Any, **kwargs: Any - ) -> None: - self._callbacks.append((callback, args, kwargs)) - - def close(self) -> None: - self._callbacks.clear() - - def start(self) -> Optional[asyncio.Handle]: - timeout = self._timeout - if timeout is not None and timeout > 0: - when = self._loop.time() + timeout - if timeout >= 5: - when = ceil(when) - return self._loop.call_at(when, self.__call__) - else: - return None - - def timer(self) -> "BaseTimerContext": - if self._timeout is not None and self._timeout > 0: - timer = TimerContext(self._loop) - self.register(timer.timeout) - return timer - else: - return TimerNoop() - - def __call__(self) -> None: - for cb, args, kwargs in self._callbacks: - with suppress(Exception): - cb(*args, **kwargs) - - self._callbacks.clear() - - -class BaseTimerContext(ContextManager["BaseTimerContext"]): - pass - - -class TimerNoop(BaseTimerContext): - def __enter__(self) -> BaseTimerContext: - return self - - def __exit__( - self, - exc_type: Optional[Type[BaseException]], - exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType], - ) -> None: - return - - -class TimerContext(BaseTimerContext): - """Low resolution timeout context manager""" - - def __init__(self, loop: asyncio.AbstractEventLoop) -> None: - self._loop = loop - self._tasks = [] # type: List[asyncio.Task[Any]] - self._cancelled = False - - def __enter__(self) -> BaseTimerContext: - task = current_task(loop=self._loop) - - if task is None: - raise RuntimeError( - "Timeout context manager should be used " "inside a task" - ) - - if self._cancelled: - raise asyncio.TimeoutError from None - - self._tasks.append(task) - return self - - def __exit__( - self, - exc_type: Optional[Type[BaseException]], - exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType], - ) -> Optional[bool]: - if self._tasks: - self._tasks.pop() - - if exc_type is asyncio.CancelledError and self._cancelled: - raise asyncio.TimeoutError from None - return None - - def timeout(self) -> None: - if not self._cancelled: - for task in set(self._tasks): - task.cancel() - - self._cancelled = True - - -def ceil_timeout(delay: Optional[float]) -> async_timeout.Timeout: - if delay is None or delay <= 0: - return async_timeout.timeout(None) - - loop = get_running_loop() - now = loop.time() - when = now + delay - if delay > 5: - when = ceil(when) - return async_timeout.timeout_at(when) - - -class HeadersMixin: - - ATTRS = frozenset(["_content_type", "_content_dict", "_stored_content_type"]) - - _content_type = None # type: Optional[str] - _content_dict = None # type: Optional[Dict[str, str]] - _stored_content_type = sentinel - - def _parse_content_type(self, raw: str) -> None: - self._stored_content_type = raw - if raw is None: - # default value according to RFC 2616 - self._content_type = "application/octet-stream" - self._content_dict = {} - else: - self._content_type, self._content_dict = cgi.parse_header(raw) - - @property - def content_type(self) -> str: - """The value of content part for Content-Type HTTP header.""" - raw = self._headers.get(hdrs.CONTENT_TYPE) # type: ignore[attr-defined] - if self._stored_content_type != raw: - self._parse_content_type(raw) - return self._content_type # type: ignore[return-value] - - @property - def charset(self) -> Optional[str]: - """The value of charset part for Content-Type HTTP header.""" - raw = self._headers.get(hdrs.CONTENT_TYPE) # type: ignore[attr-defined] - if self._stored_content_type != raw: - self._parse_content_type(raw) - return self._content_dict.get("charset") # type: ignore[union-attr] - - @property - def content_length(self) -> Optional[int]: - """The value of Content-Length HTTP header.""" - content_length = self._headers.get( # type: ignore[attr-defined] - hdrs.CONTENT_LENGTH - ) - - if content_length is not None: - return int(content_length) - else: - return None - - -def set_result(fut: "asyncio.Future[_T]", result: _T) -> None: - if not fut.done(): - fut.set_result(result) - - -def set_exception(fut: "asyncio.Future[_T]", exc: BaseException) -> None: - if not fut.done(): - fut.set_exception(exc) - - -class ChainMapProxy(Mapping[str, Any]): - __slots__ = ("_maps",) - - def __init__(self, maps: Iterable[Mapping[str, Any]]) -> None: - self._maps = tuple(maps) - - def __init_subclass__(cls) -> None: - raise TypeError( - "Inheritance class {} from ChainMapProxy " - "is forbidden".format(cls.__name__) - ) - - def __getitem__(self, key: str) -> Any: - for mapping in self._maps: - try: - return mapping[key] - except KeyError: - pass - raise KeyError(key) - - def get(self, key: str, default: Any = None) -> Any: - return self[key] if key in self else default - - def __len__(self) -> int: - # reuses stored hash values if possible - return len(set().union(*self._maps)) # type: ignore[arg-type] - - def __iter__(self) -> Iterator[str]: - d = {} # type: Dict[str, Any] - for mapping in reversed(self._maps): - # reuses stored hash values if possible - d.update(mapping) - return iter(d) - - def __contains__(self, key: object) -> bool: - return any(key in m for m in self._maps) - - def __bool__(self) -> bool: - return any(self._maps) - - def __repr__(self) -> str: - content = ", ".join(map(repr, self._maps)) - return f"ChainMapProxy({content})" - - -# https://tools.ietf.org/html/rfc7232#section-2.3 -_ETAGC = r"[!#-}\x80-\xff]+" -_ETAGC_RE = re.compile(_ETAGC) -_QUOTED_ETAG = fr'(W/)?"({_ETAGC})"' -QUOTED_ETAG_RE = re.compile(_QUOTED_ETAG) -LIST_QUOTED_ETAG_RE = re.compile(fr"({_QUOTED_ETAG})(?:\s*,\s*|$)|(.)") - -ETAG_ANY = "*" - - -@attr.s(auto_attribs=True, frozen=True, slots=True) -class ETag: - value: str - is_weak: bool = False - - -def validate_etag_value(value: str) -> None: - if value != ETAG_ANY and not _ETAGC_RE.fullmatch(value): - raise ValueError( - f"Value {value!r} is not a valid etag. Maybe it contains '\"'?" - ) - - -def parse_http_date(date_str: Optional[str]) -> Optional[datetime.datetime]: - """Process a date string, return a datetime object""" - if date_str is not None: - timetuple = parsedate(date_str) - if timetuple is not None: - with suppress(ValueError): - return datetime.datetime(*timetuple[:6], tzinfo=datetime.timezone.utc) - return None diff --git a/.venv/Lib/site-packages/aiohttp/http.py b/.venv/Lib/site-packages/aiohttp/http.py deleted file mode 100644 index 415ffbf..0000000 --- a/.venv/Lib/site-packages/aiohttp/http.py +++ /dev/null @@ -1,72 +0,0 @@ -import http.server -import sys -from typing import Mapping, Tuple - -from . import __version__ -from .http_exceptions import HttpProcessingError as HttpProcessingError -from .http_parser import ( - HeadersParser as HeadersParser, - HttpParser as HttpParser, - HttpRequestParser as HttpRequestParser, - HttpResponseParser as HttpResponseParser, - RawRequestMessage as RawRequestMessage, - RawResponseMessage as RawResponseMessage, -) -from .http_websocket import ( - WS_CLOSED_MESSAGE as WS_CLOSED_MESSAGE, - WS_CLOSING_MESSAGE as WS_CLOSING_MESSAGE, - WS_KEY as WS_KEY, - WebSocketError as WebSocketError, - WebSocketReader as WebSocketReader, - WebSocketWriter as WebSocketWriter, - WSCloseCode as WSCloseCode, - WSMessage as WSMessage, - WSMsgType as WSMsgType, - ws_ext_gen as ws_ext_gen, - ws_ext_parse as ws_ext_parse, -) -from .http_writer import ( - HttpVersion as HttpVersion, - HttpVersion10 as HttpVersion10, - HttpVersion11 as HttpVersion11, - StreamWriter as StreamWriter, -) - -__all__ = ( - "HttpProcessingError", - "RESPONSES", - "SERVER_SOFTWARE", - # .http_writer - "StreamWriter", - "HttpVersion", - "HttpVersion10", - "HttpVersion11", - # .http_parser - "HeadersParser", - "HttpParser", - "HttpRequestParser", - "HttpResponseParser", - "RawRequestMessage", - "RawResponseMessage", - # .http_websocket - "WS_CLOSED_MESSAGE", - "WS_CLOSING_MESSAGE", - "WS_KEY", - "WebSocketReader", - "WebSocketWriter", - "ws_ext_gen", - "ws_ext_parse", - "WSMessage", - "WebSocketError", - "WSMsgType", - "WSCloseCode", -) - - -SERVER_SOFTWARE = "Python/{0[0]}.{0[1]} aiohttp/{1}".format( - sys.version_info, __version__ -) # type: str - -RESPONSES = ( - http.server.BaseHTTPRequestHandler.responses -) # type: Mapping[int, Tuple[str, str]] diff --git a/.venv/Lib/site-packages/aiohttp/http_exceptions.py b/.venv/Lib/site-packages/aiohttp/http_exceptions.py deleted file mode 100644 index c885f80..0000000 --- a/.venv/Lib/site-packages/aiohttp/http_exceptions.py +++ /dev/null @@ -1,105 +0,0 @@ -"""Low-level http related exceptions.""" - - -from typing import Optional, Union - -from .typedefs import _CIMultiDict - -__all__ = ("HttpProcessingError",) - - -class HttpProcessingError(Exception): - """HTTP error. - - Shortcut for raising HTTP errors with custom code, message and headers. - - code: HTTP Error code. - message: (optional) Error message. - headers: (optional) Headers to be sent in response, a list of pairs - """ - - code = 0 - message = "" - headers = None - - def __init__( - self, - *, - code: Optional[int] = None, - message: str = "", - headers: Optional[_CIMultiDict] = None, - ) -> None: - if code is not None: - self.code = code - self.headers = headers - self.message = message - - def __str__(self) -> str: - return f"{self.code}, message={self.message!r}" - - def __repr__(self) -> str: - return f"<{self.__class__.__name__}: {self}>" - - -class BadHttpMessage(HttpProcessingError): - - code = 400 - message = "Bad Request" - - def __init__(self, message: str, *, headers: Optional[_CIMultiDict] = None) -> None: - super().__init__(message=message, headers=headers) - self.args = (message,) - - -class HttpBadRequest(BadHttpMessage): - - code = 400 - message = "Bad Request" - - -class PayloadEncodingError(BadHttpMessage): - """Base class for payload errors""" - - -class ContentEncodingError(PayloadEncodingError): - """Content encoding error.""" - - -class TransferEncodingError(PayloadEncodingError): - """transfer encoding error.""" - - -class ContentLengthError(PayloadEncodingError): - """Not enough data for satisfy content length header.""" - - -class LineTooLong(BadHttpMessage): - def __init__( - self, line: str, limit: str = "Unknown", actual_size: str = "Unknown" - ) -> None: - super().__init__( - f"Got more than {limit} bytes ({actual_size}) when reading {line}." - ) - self.args = (line, limit, actual_size) - - -class InvalidHeader(BadHttpMessage): - def __init__(self, hdr: Union[bytes, str]) -> None: - if isinstance(hdr, bytes): - hdr = hdr.decode("utf-8", "surrogateescape") - super().__init__(f"Invalid HTTP Header: {hdr}") - self.hdr = hdr - self.args = (hdr,) - - -class BadStatusLine(BadHttpMessage): - def __init__(self, line: str = "") -> None: - if not isinstance(line, str): - line = repr(line) - super().__init__(f"Bad status line {line!r}") - self.args = (line,) - self.line = line - - -class InvalidURLError(BadHttpMessage): - pass diff --git a/.venv/Lib/site-packages/aiohttp/http_parser.py b/.venv/Lib/site-packages/aiohttp/http_parser.py deleted file mode 100644 index 2dc9482..0000000 --- a/.venv/Lib/site-packages/aiohttp/http_parser.py +++ /dev/null @@ -1,956 +0,0 @@ -import abc -import asyncio -import collections -import re -import string -import zlib -from contextlib import suppress -from enum import IntEnum -from typing import ( - Any, - Generic, - List, - NamedTuple, - Optional, - Pattern, - Set, - Tuple, - Type, - TypeVar, - Union, - cast, -) - -from multidict import CIMultiDict, CIMultiDictProxy, istr -from yarl import URL - -from . import hdrs -from .base_protocol import BaseProtocol -from .helpers import NO_EXTENSIONS, BaseTimerContext -from .http_exceptions import ( - BadHttpMessage, - BadStatusLine, - ContentEncodingError, - ContentLengthError, - InvalidHeader, - LineTooLong, - TransferEncodingError, -) -from .http_writer import HttpVersion, HttpVersion10 -from .log import internal_logger -from .streams import EMPTY_PAYLOAD, StreamReader -from .typedefs import Final, RawHeaders - -try: - import brotli - - HAS_BROTLI = True -except ImportError: # pragma: no cover - HAS_BROTLI = False - - -__all__ = ( - "HeadersParser", - "HttpParser", - "HttpRequestParser", - "HttpResponseParser", - "RawRequestMessage", - "RawResponseMessage", -) - -ASCIISET: Final[Set[str]] = set(string.printable) - -# See https://tools.ietf.org/html/rfc7230#section-3.1.1 -# and https://tools.ietf.org/html/rfc7230#appendix-B -# -# method = token -# tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / -# "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA -# token = 1*tchar -METHRE: Final[Pattern[str]] = re.compile(r"[!#$%&'*+\-.^_`|~0-9A-Za-z]+") -VERSRE: Final[Pattern[str]] = re.compile(r"HTTP/(\d+).(\d+)") -HDRRE: Final[Pattern[bytes]] = re.compile(rb"[\x00-\x1F\x7F()<>@,;:\[\]={} \t\\\\\"]") - - -class RawRequestMessage(NamedTuple): - method: str - path: str - version: HttpVersion - headers: "CIMultiDictProxy[str]" - raw_headers: RawHeaders - should_close: bool - compression: Optional[str] - upgrade: bool - chunked: bool - url: URL - - -RawResponseMessage = collections.namedtuple( - "RawResponseMessage", - [ - "version", - "code", - "reason", - "headers", - "raw_headers", - "should_close", - "compression", - "upgrade", - "chunked", - ], -) - - -_MsgT = TypeVar("_MsgT", RawRequestMessage, RawResponseMessage) - - -class ParseState(IntEnum): - - PARSE_NONE = 0 - PARSE_LENGTH = 1 - PARSE_CHUNKED = 2 - PARSE_UNTIL_EOF = 3 - - -class ChunkState(IntEnum): - PARSE_CHUNKED_SIZE = 0 - PARSE_CHUNKED_CHUNK = 1 - PARSE_CHUNKED_CHUNK_EOF = 2 - PARSE_MAYBE_TRAILERS = 3 - PARSE_TRAILERS = 4 - - -class HeadersParser: - def __init__( - self, - max_line_size: int = 8190, - max_headers: int = 32768, - max_field_size: int = 8190, - ) -> None: - self.max_line_size = max_line_size - self.max_headers = max_headers - self.max_field_size = max_field_size - - def parse_headers( - self, lines: List[bytes] - ) -> Tuple["CIMultiDictProxy[str]", RawHeaders]: - headers = CIMultiDict() # type: CIMultiDict[str] - raw_headers = [] - - lines_idx = 1 - line = lines[1] - line_count = len(lines) - - while line: - # Parse initial header name : value pair. - try: - bname, bvalue = line.split(b":", 1) - except ValueError: - raise InvalidHeader(line) from None - - bname = bname.strip(b" \t") - bvalue = bvalue.lstrip() - if HDRRE.search(bname): - raise InvalidHeader(bname) - if len(bname) > self.max_field_size: - raise LineTooLong( - "request header name {}".format( - bname.decode("utf8", "xmlcharrefreplace") - ), - str(self.max_field_size), - str(len(bname)), - ) - - header_length = len(bvalue) - - # next line - lines_idx += 1 - line = lines[lines_idx] - - # consume continuation lines - continuation = line and line[0] in (32, 9) # (' ', '\t') - - if continuation: - bvalue_lst = [bvalue] - while continuation: - header_length += len(line) - if header_length > self.max_field_size: - raise LineTooLong( - "request header field {}".format( - bname.decode("utf8", "xmlcharrefreplace") - ), - str(self.max_field_size), - str(header_length), - ) - bvalue_lst.append(line) - - # next line - lines_idx += 1 - if lines_idx < line_count: - line = lines[lines_idx] - if line: - continuation = line[0] in (32, 9) # (' ', '\t') - else: - line = b"" - break - bvalue = b"".join(bvalue_lst) - else: - if header_length > self.max_field_size: - raise LineTooLong( - "request header field {}".format( - bname.decode("utf8", "xmlcharrefreplace") - ), - str(self.max_field_size), - str(header_length), - ) - - bvalue = bvalue.strip() - name = bname.decode("utf-8", "surrogateescape") - value = bvalue.decode("utf-8", "surrogateescape") - - headers.add(name, value) - raw_headers.append((bname, bvalue)) - - return (CIMultiDictProxy(headers), tuple(raw_headers)) - - -class HttpParser(abc.ABC, Generic[_MsgT]): - def __init__( - self, - protocol: Optional[BaseProtocol] = None, - loop: Optional[asyncio.AbstractEventLoop] = None, - limit: int = 2 ** 16, - max_line_size: int = 8190, - max_headers: int = 32768, - max_field_size: int = 8190, - timer: Optional[BaseTimerContext] = None, - code: Optional[int] = None, - method: Optional[str] = None, - readall: bool = False, - payload_exception: Optional[Type[BaseException]] = None, - response_with_body: bool = True, - read_until_eof: bool = False, - auto_decompress: bool = True, - ) -> None: - self.protocol = protocol - self.loop = loop - self.max_line_size = max_line_size - self.max_headers = max_headers - self.max_field_size = max_field_size - self.timer = timer - self.code = code - self.method = method - self.readall = readall - self.payload_exception = payload_exception - self.response_with_body = response_with_body - self.read_until_eof = read_until_eof - - self._lines = [] # type: List[bytes] - self._tail = b"" - self._upgraded = False - self._payload = None - self._payload_parser = None # type: Optional[HttpPayloadParser] - self._auto_decompress = auto_decompress - self._limit = limit - self._headers_parser = HeadersParser(max_line_size, max_headers, max_field_size) - - @abc.abstractmethod - def parse_message(self, lines: List[bytes]) -> _MsgT: - pass - - def feed_eof(self) -> Optional[_MsgT]: - if self._payload_parser is not None: - self._payload_parser.feed_eof() - self._payload_parser = None - else: - # try to extract partial message - if self._tail: - self._lines.append(self._tail) - - if self._lines: - if self._lines[-1] != "\r\n": - self._lines.append(b"") - with suppress(Exception): - return self.parse_message(self._lines) - return None - - def feed_data( - self, - data: bytes, - SEP: bytes = b"\r\n", - EMPTY: bytes = b"", - CONTENT_LENGTH: istr = hdrs.CONTENT_LENGTH, - METH_CONNECT: str = hdrs.METH_CONNECT, - SEC_WEBSOCKET_KEY1: istr = hdrs.SEC_WEBSOCKET_KEY1, - ) -> Tuple[List[Tuple[_MsgT, StreamReader]], bool, bytes]: - - messages = [] - - if self._tail: - data, self._tail = self._tail + data, b"" - - data_len = len(data) - start_pos = 0 - loop = self.loop - - while start_pos < data_len: - - # read HTTP message (request/response line + headers), \r\n\r\n - # and split by lines - if self._payload_parser is None and not self._upgraded: - pos = data.find(SEP, start_pos) - # consume \r\n - if pos == start_pos and not self._lines: - start_pos = pos + 2 - continue - - if pos >= start_pos: - # line found - self._lines.append(data[start_pos:pos]) - start_pos = pos + 2 - - # \r\n\r\n found - if self._lines[-1] == EMPTY: - try: - msg: _MsgT = self.parse_message(self._lines) - finally: - self._lines.clear() - - def get_content_length() -> Optional[int]: - # payload length - length_hdr = msg.headers.get(CONTENT_LENGTH) - if length_hdr is None: - return None - - try: - length = int(length_hdr) - except ValueError: - raise InvalidHeader(CONTENT_LENGTH) - - if length < 0: - raise InvalidHeader(CONTENT_LENGTH) - - return length - - length = get_content_length() - # do not support old websocket spec - if SEC_WEBSOCKET_KEY1 in msg.headers: - raise InvalidHeader(SEC_WEBSOCKET_KEY1) - - self._upgraded = msg.upgrade - - method = getattr(msg, "method", self.method) - - assert self.protocol is not None - # calculate payload - if ( - (length is not None and length > 0) - or msg.chunked - and not msg.upgrade - ): - payload = StreamReader( - self.protocol, - timer=self.timer, - loop=loop, - limit=self._limit, - ) - payload_parser = HttpPayloadParser( - payload, - length=length, - chunked=msg.chunked, - method=method, - compression=msg.compression, - code=self.code, - readall=self.readall, - response_with_body=self.response_with_body, - auto_decompress=self._auto_decompress, - ) - if not payload_parser.done: - self._payload_parser = payload_parser - elif method == METH_CONNECT: - assert isinstance(msg, RawRequestMessage) - payload = StreamReader( - self.protocol, - timer=self.timer, - loop=loop, - limit=self._limit, - ) - self._upgraded = True - self._payload_parser = HttpPayloadParser( - payload, - method=msg.method, - compression=msg.compression, - readall=True, - auto_decompress=self._auto_decompress, - ) - else: - if ( - getattr(msg, "code", 100) >= 199 - and length is None - and self.read_until_eof - ): - payload = StreamReader( - self.protocol, - timer=self.timer, - loop=loop, - limit=self._limit, - ) - payload_parser = HttpPayloadParser( - payload, - length=length, - chunked=msg.chunked, - method=method, - compression=msg.compression, - code=self.code, - readall=True, - response_with_body=self.response_with_body, - auto_decompress=self._auto_decompress, - ) - if not payload_parser.done: - self._payload_parser = payload_parser - else: - payload = EMPTY_PAYLOAD - - messages.append((msg, payload)) - else: - self._tail = data[start_pos:] - data = EMPTY - break - - # no parser, just store - elif self._payload_parser is None and self._upgraded: - assert not self._lines - break - - # feed payload - elif data and start_pos < data_len: - assert not self._lines - assert self._payload_parser is not None - try: - eof, data = self._payload_parser.feed_data(data[start_pos:]) - except BaseException as exc: - if self.payload_exception is not None: - self._payload_parser.payload.set_exception( - self.payload_exception(str(exc)) - ) - else: - self._payload_parser.payload.set_exception(exc) - - eof = True - data = b"" - - if eof: - start_pos = 0 - data_len = len(data) - self._payload_parser = None - continue - else: - break - - if data and start_pos < data_len: - data = data[start_pos:] - else: - data = EMPTY - - return messages, self._upgraded, data - - def parse_headers( - self, lines: List[bytes] - ) -> Tuple[ - "CIMultiDictProxy[str]", RawHeaders, Optional[bool], Optional[str], bool, bool - ]: - """Parses RFC 5322 headers from a stream. - - Line continuations are supported. Returns list of header name - and value pairs. Header name is in upper case. - """ - headers, raw_headers = self._headers_parser.parse_headers(lines) - close_conn = None - encoding = None - upgrade = False - chunked = False - - # keep-alive - conn = headers.get(hdrs.CONNECTION) - if conn: - v = conn.lower() - if v == "close": - close_conn = True - elif v == "keep-alive": - close_conn = False - elif v == "upgrade": - upgrade = True - - # encoding - enc = headers.get(hdrs.CONTENT_ENCODING) - if enc: - enc = enc.lower() - if enc in ("gzip", "deflate", "br"): - encoding = enc - - # chunking - te = headers.get(hdrs.TRANSFER_ENCODING) - if te is not None: - if "chunked" == te.lower(): - chunked = True - else: - raise BadHttpMessage("Request has invalid `Transfer-Encoding`") - - if hdrs.CONTENT_LENGTH in headers: - raise BadHttpMessage( - "Content-Length can't be present with Transfer-Encoding", - ) - - return (headers, raw_headers, close_conn, encoding, upgrade, chunked) - - def set_upgraded(self, val: bool) -> None: - """Set connection upgraded (to websocket) mode. - - :param bool val: new state. - """ - self._upgraded = val - - -class HttpRequestParser(HttpParser[RawRequestMessage]): - """Read request status line. - - Exception .http_exceptions.BadStatusLine - could be raised in case of any errors in status line. - Returns RawRequestMessage. - """ - - def parse_message(self, lines: List[bytes]) -> RawRequestMessage: - # request line - line = lines[0].decode("utf-8", "surrogateescape") - try: - method, path, version = line.split(None, 2) - except ValueError: - raise BadStatusLine(line) from None - - if len(path) > self.max_line_size: - raise LineTooLong( - "Status line is too long", str(self.max_line_size), str(len(path)) - ) - - path_part, _hash_separator, url_fragment = path.partition("#") - path_part, _question_mark_separator, qs_part = path_part.partition("?") - - # method - if not METHRE.match(method): - raise BadStatusLine(method) - - # version - try: - if version.startswith("HTTP/"): - n1, n2 = version[5:].split(".", 1) - version_o = HttpVersion(int(n1), int(n2)) - else: - raise BadStatusLine(version) - except Exception: - raise BadStatusLine(version) - - # read headers - ( - headers, - raw_headers, - close, - compression, - upgrade, - chunked, - ) = self.parse_headers(lines) - - if close is None: # then the headers weren't set in the request - if version_o <= HttpVersion10: # HTTP 1.0 must asks to not close - close = True - else: # HTTP 1.1 must ask to close. - close = False - - return RawRequestMessage( - method, - path, - version_o, - headers, - raw_headers, - close, - compression, - upgrade, - chunked, - # NOTE: `yarl.URL.build()` is used to mimic what the Cython-based - # NOTE: parser does, otherwise it results into the same - # NOTE: HTTP Request-Line input producing different - # NOTE: `yarl.URL()` objects - URL.build( - path=path_part, - query_string=qs_part, - fragment=url_fragment, - encoded=True, - ), - ) - - -class HttpResponseParser(HttpParser[RawResponseMessage]): - """Read response status line and headers. - - BadStatusLine could be raised in case of any errors in status line. - Returns RawResponseMessage. - """ - - def parse_message(self, lines: List[bytes]) -> RawResponseMessage: - line = lines[0].decode("utf-8", "surrogateescape") - try: - version, status = line.split(None, 1) - except ValueError: - raise BadStatusLine(line) from None - - try: - status, reason = status.split(None, 1) - except ValueError: - reason = "" - - if len(reason) > self.max_line_size: - raise LineTooLong( - "Status line is too long", str(self.max_line_size), str(len(reason)) - ) - - # version - match = VERSRE.match(version) - if match is None: - raise BadStatusLine(line) - version_o = HttpVersion(int(match.group(1)), int(match.group(2))) - - # The status code is a three-digit number - try: - status_i = int(status) - except ValueError: - raise BadStatusLine(line) from None - - if status_i > 999: - raise BadStatusLine(line) - - # read headers - ( - headers, - raw_headers, - close, - compression, - upgrade, - chunked, - ) = self.parse_headers(lines) - - if close is None: - close = version_o <= HttpVersion10 - - return RawResponseMessage( - version_o, - status_i, - reason.strip(), - headers, - raw_headers, - close, - compression, - upgrade, - chunked, - ) - - -class HttpPayloadParser: - def __init__( - self, - payload: StreamReader, - length: Optional[int] = None, - chunked: bool = False, - compression: Optional[str] = None, - code: Optional[int] = None, - method: Optional[str] = None, - readall: bool = False, - response_with_body: bool = True, - auto_decompress: bool = True, - ) -> None: - self._length = 0 - self._type = ParseState.PARSE_NONE - self._chunk = ChunkState.PARSE_CHUNKED_SIZE - self._chunk_size = 0 - self._chunk_tail = b"" - self._auto_decompress = auto_decompress - self.done = False - - # payload decompression wrapper - if response_with_body and compression and self._auto_decompress: - real_payload = DeflateBuffer( - payload, compression - ) # type: Union[StreamReader, DeflateBuffer] - else: - real_payload = payload - - # payload parser - if not response_with_body: - # don't parse payload if it's not expected to be received - self._type = ParseState.PARSE_NONE - real_payload.feed_eof() - self.done = True - - elif chunked: - self._type = ParseState.PARSE_CHUNKED - elif length is not None: - self._type = ParseState.PARSE_LENGTH - self._length = length - if self._length == 0: - real_payload.feed_eof() - self.done = True - else: - if readall and code != 204: - self._type = ParseState.PARSE_UNTIL_EOF - elif method in ("PUT", "POST"): - internal_logger.warning( # pragma: no cover - "Content-Length or Transfer-Encoding header is required" - ) - self._type = ParseState.PARSE_NONE - real_payload.feed_eof() - self.done = True - - self.payload = real_payload - - def feed_eof(self) -> None: - if self._type == ParseState.PARSE_UNTIL_EOF: - self.payload.feed_eof() - elif self._type == ParseState.PARSE_LENGTH: - raise ContentLengthError( - "Not enough data for satisfy content length header." - ) - elif self._type == ParseState.PARSE_CHUNKED: - raise TransferEncodingError( - "Not enough data for satisfy transfer length header." - ) - - def feed_data( - self, chunk: bytes, SEP: bytes = b"\r\n", CHUNK_EXT: bytes = b";" - ) -> Tuple[bool, bytes]: - # Read specified amount of bytes - if self._type == ParseState.PARSE_LENGTH: - required = self._length - chunk_len = len(chunk) - - if required >= chunk_len: - self._length = required - chunk_len - self.payload.feed_data(chunk, chunk_len) - if self._length == 0: - self.payload.feed_eof() - return True, b"" - else: - self._length = 0 - self.payload.feed_data(chunk[:required], required) - self.payload.feed_eof() - return True, chunk[required:] - - # Chunked transfer encoding parser - elif self._type == ParseState.PARSE_CHUNKED: - if self._chunk_tail: - chunk = self._chunk_tail + chunk - self._chunk_tail = b"" - - while chunk: - - # read next chunk size - if self._chunk == ChunkState.PARSE_CHUNKED_SIZE: - pos = chunk.find(SEP) - if pos >= 0: - i = chunk.find(CHUNK_EXT, 0, pos) - if i >= 0: - size_b = chunk[:i] # strip chunk-extensions - else: - size_b = chunk[:pos] - - try: - size = int(bytes(size_b), 16) - except ValueError: - exc = TransferEncodingError( - chunk[:pos].decode("ascii", "surrogateescape") - ) - self.payload.set_exception(exc) - raise exc from None - - chunk = chunk[pos + 2 :] - if size == 0: # eof marker - self._chunk = ChunkState.PARSE_MAYBE_TRAILERS - else: - self._chunk = ChunkState.PARSE_CHUNKED_CHUNK - self._chunk_size = size - self.payload.begin_http_chunk_receiving() - else: - self._chunk_tail = chunk - return False, b"" - - # read chunk and feed buffer - if self._chunk == ChunkState.PARSE_CHUNKED_CHUNK: - required = self._chunk_size - chunk_len = len(chunk) - - if required > chunk_len: - self._chunk_size = required - chunk_len - self.payload.feed_data(chunk, chunk_len) - return False, b"" - else: - self._chunk_size = 0 - self.payload.feed_data(chunk[:required], required) - chunk = chunk[required:] - self._chunk = ChunkState.PARSE_CHUNKED_CHUNK_EOF - self.payload.end_http_chunk_receiving() - - # toss the CRLF at the end of the chunk - if self._chunk == ChunkState.PARSE_CHUNKED_CHUNK_EOF: - if chunk[:2] == SEP: - chunk = chunk[2:] - self._chunk = ChunkState.PARSE_CHUNKED_SIZE - else: - self._chunk_tail = chunk - return False, b"" - - # if stream does not contain trailer, after 0\r\n - # we should get another \r\n otherwise - # trailers needs to be skiped until \r\n\r\n - if self._chunk == ChunkState.PARSE_MAYBE_TRAILERS: - head = chunk[:2] - if head == SEP: - # end of stream - self.payload.feed_eof() - return True, chunk[2:] - # Both CR and LF, or only LF may not be received yet. It is - # expected that CRLF or LF will be shown at the very first - # byte next time, otherwise trailers should come. The last - # CRLF which marks the end of response might not be - # contained in the same TCP segment which delivered the - # size indicator. - if not head: - return False, b"" - if head == SEP[:1]: - self._chunk_tail = head - return False, b"" - self._chunk = ChunkState.PARSE_TRAILERS - - # read and discard trailer up to the CRLF terminator - if self._chunk == ChunkState.PARSE_TRAILERS: - pos = chunk.find(SEP) - if pos >= 0: - chunk = chunk[pos + 2 :] - self._chunk = ChunkState.PARSE_MAYBE_TRAILERS - else: - self._chunk_tail = chunk - return False, b"" - - # Read all bytes until eof - elif self._type == ParseState.PARSE_UNTIL_EOF: - self.payload.feed_data(chunk, len(chunk)) - - return False, b"" - - -class DeflateBuffer: - """DeflateStream decompress stream and feed data into specified stream.""" - - decompressor: Any - - def __init__(self, out: StreamReader, encoding: Optional[str]) -> None: - self.out = out - self.size = 0 - self.encoding = encoding - self._started_decoding = False - - if encoding == "br": - if not HAS_BROTLI: # pragma: no cover - raise ContentEncodingError( - "Can not decode content-encoding: brotli (br). " - "Please install `Brotli`" - ) - - class BrotliDecoder: - # Supports both 'brotlipy' and 'Brotli' packages - # since they share an import name. The top branches - # are for 'brotlipy' and bottom branches for 'Brotli' - def __init__(self) -> None: - self._obj = brotli.Decompressor() - - def decompress(self, data: bytes) -> bytes: - if hasattr(self._obj, "decompress"): - return cast(bytes, self._obj.decompress(data)) - return cast(bytes, self._obj.process(data)) - - def flush(self) -> bytes: - if hasattr(self._obj, "flush"): - return cast(bytes, self._obj.flush()) - return b"" - - self.decompressor = BrotliDecoder() - else: - zlib_mode = 16 + zlib.MAX_WBITS if encoding == "gzip" else zlib.MAX_WBITS - self.decompressor = zlib.decompressobj(wbits=zlib_mode) - - def set_exception(self, exc: BaseException) -> None: - self.out.set_exception(exc) - - def feed_data(self, chunk: bytes, size: int) -> None: - if not size: - return - - self.size += size - - # RFC1950 - # bits 0..3 = CM = 0b1000 = 8 = "deflate" - # bits 4..7 = CINFO = 1..7 = windows size. - if ( - not self._started_decoding - and self.encoding == "deflate" - and chunk[0] & 0xF != 8 - ): - # Change the decoder to decompress incorrectly compressed data - # Actually we should issue a warning about non-RFC-compliant data. - self.decompressor = zlib.decompressobj(wbits=-zlib.MAX_WBITS) - - try: - chunk = self.decompressor.decompress(chunk) - except Exception: - raise ContentEncodingError( - "Can not decode content-encoding: %s" % self.encoding - ) - - self._started_decoding = True - - if chunk: - self.out.feed_data(chunk, len(chunk)) - - def feed_eof(self) -> None: - chunk = self.decompressor.flush() - - if chunk or self.size > 0: - self.out.feed_data(chunk, len(chunk)) - if self.encoding == "deflate" and not self.decompressor.eof: - raise ContentEncodingError("deflate") - - self.out.feed_eof() - - def begin_http_chunk_receiving(self) -> None: - self.out.begin_http_chunk_receiving() - - def end_http_chunk_receiving(self) -> None: - self.out.end_http_chunk_receiving() - - -HttpRequestParserPy = HttpRequestParser -HttpResponseParserPy = HttpResponseParser -RawRequestMessagePy = RawRequestMessage -RawResponseMessagePy = RawResponseMessage - -try: - if not NO_EXTENSIONS: - from ._http_parser import ( # type: ignore[import,no-redef] - HttpRequestParser, - HttpResponseParser, - RawRequestMessage, - RawResponseMessage, - ) - - HttpRequestParserC = HttpRequestParser - HttpResponseParserC = HttpResponseParser - RawRequestMessageC = RawRequestMessage - RawResponseMessageC = RawResponseMessage -except ImportError: # pragma: no cover - pass diff --git a/.venv/Lib/site-packages/aiohttp/http_websocket.py b/.venv/Lib/site-packages/aiohttp/http_websocket.py deleted file mode 100644 index 991a149..0000000 --- a/.venv/Lib/site-packages/aiohttp/http_websocket.py +++ /dev/null @@ -1,701 +0,0 @@ -"""WebSocket protocol versions 13 and 8.""" - -import asyncio -import collections -import json -import random -import re -import sys -import zlib -from enum import IntEnum -from struct import Struct -from typing import Any, Callable, List, Optional, Pattern, Set, Tuple, Union, cast - -from .base_protocol import BaseProtocol -from .helpers import NO_EXTENSIONS -from .streams import DataQueue -from .typedefs import Final - -__all__ = ( - "WS_CLOSED_MESSAGE", - "WS_CLOSING_MESSAGE", - "WS_KEY", - "WebSocketReader", - "WebSocketWriter", - "WSMessage", - "WebSocketError", - "WSMsgType", - "WSCloseCode", -) - - -class WSCloseCode(IntEnum): - OK = 1000 - GOING_AWAY = 1001 - PROTOCOL_ERROR = 1002 - UNSUPPORTED_DATA = 1003 - ABNORMAL_CLOSURE = 1006 - INVALID_TEXT = 1007 - POLICY_VIOLATION = 1008 - MESSAGE_TOO_BIG = 1009 - MANDATORY_EXTENSION = 1010 - INTERNAL_ERROR = 1011 - SERVICE_RESTART = 1012 - TRY_AGAIN_LATER = 1013 - BAD_GATEWAY = 1014 - - -ALLOWED_CLOSE_CODES: Final[Set[int]] = {int(i) for i in WSCloseCode} - - -class WSMsgType(IntEnum): - # websocket spec types - CONTINUATION = 0x0 - TEXT = 0x1 - BINARY = 0x2 - PING = 0x9 - PONG = 0xA - CLOSE = 0x8 - - # aiohttp specific types - CLOSING = 0x100 - CLOSED = 0x101 - ERROR = 0x102 - - text = TEXT - binary = BINARY - ping = PING - pong = PONG - close = CLOSE - closing = CLOSING - closed = CLOSED - error = ERROR - - -WS_KEY: Final[bytes] = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11" - - -UNPACK_LEN2 = Struct("!H").unpack_from -UNPACK_LEN3 = Struct("!Q").unpack_from -UNPACK_CLOSE_CODE = Struct("!H").unpack -PACK_LEN1 = Struct("!BB").pack -PACK_LEN2 = Struct("!BBH").pack -PACK_LEN3 = Struct("!BBQ").pack -PACK_CLOSE_CODE = Struct("!H").pack -MSG_SIZE: Final[int] = 2 ** 14 -DEFAULT_LIMIT: Final[int] = 2 ** 16 - - -_WSMessageBase = collections.namedtuple("_WSMessageBase", ["type", "data", "extra"]) - - -class WSMessage(_WSMessageBase): - def json(self, *, loads: Callable[[Any], Any] = json.loads) -> Any: - """Return parsed JSON data. - - .. versionadded:: 0.22 - """ - return loads(self.data) - - -WS_CLOSED_MESSAGE = WSMessage(WSMsgType.CLOSED, None, None) -WS_CLOSING_MESSAGE = WSMessage(WSMsgType.CLOSING, None, None) - - -class WebSocketError(Exception): - """WebSocket protocol parser error.""" - - def __init__(self, code: int, message: str) -> None: - self.code = code - super().__init__(code, message) - - def __str__(self) -> str: - return cast(str, self.args[1]) - - -class WSHandshakeError(Exception): - """WebSocket protocol handshake error.""" - - -native_byteorder: Final[str] = sys.byteorder - - -# Used by _websocket_mask_python -_XOR_TABLE: Final[List[bytes]] = [bytes(a ^ b for a in range(256)) for b in range(256)] - - -def _websocket_mask_python(mask: bytes, data: bytearray) -> None: - """Websocket masking function. - - `mask` is a `bytes` object of length 4; `data` is a `bytearray` - object of any length. The contents of `data` are masked with `mask`, - as specified in section 5.3 of RFC 6455. - - Note that this function mutates the `data` argument. - - This pure-python implementation may be replaced by an optimized - version when available. - - """ - assert isinstance(data, bytearray), data - assert len(mask) == 4, mask - - if data: - a, b, c, d = (_XOR_TABLE[n] for n in mask) - data[::4] = data[::4].translate(a) - data[1::4] = data[1::4].translate(b) - data[2::4] = data[2::4].translate(c) - data[3::4] = data[3::4].translate(d) - - -if NO_EXTENSIONS: # pragma: no cover - _websocket_mask = _websocket_mask_python -else: - try: - from ._websocket import _websocket_mask_cython # type: ignore[import] - - _websocket_mask = _websocket_mask_cython - except ImportError: # pragma: no cover - _websocket_mask = _websocket_mask_python - -_WS_DEFLATE_TRAILING: Final[bytes] = bytes([0x00, 0x00, 0xFF, 0xFF]) - - -_WS_EXT_RE: Final[Pattern[str]] = re.compile( - r"^(?:;\s*(?:" - r"(server_no_context_takeover)|" - r"(client_no_context_takeover)|" - r"(server_max_window_bits(?:=(\d+))?)|" - r"(client_max_window_bits(?:=(\d+))?)))*$" -) - -_WS_EXT_RE_SPLIT: Final[Pattern[str]] = re.compile(r"permessage-deflate([^,]+)?") - - -def ws_ext_parse(extstr: Optional[str], isserver: bool = False) -> Tuple[int, bool]: - if not extstr: - return 0, False - - compress = 0 - notakeover = False - for ext in _WS_EXT_RE_SPLIT.finditer(extstr): - defext = ext.group(1) - # Return compress = 15 when get `permessage-deflate` - if not defext: - compress = 15 - break - match = _WS_EXT_RE.match(defext) - if match: - compress = 15 - if isserver: - # Server never fail to detect compress handshake. - # Server does not need to send max wbit to client - if match.group(4): - compress = int(match.group(4)) - # Group3 must match if group4 matches - # Compress wbit 8 does not support in zlib - # If compress level not support, - # CONTINUE to next extension - if compress > 15 or compress < 9: - compress = 0 - continue - if match.group(1): - notakeover = True - # Ignore regex group 5 & 6 for client_max_window_bits - break - else: - if match.group(6): - compress = int(match.group(6)) - # Group5 must match if group6 matches - # Compress wbit 8 does not support in zlib - # If compress level not support, - # FAIL the parse progress - if compress > 15 or compress < 9: - raise WSHandshakeError("Invalid window size") - if match.group(2): - notakeover = True - # Ignore regex group 5 & 6 for client_max_window_bits - break - # Return Fail if client side and not match - elif not isserver: - raise WSHandshakeError("Extension for deflate not supported" + ext.group(1)) - - return compress, notakeover - - -def ws_ext_gen( - compress: int = 15, isserver: bool = False, server_notakeover: bool = False -) -> str: - # client_notakeover=False not used for server - # compress wbit 8 does not support in zlib - if compress < 9 or compress > 15: - raise ValueError( - "Compress wbits must between 9 and 15, " "zlib does not support wbits=8" - ) - enabledext = ["permessage-deflate"] - if not isserver: - enabledext.append("client_max_window_bits") - - if compress < 15: - enabledext.append("server_max_window_bits=" + str(compress)) - if server_notakeover: - enabledext.append("server_no_context_takeover") - # if client_notakeover: - # enabledext.append('client_no_context_takeover') - return "; ".join(enabledext) - - -class WSParserState(IntEnum): - READ_HEADER = 1 - READ_PAYLOAD_LENGTH = 2 - READ_PAYLOAD_MASK = 3 - READ_PAYLOAD = 4 - - -class WebSocketReader: - def __init__( - self, queue: DataQueue[WSMessage], max_msg_size: int, compress: bool = True - ) -> None: - self.queue = queue - self._max_msg_size = max_msg_size - - self._exc = None # type: Optional[BaseException] - self._partial = bytearray() - self._state = WSParserState.READ_HEADER - - self._opcode = None # type: Optional[int] - self._frame_fin = False - self._frame_opcode = None # type: Optional[int] - self._frame_payload = bytearray() - - self._tail = b"" - self._has_mask = False - self._frame_mask = None # type: Optional[bytes] - self._payload_length = 0 - self._payload_length_flag = 0 - self._compressed = None # type: Optional[bool] - self._decompressobj = None # type: Any # zlib.decompressobj actually - self._compress = compress - - def feed_eof(self) -> None: - self.queue.feed_eof() - - def feed_data(self, data: bytes) -> Tuple[bool, bytes]: - if self._exc: - return True, data - - try: - return self._feed_data(data) - except Exception as exc: - self._exc = exc - self.queue.set_exception(exc) - return True, b"" - - def _feed_data(self, data: bytes) -> Tuple[bool, bytes]: - for fin, opcode, payload, compressed in self.parse_frame(data): - if compressed and not self._decompressobj: - self._decompressobj = zlib.decompressobj(wbits=-zlib.MAX_WBITS) - if opcode == WSMsgType.CLOSE: - if len(payload) >= 2: - close_code = UNPACK_CLOSE_CODE(payload[:2])[0] - if close_code < 3000 and close_code not in ALLOWED_CLOSE_CODES: - raise WebSocketError( - WSCloseCode.PROTOCOL_ERROR, - f"Invalid close code: {close_code}", - ) - try: - close_message = payload[2:].decode("utf-8") - except UnicodeDecodeError as exc: - raise WebSocketError( - WSCloseCode.INVALID_TEXT, "Invalid UTF-8 text message" - ) from exc - msg = WSMessage(WSMsgType.CLOSE, close_code, close_message) - elif payload: - raise WebSocketError( - WSCloseCode.PROTOCOL_ERROR, - f"Invalid close frame: {fin} {opcode} {payload!r}", - ) - else: - msg = WSMessage(WSMsgType.CLOSE, 0, "") - - self.queue.feed_data(msg, 0) - - elif opcode == WSMsgType.PING: - self.queue.feed_data( - WSMessage(WSMsgType.PING, payload, ""), len(payload) - ) - - elif opcode == WSMsgType.PONG: - self.queue.feed_data( - WSMessage(WSMsgType.PONG, payload, ""), len(payload) - ) - - elif ( - opcode not in (WSMsgType.TEXT, WSMsgType.BINARY) - and self._opcode is None - ): - raise WebSocketError( - WSCloseCode.PROTOCOL_ERROR, f"Unexpected opcode={opcode!r}" - ) - else: - # load text/binary - if not fin: - # got partial frame payload - if opcode != WSMsgType.CONTINUATION: - self._opcode = opcode - self._partial.extend(payload) - if self._max_msg_size and len(self._partial) >= self._max_msg_size: - raise WebSocketError( - WSCloseCode.MESSAGE_TOO_BIG, - "Message size {} exceeds limit {}".format( - len(self._partial), self._max_msg_size - ), - ) - else: - # previous frame was non finished - # we should get continuation opcode - if self._partial: - if opcode != WSMsgType.CONTINUATION: - raise WebSocketError( - WSCloseCode.PROTOCOL_ERROR, - "The opcode in non-fin frame is expected " - "to be zero, got {!r}".format(opcode), - ) - - if opcode == WSMsgType.CONTINUATION: - assert self._opcode is not None - opcode = self._opcode - self._opcode = None - - self._partial.extend(payload) - if self._max_msg_size and len(self._partial) >= self._max_msg_size: - raise WebSocketError( - WSCloseCode.MESSAGE_TOO_BIG, - "Message size {} exceeds limit {}".format( - len(self._partial), self._max_msg_size - ), - ) - - # Decompress process must to be done after all packets - # received. - if compressed: - self._partial.extend(_WS_DEFLATE_TRAILING) - payload_merged = self._decompressobj.decompress( - self._partial, self._max_msg_size - ) - if self._decompressobj.unconsumed_tail: - left = len(self._decompressobj.unconsumed_tail) - raise WebSocketError( - WSCloseCode.MESSAGE_TOO_BIG, - "Decompressed message size {} exceeds limit {}".format( - self._max_msg_size + left, self._max_msg_size - ), - ) - else: - payload_merged = bytes(self._partial) - - self._partial.clear() - - if opcode == WSMsgType.TEXT: - try: - text = payload_merged.decode("utf-8") - self.queue.feed_data( - WSMessage(WSMsgType.TEXT, text, ""), len(text) - ) - except UnicodeDecodeError as exc: - raise WebSocketError( - WSCloseCode.INVALID_TEXT, "Invalid UTF-8 text message" - ) from exc - else: - self.queue.feed_data( - WSMessage(WSMsgType.BINARY, payload_merged, ""), - len(payload_merged), - ) - - return False, b"" - - def parse_frame( - self, buf: bytes - ) -> List[Tuple[bool, Optional[int], bytearray, Optional[bool]]]: - """Return the next frame from the socket.""" - frames = [] - if self._tail: - buf, self._tail = self._tail + buf, b"" - - start_pos = 0 - buf_length = len(buf) - - while True: - # read header - if self._state == WSParserState.READ_HEADER: - if buf_length - start_pos >= 2: - data = buf[start_pos : start_pos + 2] - start_pos += 2 - first_byte, second_byte = data - - fin = (first_byte >> 7) & 1 - rsv1 = (first_byte >> 6) & 1 - rsv2 = (first_byte >> 5) & 1 - rsv3 = (first_byte >> 4) & 1 - opcode = first_byte & 0xF - - # frame-fin = %x0 ; more frames of this message follow - # / %x1 ; final frame of this message - # frame-rsv1 = %x0 ; - # 1 bit, MUST be 0 unless negotiated otherwise - # frame-rsv2 = %x0 ; - # 1 bit, MUST be 0 unless negotiated otherwise - # frame-rsv3 = %x0 ; - # 1 bit, MUST be 0 unless negotiated otherwise - # - # Remove rsv1 from this test for deflate development - if rsv2 or rsv3 or (rsv1 and not self._compress): - raise WebSocketError( - WSCloseCode.PROTOCOL_ERROR, - "Received frame with non-zero reserved bits", - ) - - if opcode > 0x7 and fin == 0: - raise WebSocketError( - WSCloseCode.PROTOCOL_ERROR, - "Received fragmented control frame", - ) - - has_mask = (second_byte >> 7) & 1 - length = second_byte & 0x7F - - # Control frames MUST have a payload - # length of 125 bytes or less - if opcode > 0x7 and length > 125: - raise WebSocketError( - WSCloseCode.PROTOCOL_ERROR, - "Control frame payload cannot be " "larger than 125 bytes", - ) - - # Set compress status if last package is FIN - # OR set compress status if this is first fragment - # Raise error if not first fragment with rsv1 = 0x1 - if self._frame_fin or self._compressed is None: - self._compressed = True if rsv1 else False - elif rsv1: - raise WebSocketError( - WSCloseCode.PROTOCOL_ERROR, - "Received frame with non-zero reserved bits", - ) - - self._frame_fin = bool(fin) - self._frame_opcode = opcode - self._has_mask = bool(has_mask) - self._payload_length_flag = length - self._state = WSParserState.READ_PAYLOAD_LENGTH - else: - break - - # read payload length - if self._state == WSParserState.READ_PAYLOAD_LENGTH: - length = self._payload_length_flag - if length == 126: - if buf_length - start_pos >= 2: - data = buf[start_pos : start_pos + 2] - start_pos += 2 - length = UNPACK_LEN2(data)[0] - self._payload_length = length - self._state = ( - WSParserState.READ_PAYLOAD_MASK - if self._has_mask - else WSParserState.READ_PAYLOAD - ) - else: - break - elif length > 126: - if buf_length - start_pos >= 8: - data = buf[start_pos : start_pos + 8] - start_pos += 8 - length = UNPACK_LEN3(data)[0] - self._payload_length = length - self._state = ( - WSParserState.READ_PAYLOAD_MASK - if self._has_mask - else WSParserState.READ_PAYLOAD - ) - else: - break - else: - self._payload_length = length - self._state = ( - WSParserState.READ_PAYLOAD_MASK - if self._has_mask - else WSParserState.READ_PAYLOAD - ) - - # read payload mask - if self._state == WSParserState.READ_PAYLOAD_MASK: - if buf_length - start_pos >= 4: - self._frame_mask = buf[start_pos : start_pos + 4] - start_pos += 4 - self._state = WSParserState.READ_PAYLOAD - else: - break - - if self._state == WSParserState.READ_PAYLOAD: - length = self._payload_length - payload = self._frame_payload - - chunk_len = buf_length - start_pos - if length >= chunk_len: - self._payload_length = length - chunk_len - payload.extend(buf[start_pos:]) - start_pos = buf_length - else: - self._payload_length = 0 - payload.extend(buf[start_pos : start_pos + length]) - start_pos = start_pos + length - - if self._payload_length == 0: - if self._has_mask: - assert self._frame_mask is not None - _websocket_mask(self._frame_mask, payload) - - frames.append( - (self._frame_fin, self._frame_opcode, payload, self._compressed) - ) - - self._frame_payload = bytearray() - self._state = WSParserState.READ_HEADER - else: - break - - self._tail = buf[start_pos:] - - return frames - - -class WebSocketWriter: - def __init__( - self, - protocol: BaseProtocol, - transport: asyncio.Transport, - *, - use_mask: bool = False, - limit: int = DEFAULT_LIMIT, - random: Any = random.Random(), - compress: int = 0, - notakeover: bool = False, - ) -> None: - self.protocol = protocol - self.transport = transport - self.use_mask = use_mask - self.randrange = random.randrange - self.compress = compress - self.notakeover = notakeover - self._closing = False - self._limit = limit - self._output_size = 0 - self._compressobj = None # type: Any # actually compressobj - - async def _send_frame( - self, message: bytes, opcode: int, compress: Optional[int] = None - ) -> None: - """Send a frame over the websocket with message as its payload.""" - if self._closing and not (opcode & WSMsgType.CLOSE): - raise ConnectionResetError("Cannot write to closing transport") - - rsv = 0 - - # Only compress larger packets (disabled) - # Does small packet needs to be compressed? - # if self.compress and opcode < 8 and len(message) > 124: - if (compress or self.compress) and opcode < 8: - if compress: - # Do not set self._compress if compressing is for this frame - compressobj = zlib.compressobj(level=zlib.Z_BEST_SPEED, wbits=-compress) - else: # self.compress - if not self._compressobj: - self._compressobj = zlib.compressobj( - level=zlib.Z_BEST_SPEED, wbits=-self.compress - ) - compressobj = self._compressobj - - message = compressobj.compress(message) - message = message + compressobj.flush( - zlib.Z_FULL_FLUSH if self.notakeover else zlib.Z_SYNC_FLUSH - ) - if message.endswith(_WS_DEFLATE_TRAILING): - message = message[:-4] - rsv = rsv | 0x40 - - msg_length = len(message) - - use_mask = self.use_mask - if use_mask: - mask_bit = 0x80 - else: - mask_bit = 0 - - if msg_length < 126: - header = PACK_LEN1(0x80 | rsv | opcode, msg_length | mask_bit) - elif msg_length < (1 << 16): - header = PACK_LEN2(0x80 | rsv | opcode, 126 | mask_bit, msg_length) - else: - header = PACK_LEN3(0x80 | rsv | opcode, 127 | mask_bit, msg_length) - if use_mask: - mask = self.randrange(0, 0xFFFFFFFF) - mask = mask.to_bytes(4, "big") - message = bytearray(message) - _websocket_mask(mask, message) - self._write(header + mask + message) - self._output_size += len(header) + len(mask) + len(message) - else: - if len(message) > MSG_SIZE: - self._write(header) - self._write(message) - else: - self._write(header + message) - - self._output_size += len(header) + len(message) - - if self._output_size > self._limit: - self._output_size = 0 - await self.protocol._drain_helper() - - def _write(self, data: bytes) -> None: - if self.transport is None or self.transport.is_closing(): - raise ConnectionResetError("Cannot write to closing transport") - self.transport.write(data) - - async def pong(self, message: bytes = b"") -> None: - """Send pong message.""" - if isinstance(message, str): - message = message.encode("utf-8") - await self._send_frame(message, WSMsgType.PONG) - - async def ping(self, message: bytes = b"") -> None: - """Send ping message.""" - if isinstance(message, str): - message = message.encode("utf-8") - await self._send_frame(message, WSMsgType.PING) - - async def send( - self, - message: Union[str, bytes], - binary: bool = False, - compress: Optional[int] = None, - ) -> None: - """Send a frame over the websocket with message as its payload.""" - if isinstance(message, str): - message = message.encode("utf-8") - if binary: - await self._send_frame(message, WSMsgType.BINARY, compress) - else: - await self._send_frame(message, WSMsgType.TEXT, compress) - - async def close(self, code: int = 1000, message: bytes = b"") -> None: - """Close the websocket, sending the specified code and message.""" - if isinstance(message, str): - message = message.encode("utf-8") - try: - await self._send_frame( - PACK_CLOSE_CODE(code) + message, opcode=WSMsgType.CLOSE - ) - finally: - self._closing = True diff --git a/.venv/Lib/site-packages/aiohttp/http_writer.py b/.venv/Lib/site-packages/aiohttp/http_writer.py deleted file mode 100644 index e091447..0000000 --- a/.venv/Lib/site-packages/aiohttp/http_writer.py +++ /dev/null @@ -1,200 +0,0 @@ -"""Http related parsers and protocol.""" - -import asyncio -import zlib -from typing import Any, Awaitable, Callable, NamedTuple, Optional, Union # noqa - -from multidict import CIMultiDict - -from .abc import AbstractStreamWriter -from .base_protocol import BaseProtocol -from .helpers import NO_EXTENSIONS - -__all__ = ("StreamWriter", "HttpVersion", "HttpVersion10", "HttpVersion11") - - -class HttpVersion(NamedTuple): - major: int - minor: int - - -HttpVersion10 = HttpVersion(1, 0) -HttpVersion11 = HttpVersion(1, 1) - - -_T_OnChunkSent = Optional[Callable[[bytes], Awaitable[None]]] -_T_OnHeadersSent = Optional[Callable[["CIMultiDict[str]"], Awaitable[None]]] - - -class StreamWriter(AbstractStreamWriter): - def __init__( - self, - protocol: BaseProtocol, - loop: asyncio.AbstractEventLoop, - on_chunk_sent: _T_OnChunkSent = None, - on_headers_sent: _T_OnHeadersSent = None, - ) -> None: - self._protocol = protocol - self._transport = protocol.transport - - self.loop = loop - self.length = None - self.chunked = False - self.buffer_size = 0 - self.output_size = 0 - - self._eof = False - self._compress = None # type: Any - self._drain_waiter = None - - self._on_chunk_sent = on_chunk_sent # type: _T_OnChunkSent - self._on_headers_sent = on_headers_sent # type: _T_OnHeadersSent - - @property - def transport(self) -> Optional[asyncio.Transport]: - return self._transport - - @property - def protocol(self) -> BaseProtocol: - return self._protocol - - def enable_chunking(self) -> None: - self.chunked = True - - def enable_compression( - self, encoding: str = "deflate", strategy: int = zlib.Z_DEFAULT_STRATEGY - ) -> None: - zlib_mode = 16 + zlib.MAX_WBITS if encoding == "gzip" else zlib.MAX_WBITS - self._compress = zlib.compressobj(wbits=zlib_mode, strategy=strategy) - - def _write(self, chunk: bytes) -> None: - size = len(chunk) - self.buffer_size += size - self.output_size += size - - if self._transport is None or self._transport.is_closing(): - raise ConnectionResetError("Cannot write to closing transport") - self._transport.write(chunk) - - async def write( - self, chunk: bytes, *, drain: bool = True, LIMIT: int = 0x10000 - ) -> None: - """Writes chunk of data to a stream. - - write_eof() indicates end of stream. - writer can't be used after write_eof() method being called. - write() return drain future. - """ - if self._on_chunk_sent is not None: - await self._on_chunk_sent(chunk) - - if isinstance(chunk, memoryview): - if chunk.nbytes != len(chunk): - # just reshape it - chunk = chunk.cast("c") - - if self._compress is not None: - chunk = self._compress.compress(chunk) - if not chunk: - return - - if self.length is not None: - chunk_len = len(chunk) - if self.length >= chunk_len: - self.length = self.length - chunk_len - else: - chunk = chunk[: self.length] - self.length = 0 - if not chunk: - return - - if chunk: - if self.chunked: - chunk_len_pre = ("%x\r\n" % len(chunk)).encode("ascii") - chunk = chunk_len_pre + chunk + b"\r\n" - - self._write(chunk) - - if self.buffer_size > LIMIT and drain: - self.buffer_size = 0 - await self.drain() - - async def write_headers( - self, status_line: str, headers: "CIMultiDict[str]" - ) -> None: - """Write request/response status and headers.""" - if self._on_headers_sent is not None: - await self._on_headers_sent(headers) - - # status + headers - buf = _serialize_headers(status_line, headers) - self._write(buf) - - async def write_eof(self, chunk: bytes = b"") -> None: - if self._eof: - return - - if chunk and self._on_chunk_sent is not None: - await self._on_chunk_sent(chunk) - - if self._compress: - if chunk: - chunk = self._compress.compress(chunk) - - chunk = chunk + self._compress.flush() - if chunk and self.chunked: - chunk_len = ("%x\r\n" % len(chunk)).encode("ascii") - chunk = chunk_len + chunk + b"\r\n0\r\n\r\n" - else: - if self.chunked: - if chunk: - chunk_len = ("%x\r\n" % len(chunk)).encode("ascii") - chunk = chunk_len + chunk + b"\r\n0\r\n\r\n" - else: - chunk = b"0\r\n\r\n" - - if chunk: - self._write(chunk) - - await self.drain() - - self._eof = True - self._transport = None - - async def drain(self) -> None: - """Flush the write buffer. - - The intended use is to write - - await w.write(data) - await w.drain() - """ - if self._protocol.transport is not None: - await self._protocol._drain_helper() - - -def _safe_header(string: str) -> str: - if "\r" in string or "\n" in string: - raise ValueError( - "Newline or carriage return detected in headers. " - "Potential header injection attack." - ) - return string - - -def _py_serialize_headers(status_line: str, headers: "CIMultiDict[str]") -> bytes: - headers_gen = (_safe_header(k) + ": " + _safe_header(v) for k, v in headers.items()) - line = status_line + "\r\n" + "\r\n".join(headers_gen) + "\r\n\r\n" - return line.encode("utf-8") - - -_serialize_headers = _py_serialize_headers - -try: - import aiohttp._http_writer as _http_writer # type: ignore[import] - - _c_serialize_headers = _http_writer._serialize_headers - if not NO_EXTENSIONS: - _serialize_headers = _c_serialize_headers -except ImportError: - pass diff --git a/.venv/Lib/site-packages/aiohttp/locks.py b/.venv/Lib/site-packages/aiohttp/locks.py deleted file mode 100644 index df65e3e..0000000 --- a/.venv/Lib/site-packages/aiohttp/locks.py +++ /dev/null @@ -1,41 +0,0 @@ -import asyncio -import collections -from typing import Any, Deque, Optional - - -class EventResultOrError: - """Event asyncio lock helper class. - - Wraps the Event asyncio lock allowing either to awake the - locked Tasks without any error or raising an exception. - - thanks to @vorpalsmith for the simple design. - """ - - def __init__(self, loop: asyncio.AbstractEventLoop) -> None: - self._loop = loop - self._exc = None # type: Optional[BaseException] - self._event = asyncio.Event() - self._waiters = collections.deque() # type: Deque[asyncio.Future[Any]] - - def set(self, exc: Optional[BaseException] = None) -> None: - self._exc = exc - self._event.set() - - async def wait(self) -> Any: - waiter = self._loop.create_task(self._event.wait()) - self._waiters.append(waiter) - try: - val = await waiter - finally: - self._waiters.remove(waiter) - - if self._exc is not None: - raise self._exc - - return val - - def cancel(self) -> None: - """Cancel all waiters""" - for waiter in self._waiters: - waiter.cancel() diff --git a/.venv/Lib/site-packages/aiohttp/log.py b/.venv/Lib/site-packages/aiohttp/log.py deleted file mode 100644 index 3cecea2..0000000 --- a/.venv/Lib/site-packages/aiohttp/log.py +++ /dev/null @@ -1,8 +0,0 @@ -import logging - -access_logger = logging.getLogger("aiohttp.access") -client_logger = logging.getLogger("aiohttp.client") -internal_logger = logging.getLogger("aiohttp.internal") -server_logger = logging.getLogger("aiohttp.server") -web_logger = logging.getLogger("aiohttp.web") -ws_logger = logging.getLogger("aiohttp.websocket") diff --git a/.venv/Lib/site-packages/aiohttp/multipart.py b/.venv/Lib/site-packages/aiohttp/multipart.py deleted file mode 100644 index c84e200..0000000 --- a/.venv/Lib/site-packages/aiohttp/multipart.py +++ /dev/null @@ -1,963 +0,0 @@ -import base64 -import binascii -import json -import re -import uuid -import warnings -import zlib -from collections import deque -from types import TracebackType -from typing import ( - TYPE_CHECKING, - Any, - AsyncIterator, - Deque, - Dict, - Iterator, - List, - Mapping, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) -from urllib.parse import parse_qsl, unquote, urlencode - -from multidict import CIMultiDict, CIMultiDictProxy, MultiMapping - -from .hdrs import ( - CONTENT_DISPOSITION, - CONTENT_ENCODING, - CONTENT_LENGTH, - CONTENT_TRANSFER_ENCODING, - CONTENT_TYPE, -) -from .helpers import CHAR, TOKEN, parse_mimetype, reify -from .http import HeadersParser -from .payload import ( - JsonPayload, - LookupError, - Order, - Payload, - StringPayload, - get_payload, - payload_type, -) -from .streams import StreamReader - -__all__ = ( - "MultipartReader", - "MultipartWriter", - "BodyPartReader", - "BadContentDispositionHeader", - "BadContentDispositionParam", - "parse_content_disposition", - "content_disposition_filename", -) - - -if TYPE_CHECKING: # pragma: no cover - from .client_reqrep import ClientResponse - - -class BadContentDispositionHeader(RuntimeWarning): - pass - - -class BadContentDispositionParam(RuntimeWarning): - pass - - -def parse_content_disposition( - header: Optional[str], -) -> Tuple[Optional[str], Dict[str, str]]: - def is_token(string: str) -> bool: - return bool(string) and TOKEN >= set(string) - - def is_quoted(string: str) -> bool: - return string[0] == string[-1] == '"' - - def is_rfc5987(string: str) -> bool: - return is_token(string) and string.count("'") == 2 - - def is_extended_param(string: str) -> bool: - return string.endswith("*") - - def is_continuous_param(string: str) -> bool: - pos = string.find("*") + 1 - if not pos: - return False - substring = string[pos:-1] if string.endswith("*") else string[pos:] - return substring.isdigit() - - def unescape(text: str, *, chars: str = "".join(map(re.escape, CHAR))) -> str: - return re.sub(f"\\\\([{chars}])", "\\1", text) - - if not header: - return None, {} - - disptype, *parts = header.split(";") - if not is_token(disptype): - warnings.warn(BadContentDispositionHeader(header)) - return None, {} - - params = {} # type: Dict[str, str] - while parts: - item = parts.pop(0) - - if "=" not in item: - warnings.warn(BadContentDispositionHeader(header)) - return None, {} - - key, value = item.split("=", 1) - key = key.lower().strip() - value = value.lstrip() - - if key in params: - warnings.warn(BadContentDispositionHeader(header)) - return None, {} - - if not is_token(key): - warnings.warn(BadContentDispositionParam(item)) - continue - - elif is_continuous_param(key): - if is_quoted(value): - value = unescape(value[1:-1]) - elif not is_token(value): - warnings.warn(BadContentDispositionParam(item)) - continue - - elif is_extended_param(key): - if is_rfc5987(value): - encoding, _, value = value.split("'", 2) - encoding = encoding or "utf-8" - else: - warnings.warn(BadContentDispositionParam(item)) - continue - - try: - value = unquote(value, encoding, "strict") - except UnicodeDecodeError: # pragma: nocover - warnings.warn(BadContentDispositionParam(item)) - continue - - else: - failed = True - if is_quoted(value): - failed = False - value = unescape(value[1:-1].lstrip("\\/")) - elif is_token(value): - failed = False - elif parts: - # maybe just ; in filename, in any case this is just - # one case fix, for proper fix we need to redesign parser - _value = f"{value};{parts[0]}" - if is_quoted(_value): - parts.pop(0) - value = unescape(_value[1:-1].lstrip("\\/")) - failed = False - - if failed: - warnings.warn(BadContentDispositionHeader(header)) - return None, {} - - params[key] = value - - return disptype.lower(), params - - -def content_disposition_filename( - params: Mapping[str, str], name: str = "filename" -) -> Optional[str]: - name_suf = "%s*" % name - if not params: - return None - elif name_suf in params: - return params[name_suf] - elif name in params: - return params[name] - else: - parts = [] - fnparams = sorted( - (key, value) for key, value in params.items() if key.startswith(name_suf) - ) - for num, (key, value) in enumerate(fnparams): - _, tail = key.split("*", 1) - if tail.endswith("*"): - tail = tail[:-1] - if tail == str(num): - parts.append(value) - else: - break - if not parts: - return None - value = "".join(parts) - if "'" in value: - encoding, _, value = value.split("'", 2) - encoding = encoding or "utf-8" - return unquote(value, encoding, "strict") - return value - - -class MultipartResponseWrapper: - """Wrapper around the MultipartReader. - - It takes care about - underlying connection and close it when it needs in. - """ - - def __init__( - self, - resp: "ClientResponse", - stream: "MultipartReader", - ) -> None: - self.resp = resp - self.stream = stream - - def __aiter__(self) -> "MultipartResponseWrapper": - return self - - async def __anext__( - self, - ) -> Union["MultipartReader", "BodyPartReader"]: - part = await self.next() - if part is None: - raise StopAsyncIteration - return part - - def at_eof(self) -> bool: - """Returns True when all response data had been read.""" - return self.resp.content.at_eof() - - async def next( - self, - ) -> Optional[Union["MultipartReader", "BodyPartReader"]]: - """Emits next multipart reader object.""" - item = await self.stream.next() - if self.stream.at_eof(): - await self.release() - return item - - async def release(self) -> None: - """Release the connection gracefully. - - All remaining content is read to the void. - """ - await self.resp.release() - - -class BodyPartReader: - """Multipart reader for single body part.""" - - chunk_size = 8192 - - def __init__( - self, boundary: bytes, headers: "CIMultiDictProxy[str]", content: StreamReader - ) -> None: - self.headers = headers - self._boundary = boundary - self._content = content - self._at_eof = False - length = self.headers.get(CONTENT_LENGTH, None) - self._length = int(length) if length is not None else None - self._read_bytes = 0 - # TODO: typeing.Deque is not supported by Python 3.5 - self._unread: Deque[bytes] = deque() - self._prev_chunk = None # type: Optional[bytes] - self._content_eof = 0 - self._cache = {} # type: Dict[str, Any] - - def __aiter__(self) -> AsyncIterator["BodyPartReader"]: - return self # type: ignore[return-value] - - async def __anext__(self) -> bytes: - part = await self.next() - if part is None: - raise StopAsyncIteration - return part - - async def next(self) -> Optional[bytes]: - item = await self.read() - if not item: - return None - return item - - async def read(self, *, decode: bool = False) -> bytes: - """Reads body part data. - - decode: Decodes data following by encoding - method from Content-Encoding header. If it missed - data remains untouched - """ - if self._at_eof: - return b"" - data = bytearray() - while not self._at_eof: - data.extend(await self.read_chunk(self.chunk_size)) - if decode: - return self.decode(data) - return data - - async def read_chunk(self, size: int = chunk_size) -> bytes: - """Reads body part content chunk of the specified size. - - size: chunk size - """ - if self._at_eof: - return b"" - if self._length: - chunk = await self._read_chunk_from_length(size) - else: - chunk = await self._read_chunk_from_stream(size) - - self._read_bytes += len(chunk) - if self._read_bytes == self._length: - self._at_eof = True - if self._at_eof: - clrf = await self._content.readline() - assert ( - b"\r\n" == clrf - ), "reader did not read all the data or it is malformed" - return chunk - - async def _read_chunk_from_length(self, size: int) -> bytes: - # Reads body part content chunk of the specified size. - # The body part must has Content-Length header with proper value. - assert self._length is not None, "Content-Length required for chunked read" - chunk_size = min(size, self._length - self._read_bytes) - chunk = await self._content.read(chunk_size) - return chunk - - async def _read_chunk_from_stream(self, size: int) -> bytes: - # Reads content chunk of body part with unknown length. - # The Content-Length header for body part is not necessary. - assert ( - size >= len(self._boundary) + 2 - ), "Chunk size must be greater or equal than boundary length + 2" - first_chunk = self._prev_chunk is None - if first_chunk: - self._prev_chunk = await self._content.read(size) - - chunk = await self._content.read(size) - self._content_eof += int(self._content.at_eof()) - assert self._content_eof < 3, "Reading after EOF" - assert self._prev_chunk is not None - window = self._prev_chunk + chunk - sub = b"\r\n" + self._boundary - if first_chunk: - idx = window.find(sub) - else: - idx = window.find(sub, max(0, len(self._prev_chunk) - len(sub))) - if idx >= 0: - # pushing boundary back to content - with warnings.catch_warnings(): - warnings.filterwarnings("ignore", category=DeprecationWarning) - self._content.unread_data(window[idx:]) - if size > idx: - self._prev_chunk = self._prev_chunk[:idx] - chunk = window[len(self._prev_chunk) : idx] - if not chunk: - self._at_eof = True - result = self._prev_chunk - self._prev_chunk = chunk - return result - - async def readline(self) -> bytes: - """Reads body part by line by line.""" - if self._at_eof: - return b"" - - if self._unread: - line = self._unread.popleft() - else: - line = await self._content.readline() - - if line.startswith(self._boundary): - # the very last boundary may not come with \r\n, - # so set single rules for everyone - sline = line.rstrip(b"\r\n") - boundary = self._boundary - last_boundary = self._boundary + b"--" - # ensure that we read exactly the boundary, not something alike - if sline == boundary or sline == last_boundary: - self._at_eof = True - self._unread.append(line) - return b"" - else: - next_line = await self._content.readline() - if next_line.startswith(self._boundary): - line = line[:-2] # strip CRLF but only once - self._unread.append(next_line) - - return line - - async def release(self) -> None: - """Like read(), but reads all the data to the void.""" - if self._at_eof: - return - while not self._at_eof: - await self.read_chunk(self.chunk_size) - - async def text(self, *, encoding: Optional[str] = None) -> str: - """Like read(), but assumes that body part contains text data.""" - data = await self.read(decode=True) - # see https://www.w3.org/TR/html5/forms.html#multipart/form-data-encoding-algorithm # NOQA - # and https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-send # NOQA - encoding = encoding or self.get_charset(default="utf-8") - return data.decode(encoding) - - async def json(self, *, encoding: Optional[str] = None) -> Optional[Dict[str, Any]]: - """Like read(), but assumes that body parts contains JSON data.""" - data = await self.read(decode=True) - if not data: - return None - encoding = encoding or self.get_charset(default="utf-8") - return cast(Dict[str, Any], json.loads(data.decode(encoding))) - - async def form(self, *, encoding: Optional[str] = None) -> List[Tuple[str, str]]: - """Like read(), but assumes that body parts contain form urlencoded data.""" - data = await self.read(decode=True) - if not data: - return [] - if encoding is not None: - real_encoding = encoding - else: - real_encoding = self.get_charset(default="utf-8") - return parse_qsl( - data.rstrip().decode(real_encoding), - keep_blank_values=True, - encoding=real_encoding, - ) - - def at_eof(self) -> bool: - """Returns True if the boundary was reached or False otherwise.""" - return self._at_eof - - def decode(self, data: bytes) -> bytes: - """Decodes data. - - Decoding is done according the specified Content-Encoding - or Content-Transfer-Encoding headers value. - """ - if CONTENT_TRANSFER_ENCODING in self.headers: - data = self._decode_content_transfer(data) - if CONTENT_ENCODING in self.headers: - return self._decode_content(data) - return data - - def _decode_content(self, data: bytes) -> bytes: - encoding = self.headers.get(CONTENT_ENCODING, "").lower() - - if encoding == "deflate": - return zlib.decompress(data, -zlib.MAX_WBITS) - elif encoding == "gzip": - return zlib.decompress(data, 16 + zlib.MAX_WBITS) - elif encoding == "identity": - return data - else: - raise RuntimeError(f"unknown content encoding: {encoding}") - - def _decode_content_transfer(self, data: bytes) -> bytes: - encoding = self.headers.get(CONTENT_TRANSFER_ENCODING, "").lower() - - if encoding == "base64": - return base64.b64decode(data) - elif encoding == "quoted-printable": - return binascii.a2b_qp(data) - elif encoding in ("binary", "8bit", "7bit"): - return data - else: - raise RuntimeError( - "unknown content transfer encoding: {}" "".format(encoding) - ) - - def get_charset(self, default: str) -> str: - """Returns charset parameter from Content-Type header or default.""" - ctype = self.headers.get(CONTENT_TYPE, "") - mimetype = parse_mimetype(ctype) - return mimetype.parameters.get("charset", default) - - @reify - def name(self) -> Optional[str]: - """Returns name specified in Content-Disposition header. - - If the header is missing or malformed, returns None. - """ - _, params = parse_content_disposition(self.headers.get(CONTENT_DISPOSITION)) - return content_disposition_filename(params, "name") - - @reify - def filename(self) -> Optional[str]: - """Returns filename specified in Content-Disposition header. - - Returns None if the header is missing or malformed. - """ - _, params = parse_content_disposition(self.headers.get(CONTENT_DISPOSITION)) - return content_disposition_filename(params, "filename") - - -@payload_type(BodyPartReader, order=Order.try_first) -class BodyPartReaderPayload(Payload): - def __init__(self, value: BodyPartReader, *args: Any, **kwargs: Any) -> None: - super().__init__(value, *args, **kwargs) - - params = {} # type: Dict[str, str] - if value.name is not None: - params["name"] = value.name - if value.filename is not None: - params["filename"] = value.filename - - if params: - self.set_content_disposition("attachment", True, **params) - - async def write(self, writer: Any) -> None: - field = self._value - chunk = await field.read_chunk(size=2 ** 16) - while chunk: - await writer.write(field.decode(chunk)) - chunk = await field.read_chunk(size=2 ** 16) - - -class MultipartReader: - """Multipart body reader.""" - - #: Response wrapper, used when multipart readers constructs from response. - response_wrapper_cls = MultipartResponseWrapper - #: Multipart reader class, used to handle multipart/* body parts. - #: None points to type(self) - multipart_reader_cls = None - #: Body part reader class for non multipart/* content types. - part_reader_cls = BodyPartReader - - def __init__(self, headers: Mapping[str, str], content: StreamReader) -> None: - self.headers = headers - self._boundary = ("--" + self._get_boundary()).encode() - self._content = content - self._last_part = ( - None - ) # type: Optional[Union['MultipartReader', BodyPartReader]] - self._at_eof = False - self._at_bof = True - self._unread = [] # type: List[bytes] - - def __aiter__( - self, - ) -> AsyncIterator["BodyPartReader"]: - return self # type: ignore[return-value] - - async def __anext__( - self, - ) -> Optional[Union["MultipartReader", BodyPartReader]]: - part = await self.next() - if part is None: - raise StopAsyncIteration - return part - - @classmethod - def from_response( - cls, - response: "ClientResponse", - ) -> MultipartResponseWrapper: - """Constructs reader instance from HTTP response. - - :param response: :class:`~aiohttp.client.ClientResponse` instance - """ - obj = cls.response_wrapper_cls( - response, cls(response.headers, response.content) - ) - return obj - - def at_eof(self) -> bool: - """Returns True if the final boundary was reached, false otherwise.""" - return self._at_eof - - async def next( - self, - ) -> Optional[Union["MultipartReader", BodyPartReader]]: - """Emits the next multipart body part.""" - # So, if we're at BOF, we need to skip till the boundary. - if self._at_eof: - return None - await self._maybe_release_last_part() - if self._at_bof: - await self._read_until_first_boundary() - self._at_bof = False - else: - await self._read_boundary() - if self._at_eof: # we just read the last boundary, nothing to do there - return None - self._last_part = await self.fetch_next_part() - return self._last_part - - async def release(self) -> None: - """Reads all the body parts to the void till the final boundary.""" - while not self._at_eof: - item = await self.next() - if item is None: - break - await item.release() - - async def fetch_next_part( - self, - ) -> Union["MultipartReader", BodyPartReader]: - """Returns the next body part reader.""" - headers = await self._read_headers() - return self._get_part_reader(headers) - - def _get_part_reader( - self, - headers: "CIMultiDictProxy[str]", - ) -> Union["MultipartReader", BodyPartReader]: - """Dispatches the response by the `Content-Type` header. - - Returns a suitable reader instance. - - :param dict headers: Response headers - """ - ctype = headers.get(CONTENT_TYPE, "") - mimetype = parse_mimetype(ctype) - - if mimetype.type == "multipart": - if self.multipart_reader_cls is None: - return type(self)(headers, self._content) - return self.multipart_reader_cls(headers, self._content) - else: - return self.part_reader_cls(self._boundary, headers, self._content) - - def _get_boundary(self) -> str: - mimetype = parse_mimetype(self.headers[CONTENT_TYPE]) - - assert mimetype.type == "multipart", "multipart/* content type expected" - - if "boundary" not in mimetype.parameters: - raise ValueError( - "boundary missed for Content-Type: %s" % self.headers[CONTENT_TYPE] - ) - - boundary = mimetype.parameters["boundary"] - if len(boundary) > 70: - raise ValueError("boundary %r is too long (70 chars max)" % boundary) - - return boundary - - async def _readline(self) -> bytes: - if self._unread: - return self._unread.pop() - return await self._content.readline() - - async def _read_until_first_boundary(self) -> None: - while True: - chunk = await self._readline() - if chunk == b"": - raise ValueError( - "Could not find starting boundary %r" % (self._boundary) - ) - chunk = chunk.rstrip() - if chunk == self._boundary: - return - elif chunk == self._boundary + b"--": - self._at_eof = True - return - - async def _read_boundary(self) -> None: - chunk = (await self._readline()).rstrip() - if chunk == self._boundary: - pass - elif chunk == self._boundary + b"--": - self._at_eof = True - epilogue = await self._readline() - next_line = await self._readline() - - # the epilogue is expected and then either the end of input or the - # parent multipart boundary, if the parent boundary is found then - # it should be marked as unread and handed to the parent for - # processing - if next_line[:2] == b"--": - self._unread.append(next_line) - # otherwise the request is likely missing an epilogue and both - # lines should be passed to the parent for processing - # (this handles the old behavior gracefully) - else: - self._unread.extend([next_line, epilogue]) - else: - raise ValueError(f"Invalid boundary {chunk!r}, expected {self._boundary!r}") - - async def _read_headers(self) -> "CIMultiDictProxy[str]": - lines = [b""] - while True: - chunk = await self._content.readline() - chunk = chunk.strip() - lines.append(chunk) - if not chunk: - break - parser = HeadersParser() - headers, raw_headers = parser.parse_headers(lines) - return headers - - async def _maybe_release_last_part(self) -> None: - """Ensures that the last read body part is read completely.""" - if self._last_part is not None: - if not self._last_part.at_eof(): - await self._last_part.release() - self._unread.extend(self._last_part._unread) - self._last_part = None - - -_Part = Tuple[Payload, str, str] - - -class MultipartWriter(Payload): - """Multipart body writer.""" - - def __init__(self, subtype: str = "mixed", boundary: Optional[str] = None) -> None: - boundary = boundary if boundary is not None else uuid.uuid4().hex - # The underlying Payload API demands a str (utf-8), not bytes, - # so we need to ensure we don't lose anything during conversion. - # As a result, require the boundary to be ASCII only. - # In both situations. - - try: - self._boundary = boundary.encode("ascii") - except UnicodeEncodeError: - raise ValueError("boundary should contain ASCII only chars") from None - ctype = f"multipart/{subtype}; boundary={self._boundary_value}" - - super().__init__(None, content_type=ctype) - - self._parts = [] # type: List[_Part] - - def __enter__(self) -> "MultipartWriter": - return self - - def __exit__( - self, - exc_type: Optional[Type[BaseException]], - exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType], - ) -> None: - pass - - def __iter__(self) -> Iterator[_Part]: - return iter(self._parts) - - def __len__(self) -> int: - return len(self._parts) - - def __bool__(self) -> bool: - return True - - _valid_tchar_regex = re.compile(br"\A[!#$%&'*+\-.^_`|~\w]+\Z") - _invalid_qdtext_char_regex = re.compile(br"[\x00-\x08\x0A-\x1F\x7F]") - - @property - def _boundary_value(self) -> str: - """Wrap boundary parameter value in quotes, if necessary. - - Reads self.boundary and returns a unicode sting. - """ - # Refer to RFCs 7231, 7230, 5234. - # - # parameter = token "=" ( token / quoted-string ) - # token = 1*tchar - # quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE - # qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text - # obs-text = %x80-FF - # quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - # tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" - # / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" - # / DIGIT / ALPHA - # ; any VCHAR, except delimiters - # VCHAR = %x21-7E - value = self._boundary - if re.match(self._valid_tchar_regex, value): - return value.decode("ascii") # cannot fail - - if re.search(self._invalid_qdtext_char_regex, value): - raise ValueError("boundary value contains invalid characters") - - # escape %x5C and %x22 - quoted_value_content = value.replace(b"\\", b"\\\\") - quoted_value_content = quoted_value_content.replace(b'"', b'\\"') - - return '"' + quoted_value_content.decode("ascii") + '"' - - @property - def boundary(self) -> str: - return self._boundary.decode("ascii") - - def append(self, obj: Any, headers: Optional[MultiMapping[str]] = None) -> Payload: - if headers is None: - headers = CIMultiDict() - - if isinstance(obj, Payload): - obj.headers.update(headers) - return self.append_payload(obj) - else: - try: - payload = get_payload(obj, headers=headers) - except LookupError: - raise TypeError("Cannot create payload from %r" % obj) - else: - return self.append_payload(payload) - - def append_payload(self, payload: Payload) -> Payload: - """Adds a new body part to multipart writer.""" - # compression - encoding = payload.headers.get( - CONTENT_ENCODING, - "", - ).lower() # type: Optional[str] - if encoding and encoding not in ("deflate", "gzip", "identity"): - raise RuntimeError(f"unknown content encoding: {encoding}") - if encoding == "identity": - encoding = None - - # te encoding - te_encoding = payload.headers.get( - CONTENT_TRANSFER_ENCODING, - "", - ).lower() # type: Optional[str] - if te_encoding not in ("", "base64", "quoted-printable", "binary"): - raise RuntimeError( - "unknown content transfer encoding: {}" "".format(te_encoding) - ) - if te_encoding == "binary": - te_encoding = None - - # size - size = payload.size - if size is not None and not (encoding or te_encoding): - payload.headers[CONTENT_LENGTH] = str(size) - - self._parts.append((payload, encoding, te_encoding)) # type: ignore[arg-type] - return payload - - def append_json( - self, obj: Any, headers: Optional[MultiMapping[str]] = None - ) -> Payload: - """Helper to append JSON part.""" - if headers is None: - headers = CIMultiDict() - - return self.append_payload(JsonPayload(obj, headers=headers)) - - def append_form( - self, - obj: Union[Sequence[Tuple[str, str]], Mapping[str, str]], - headers: Optional[MultiMapping[str]] = None, - ) -> Payload: - """Helper to append form urlencoded part.""" - assert isinstance(obj, (Sequence, Mapping)) - - if headers is None: - headers = CIMultiDict() - - if isinstance(obj, Mapping): - obj = list(obj.items()) - data = urlencode(obj, doseq=True) - - return self.append_payload( - StringPayload( - data, headers=headers, content_type="application/x-www-form-urlencoded" - ) - ) - - @property - def size(self) -> Optional[int]: - """Size of the payload.""" - total = 0 - for part, encoding, te_encoding in self._parts: - if encoding or te_encoding or part.size is None: - return None - - total += int( - 2 - + len(self._boundary) - + 2 - + part.size # b'--'+self._boundary+b'\r\n' - + len(part._binary_headers) - + 2 # b'\r\n' - ) - - total += 2 + len(self._boundary) + 4 # b'--'+self._boundary+b'--\r\n' - return total - - async def write(self, writer: Any, close_boundary: bool = True) -> None: - """Write body.""" - for part, encoding, te_encoding in self._parts: - await writer.write(b"--" + self._boundary + b"\r\n") - await writer.write(part._binary_headers) - - if encoding or te_encoding: - w = MultipartPayloadWriter(writer) - if encoding: - w.enable_compression(encoding) - if te_encoding: - w.enable_encoding(te_encoding) - await part.write(w) # type: ignore[arg-type] - await w.write_eof() - else: - await part.write(writer) - - await writer.write(b"\r\n") - - if close_boundary: - await writer.write(b"--" + self._boundary + b"--\r\n") - - -class MultipartPayloadWriter: - def __init__(self, writer: Any) -> None: - self._writer = writer - self._encoding = None # type: Optional[str] - self._compress = None # type: Any - self._encoding_buffer = None # type: Optional[bytearray] - - def enable_encoding(self, encoding: str) -> None: - if encoding == "base64": - self._encoding = encoding - self._encoding_buffer = bytearray() - elif encoding == "quoted-printable": - self._encoding = "quoted-printable" - - def enable_compression( - self, encoding: str = "deflate", strategy: int = zlib.Z_DEFAULT_STRATEGY - ) -> None: - zlib_mode = 16 + zlib.MAX_WBITS if encoding == "gzip" else -zlib.MAX_WBITS - self._compress = zlib.compressobj(wbits=zlib_mode, strategy=strategy) - - async def write_eof(self) -> None: - if self._compress is not None: - chunk = self._compress.flush() - if chunk: - self._compress = None - await self.write(chunk) - - if self._encoding == "base64": - if self._encoding_buffer: - await self._writer.write(base64.b64encode(self._encoding_buffer)) - - async def write(self, chunk: bytes) -> None: - if self._compress is not None: - if chunk: - chunk = self._compress.compress(chunk) - if not chunk: - return - - if self._encoding == "base64": - buf = self._encoding_buffer - assert buf is not None - buf.extend(chunk) - - if buf: - div, mod = divmod(len(buf), 3) - enc_chunk, self._encoding_buffer = (buf[: div * 3], buf[div * 3 :]) - if enc_chunk: - b64chunk = base64.b64encode(enc_chunk) - await self._writer.write(b64chunk) - elif self._encoding == "quoted-printable": - await self._writer.write(binascii.b2a_qp(chunk)) - else: - await self._writer.write(chunk) diff --git a/.venv/Lib/site-packages/aiohttp/payload.py b/.venv/Lib/site-packages/aiohttp/payload.py deleted file mode 100644 index 2ee90be..0000000 --- a/.venv/Lib/site-packages/aiohttp/payload.py +++ /dev/null @@ -1,465 +0,0 @@ -import asyncio -import enum -import io -import json -import mimetypes -import os -import warnings -from abc import ABC, abstractmethod -from itertools import chain -from typing import ( - IO, - TYPE_CHECKING, - Any, - ByteString, - Dict, - Iterable, - Optional, - TextIO, - Tuple, - Type, - Union, -) - -from multidict import CIMultiDict - -from . import hdrs -from .abc import AbstractStreamWriter -from .helpers import ( - PY_36, - content_disposition_header, - guess_filename, - parse_mimetype, - sentinel, -) -from .streams import StreamReader -from .typedefs import Final, JSONEncoder, _CIMultiDict - -__all__ = ( - "PAYLOAD_REGISTRY", - "get_payload", - "payload_type", - "Payload", - "BytesPayload", - "StringPayload", - "IOBasePayload", - "BytesIOPayload", - "BufferedReaderPayload", - "TextIOPayload", - "StringIOPayload", - "JsonPayload", - "AsyncIterablePayload", -) - -TOO_LARGE_BYTES_BODY: Final[int] = 2 ** 20 # 1 MB - -if TYPE_CHECKING: # pragma: no cover - from typing import List - - -class LookupError(Exception): - pass - - -class Order(str, enum.Enum): - normal = "normal" - try_first = "try_first" - try_last = "try_last" - - -def get_payload(data: Any, *args: Any, **kwargs: Any) -> "Payload": - return PAYLOAD_REGISTRY.get(data, *args, **kwargs) - - -def register_payload( - factory: Type["Payload"], type: Any, *, order: Order = Order.normal -) -> None: - PAYLOAD_REGISTRY.register(factory, type, order=order) - - -class payload_type: - def __init__(self, type: Any, *, order: Order = Order.normal) -> None: - self.type = type - self.order = order - - def __call__(self, factory: Type["Payload"]) -> Type["Payload"]: - register_payload(factory, self.type, order=self.order) - return factory - - -PayloadType = Type["Payload"] -_PayloadRegistryItem = Tuple[PayloadType, Any] - - -class PayloadRegistry: - """Payload registry. - - note: we need zope.interface for more efficient adapter search - """ - - def __init__(self) -> None: - self._first = [] # type: List[_PayloadRegistryItem] - self._normal = [] # type: List[_PayloadRegistryItem] - self._last = [] # type: List[_PayloadRegistryItem] - - def get( - self, - data: Any, - *args: Any, - _CHAIN: "Type[chain[_PayloadRegistryItem]]" = chain, - **kwargs: Any, - ) -> "Payload": - if isinstance(data, Payload): - return data - for factory, type in _CHAIN(self._first, self._normal, self._last): - if isinstance(data, type): - return factory(data, *args, **kwargs) - - raise LookupError() - - def register( - self, factory: PayloadType, type: Any, *, order: Order = Order.normal - ) -> None: - if order is Order.try_first: - self._first.append((factory, type)) - elif order is Order.normal: - self._normal.append((factory, type)) - elif order is Order.try_last: - self._last.append((factory, type)) - else: - raise ValueError(f"Unsupported order {order!r}") - - -class Payload(ABC): - - _default_content_type = "application/octet-stream" # type: str - _size = None # type: Optional[int] - - def __init__( - self, - value: Any, - headers: Optional[ - Union[_CIMultiDict, Dict[str, str], Iterable[Tuple[str, str]]] - ] = None, - content_type: Optional[str] = sentinel, - filename: Optional[str] = None, - encoding: Optional[str] = None, - **kwargs: Any, - ) -> None: - self._encoding = encoding - self._filename = filename - self._headers = CIMultiDict() # type: _CIMultiDict - self._value = value - if content_type is not sentinel and content_type is not None: - self._headers[hdrs.CONTENT_TYPE] = content_type - elif self._filename is not None: - content_type = mimetypes.guess_type(self._filename)[0] - if content_type is None: - content_type = self._default_content_type - self._headers[hdrs.CONTENT_TYPE] = content_type - else: - self._headers[hdrs.CONTENT_TYPE] = self._default_content_type - self._headers.update(headers or {}) - - @property - def size(self) -> Optional[int]: - """Size of the payload.""" - return self._size - - @property - def filename(self) -> Optional[str]: - """Filename of the payload.""" - return self._filename - - @property - def headers(self) -> _CIMultiDict: - """Custom item headers""" - return self._headers - - @property - def _binary_headers(self) -> bytes: - return ( - "".join([k + ": " + v + "\r\n" for k, v in self.headers.items()]).encode( - "utf-8" - ) - + b"\r\n" - ) - - @property - def encoding(self) -> Optional[str]: - """Payload encoding""" - return self._encoding - - @property - def content_type(self) -> str: - """Content type""" - return self._headers[hdrs.CONTENT_TYPE] - - def set_content_disposition( - self, - disptype: str, - quote_fields: bool = True, - _charset: str = "utf-8", - **params: Any, - ) -> None: - """Sets ``Content-Disposition`` header.""" - self._headers[hdrs.CONTENT_DISPOSITION] = content_disposition_header( - disptype, quote_fields=quote_fields, _charset=_charset, **params - ) - - @abstractmethod - async def write(self, writer: AbstractStreamWriter) -> None: - """Write payload. - - writer is an AbstractStreamWriter instance: - """ - - -class BytesPayload(Payload): - def __init__(self, value: ByteString, *args: Any, **kwargs: Any) -> None: - if not isinstance(value, (bytes, bytearray, memoryview)): - raise TypeError(f"value argument must be byte-ish, not {type(value)!r}") - - if "content_type" not in kwargs: - kwargs["content_type"] = "application/octet-stream" - - super().__init__(value, *args, **kwargs) - - if isinstance(value, memoryview): - self._size = value.nbytes - else: - self._size = len(value) - - if self._size > TOO_LARGE_BYTES_BODY: - if PY_36: - kwargs = {"source": self} - else: - kwargs = {} - warnings.warn( - "Sending a large body directly with raw bytes might" - " lock the event loop. You should probably pass an " - "io.BytesIO object instead", - ResourceWarning, - **kwargs, - ) - - async def write(self, writer: AbstractStreamWriter) -> None: - await writer.write(self._value) - - -class StringPayload(BytesPayload): - def __init__( - self, - value: str, - *args: Any, - encoding: Optional[str] = None, - content_type: Optional[str] = None, - **kwargs: Any, - ) -> None: - - if encoding is None: - if content_type is None: - real_encoding = "utf-8" - content_type = "text/plain; charset=utf-8" - else: - mimetype = parse_mimetype(content_type) - real_encoding = mimetype.parameters.get("charset", "utf-8") - else: - if content_type is None: - content_type = "text/plain; charset=%s" % encoding - real_encoding = encoding - - super().__init__( - value.encode(real_encoding), - encoding=real_encoding, - content_type=content_type, - *args, - **kwargs, - ) - - -class StringIOPayload(StringPayload): - def __init__(self, value: IO[str], *args: Any, **kwargs: Any) -> None: - super().__init__(value.read(), *args, **kwargs) - - -class IOBasePayload(Payload): - _value: IO[Any] - - def __init__( - self, value: IO[Any], disposition: str = "attachment", *args: Any, **kwargs: Any - ) -> None: - if "filename" not in kwargs: - kwargs["filename"] = guess_filename(value) - - super().__init__(value, *args, **kwargs) - - if self._filename is not None and disposition is not None: - if hdrs.CONTENT_DISPOSITION not in self.headers: - self.set_content_disposition(disposition, filename=self._filename) - - async def write(self, writer: AbstractStreamWriter) -> None: - loop = asyncio.get_event_loop() - try: - chunk = await loop.run_in_executor(None, self._value.read, 2 ** 16) - while chunk: - await writer.write(chunk) - chunk = await loop.run_in_executor(None, self._value.read, 2 ** 16) - finally: - await loop.run_in_executor(None, self._value.close) - - -class TextIOPayload(IOBasePayload): - _value: TextIO - - def __init__( - self, - value: TextIO, - *args: Any, - encoding: Optional[str] = None, - content_type: Optional[str] = None, - **kwargs: Any, - ) -> None: - - if encoding is None: - if content_type is None: - encoding = "utf-8" - content_type = "text/plain; charset=utf-8" - else: - mimetype = parse_mimetype(content_type) - encoding = mimetype.parameters.get("charset", "utf-8") - else: - if content_type is None: - content_type = "text/plain; charset=%s" % encoding - - super().__init__( - value, - content_type=content_type, - encoding=encoding, - *args, - **kwargs, - ) - - @property - def size(self) -> Optional[int]: - try: - return os.fstat(self._value.fileno()).st_size - self._value.tell() - except OSError: - return None - - async def write(self, writer: AbstractStreamWriter) -> None: - loop = asyncio.get_event_loop() - try: - chunk = await loop.run_in_executor(None, self._value.read, 2 ** 16) - while chunk: - data = ( - chunk.encode(encoding=self._encoding) - if self._encoding - else chunk.encode() - ) - await writer.write(data) - chunk = await loop.run_in_executor(None, self._value.read, 2 ** 16) - finally: - await loop.run_in_executor(None, self._value.close) - - -class BytesIOPayload(IOBasePayload): - @property - def size(self) -> int: - position = self._value.tell() - end = self._value.seek(0, os.SEEK_END) - self._value.seek(position) - return end - position - - -class BufferedReaderPayload(IOBasePayload): - @property - def size(self) -> Optional[int]: - try: - return os.fstat(self._value.fileno()).st_size - self._value.tell() - except OSError: - # data.fileno() is not supported, e.g. - # io.BufferedReader(io.BytesIO(b'data')) - return None - - -class JsonPayload(BytesPayload): - def __init__( - self, - value: Any, - encoding: str = "utf-8", - content_type: str = "application/json", - dumps: JSONEncoder = json.dumps, - *args: Any, - **kwargs: Any, - ) -> None: - - super().__init__( - dumps(value).encode(encoding), - content_type=content_type, - encoding=encoding, - *args, - **kwargs, - ) - - -if TYPE_CHECKING: # pragma: no cover - from typing import AsyncIterable, AsyncIterator - - _AsyncIterator = AsyncIterator[bytes] - _AsyncIterable = AsyncIterable[bytes] -else: - from collections.abc import AsyncIterable, AsyncIterator - - _AsyncIterator = AsyncIterator - _AsyncIterable = AsyncIterable - - -class AsyncIterablePayload(Payload): - - _iter = None # type: Optional[_AsyncIterator] - - def __init__(self, value: _AsyncIterable, *args: Any, **kwargs: Any) -> None: - if not isinstance(value, AsyncIterable): - raise TypeError( - "value argument must support " - "collections.abc.AsyncIterablebe interface, " - "got {!r}".format(type(value)) - ) - - if "content_type" not in kwargs: - kwargs["content_type"] = "application/octet-stream" - - super().__init__(value, *args, **kwargs) - - self._iter = value.__aiter__() - - async def write(self, writer: AbstractStreamWriter) -> None: - if self._iter: - try: - # iter is not None check prevents rare cases - # when the case iterable is used twice - while True: - chunk = await self._iter.__anext__() - await writer.write(chunk) - except StopAsyncIteration: - self._iter = None - - -class StreamReaderPayload(AsyncIterablePayload): - def __init__(self, value: StreamReader, *args: Any, **kwargs: Any) -> None: - super().__init__(value.iter_any(), *args, **kwargs) - - -PAYLOAD_REGISTRY = PayloadRegistry() -PAYLOAD_REGISTRY.register(BytesPayload, (bytes, bytearray, memoryview)) -PAYLOAD_REGISTRY.register(StringPayload, str) -PAYLOAD_REGISTRY.register(StringIOPayload, io.StringIO) -PAYLOAD_REGISTRY.register(TextIOPayload, io.TextIOBase) -PAYLOAD_REGISTRY.register(BytesIOPayload, io.BytesIO) -PAYLOAD_REGISTRY.register(BufferedReaderPayload, (io.BufferedReader, io.BufferedRandom)) -PAYLOAD_REGISTRY.register(IOBasePayload, io.IOBase) -PAYLOAD_REGISTRY.register(StreamReaderPayload, StreamReader) -# try_last for giving a chance to more specialized async interables like -# multidict.BodyPartReaderPayload override the default -PAYLOAD_REGISTRY.register(AsyncIterablePayload, AsyncIterable, order=Order.try_last) diff --git a/.venv/Lib/site-packages/aiohttp/payload_streamer.py b/.venv/Lib/site-packages/aiohttp/payload_streamer.py deleted file mode 100644 index 9f8b8bc..0000000 --- a/.venv/Lib/site-packages/aiohttp/payload_streamer.py +++ /dev/null @@ -1,75 +0,0 @@ -""" -Payload implemenation for coroutines as data provider. - -As a simple case, you can upload data from file:: - - @aiohttp.streamer - async def file_sender(writer, file_name=None): - with open(file_name, 'rb') as f: - chunk = f.read(2**16) - while chunk: - await writer.write(chunk) - - chunk = f.read(2**16) - -Then you can use `file_sender` like this: - - async with session.post('http://httpbin.org/post', - data=file_sender(file_name='huge_file')) as resp: - print(await resp.text()) - -..note:: Coroutine must accept `writer` as first argument - -""" - -import types -import warnings -from typing import Any, Awaitable, Callable, Dict, Tuple - -from .abc import AbstractStreamWriter -from .payload import Payload, payload_type - -__all__ = ("streamer",) - - -class _stream_wrapper: - def __init__( - self, - coro: Callable[..., Awaitable[None]], - args: Tuple[Any, ...], - kwargs: Dict[str, Any], - ) -> None: - self.coro = types.coroutine(coro) - self.args = args - self.kwargs = kwargs - - async def __call__(self, writer: AbstractStreamWriter) -> None: - await self.coro(writer, *self.args, **self.kwargs) # type: ignore[operator] - - -class streamer: - def __init__(self, coro: Callable[..., Awaitable[None]]) -> None: - warnings.warn( - "@streamer is deprecated, use async generators instead", - DeprecationWarning, - stacklevel=2, - ) - self.coro = coro - - def __call__(self, *args: Any, **kwargs: Any) -> _stream_wrapper: - return _stream_wrapper(self.coro, args, kwargs) - - -@payload_type(_stream_wrapper) -class StreamWrapperPayload(Payload): - async def write(self, writer: AbstractStreamWriter) -> None: - await self._value(writer) - - -@payload_type(streamer) -class StreamPayload(StreamWrapperPayload): - def __init__(self, value: Any, *args: Any, **kwargs: Any) -> None: - super().__init__(value(), *args, **kwargs) - - async def write(self, writer: AbstractStreamWriter) -> None: - await self._value(writer) diff --git a/.venv/Lib/site-packages/aiohttp/py.typed b/.venv/Lib/site-packages/aiohttp/py.typed deleted file mode 100644 index f5642f7..0000000 --- a/.venv/Lib/site-packages/aiohttp/py.typed +++ /dev/null @@ -1 +0,0 @@ -Marker diff --git a/.venv/Lib/site-packages/aiohttp/pytest_plugin.py b/.venv/Lib/site-packages/aiohttp/pytest_plugin.py deleted file mode 100644 index dd9a9f6..0000000 --- a/.venv/Lib/site-packages/aiohttp/pytest_plugin.py +++ /dev/null @@ -1,391 +0,0 @@ -import asyncio -import contextlib -import warnings -from collections.abc import Callable -from typing import Any, Awaitable, Callable, Dict, Generator, Optional, Union - -import pytest - -from aiohttp.helpers import PY_37, isasyncgenfunction -from aiohttp.web import Application - -from .test_utils import ( - BaseTestServer, - RawTestServer, - TestClient, - TestServer, - loop_context, - setup_test_loop, - teardown_test_loop, - unused_port as _unused_port, -) - -try: - import uvloop -except ImportError: # pragma: no cover - uvloop = None - -try: - import tokio -except ImportError: # pragma: no cover - tokio = None - -AiohttpClient = Callable[[Union[Application, BaseTestServer]], Awaitable[TestClient]] - - -def pytest_addoption(parser): # type: ignore[no-untyped-def] - parser.addoption( - "--aiohttp-fast", - action="store_true", - default=False, - help="run tests faster by disabling extra checks", - ) - parser.addoption( - "--aiohttp-loop", - action="store", - default="pyloop", - help="run tests with specific loop: pyloop, uvloop, tokio or all", - ) - parser.addoption( - "--aiohttp-enable-loop-debug", - action="store_true", - default=False, - help="enable event loop debug mode", - ) - - -def pytest_fixture_setup(fixturedef): # type: ignore[no-untyped-def] - """Set up pytest fixture. - - Allow fixtures to be coroutines. Run coroutine fixtures in an event loop. - """ - func = fixturedef.func - - if isasyncgenfunction(func): - # async generator fixture - is_async_gen = True - elif asyncio.iscoroutinefunction(func): - # regular async fixture - is_async_gen = False - else: - # not an async fixture, nothing to do - return - - strip_request = False - if "request" not in fixturedef.argnames: - fixturedef.argnames += ("request",) - strip_request = True - - def wrapper(*args, **kwargs): # type: ignore[no-untyped-def] - request = kwargs["request"] - if strip_request: - del kwargs["request"] - - # if neither the fixture nor the test use the 'loop' fixture, - # 'getfixturevalue' will fail because the test is not parameterized - # (this can be removed someday if 'loop' is no longer parameterized) - if "loop" not in request.fixturenames: - raise Exception( - "Asynchronous fixtures must depend on the 'loop' fixture or " - "be used in tests depending from it." - ) - - _loop = request.getfixturevalue("loop") - - if is_async_gen: - # for async generators, we need to advance the generator once, - # then advance it again in a finalizer - gen = func(*args, **kwargs) - - def finalizer(): # type: ignore[no-untyped-def] - try: - return _loop.run_until_complete(gen.__anext__()) - except StopAsyncIteration: - pass - - request.addfinalizer(finalizer) - return _loop.run_until_complete(gen.__anext__()) - else: - return _loop.run_until_complete(func(*args, **kwargs)) - - fixturedef.func = wrapper - - -@pytest.fixture -def fast(request): # type: ignore[no-untyped-def] - """--fast config option""" - return request.config.getoption("--aiohttp-fast") - - -@pytest.fixture -def loop_debug(request): # type: ignore[no-untyped-def] - """--enable-loop-debug config option""" - return request.config.getoption("--aiohttp-enable-loop-debug") - - -@contextlib.contextmanager -def _runtime_warning_context(): # type: ignore[no-untyped-def] - """Context manager which checks for RuntimeWarnings. - - This exists specifically to - avoid "coroutine 'X' was never awaited" warnings being missed. - - If RuntimeWarnings occur in the context a RuntimeError is raised. - """ - with warnings.catch_warnings(record=True) as _warnings: - yield - rw = [ - "{w.filename}:{w.lineno}:{w.message}".format(w=w) - for w in _warnings - if w.category == RuntimeWarning - ] - if rw: - raise RuntimeError( - "{} Runtime Warning{},\n{}".format( - len(rw), "" if len(rw) == 1 else "s", "\n".join(rw) - ) - ) - - -@contextlib.contextmanager -def _passthrough_loop_context(loop, fast=False): # type: ignore[no-untyped-def] - """Passthrough loop context. - - Sets up and tears down a loop unless one is passed in via the loop - argument when it's passed straight through. - """ - if loop: - # loop already exists, pass it straight through - yield loop - else: - # this shadows loop_context's standard behavior - loop = setup_test_loop() - yield loop - teardown_test_loop(loop, fast=fast) - - -def pytest_pycollect_makeitem(collector, name, obj): # type: ignore[no-untyped-def] - """Fix pytest collecting for coroutines.""" - if collector.funcnamefilter(name) and asyncio.iscoroutinefunction(obj): - return list(collector._genfunctions(name, obj)) - - -def pytest_pyfunc_call(pyfuncitem): # type: ignore[no-untyped-def] - """Run coroutines in an event loop instead of a normal function call.""" - fast = pyfuncitem.config.getoption("--aiohttp-fast") - if asyncio.iscoroutinefunction(pyfuncitem.function): - existing_loop = pyfuncitem.funcargs.get( - "proactor_loop" - ) or pyfuncitem.funcargs.get("loop", None) - with _runtime_warning_context(): - with _passthrough_loop_context(existing_loop, fast=fast) as _loop: - testargs = { - arg: pyfuncitem.funcargs[arg] - for arg in pyfuncitem._fixtureinfo.argnames - } - _loop.run_until_complete(pyfuncitem.obj(**testargs)) - - return True - - -def pytest_generate_tests(metafunc): # type: ignore[no-untyped-def] - if "loop_factory" not in metafunc.fixturenames: - return - - loops = metafunc.config.option.aiohttp_loop - avail_factories = {"pyloop": asyncio.DefaultEventLoopPolicy} - - if uvloop is not None: # pragma: no cover - avail_factories["uvloop"] = uvloop.EventLoopPolicy - - if tokio is not None: # pragma: no cover - avail_factories["tokio"] = tokio.EventLoopPolicy - - if loops == "all": - loops = "pyloop,uvloop?,tokio?" - - factories = {} # type: ignore[var-annotated] - for name in loops.split(","): - required = not name.endswith("?") - name = name.strip(" ?") - if name not in avail_factories: # pragma: no cover - if required: - raise ValueError( - "Unknown loop '%s', available loops: %s" - % (name, list(factories.keys())) - ) - else: - continue - factories[name] = avail_factories[name] - metafunc.parametrize( - "loop_factory", list(factories.values()), ids=list(factories.keys()) - ) - - -@pytest.fixture -def loop(loop_factory, fast, loop_debug): # type: ignore[no-untyped-def] - """Return an instance of the event loop.""" - policy = loop_factory() - asyncio.set_event_loop_policy(policy) - with loop_context(fast=fast) as _loop: - if loop_debug: - _loop.set_debug(True) # pragma: no cover - asyncio.set_event_loop(_loop) - yield _loop - - -@pytest.fixture -def proactor_loop(): # type: ignore[no-untyped-def] - if not PY_37: - policy = asyncio.get_event_loop_policy() - policy._loop_factory = asyncio.ProactorEventLoop # type: ignore[attr-defined] - else: - policy = asyncio.WindowsProactorEventLoopPolicy() # type: ignore[attr-defined] - asyncio.set_event_loop_policy(policy) - - with loop_context(policy.new_event_loop) as _loop: - asyncio.set_event_loop(_loop) - yield _loop - - -@pytest.fixture -def unused_port(aiohttp_unused_port): # type: ignore[no-untyped-def] # pragma: no cover - warnings.warn( - "Deprecated, use aiohttp_unused_port fixture instead", - DeprecationWarning, - stacklevel=2, - ) - return aiohttp_unused_port - - -@pytest.fixture -def aiohttp_unused_port(): # type: ignore[no-untyped-def] - """Return a port that is unused on the current host.""" - return _unused_port - - -@pytest.fixture -def aiohttp_server(loop): # type: ignore[no-untyped-def] - """Factory to create a TestServer instance, given an app. - - aiohttp_server(app, **kwargs) - """ - servers = [] - - async def go(app, *, port=None, **kwargs): # type: ignore[no-untyped-def] - server = TestServer(app, port=port) - await server.start_server(loop=loop, **kwargs) - servers.append(server) - return server - - yield go - - async def finalize() -> None: - while servers: - await servers.pop().close() - - loop.run_until_complete(finalize()) - - -@pytest.fixture -def test_server(aiohttp_server): # type: ignore[no-untyped-def] # pragma: no cover - warnings.warn( - "Deprecated, use aiohttp_server fixture instead", - DeprecationWarning, - stacklevel=2, - ) - return aiohttp_server - - -@pytest.fixture -def aiohttp_raw_server(loop): # type: ignore[no-untyped-def] - """Factory to create a RawTestServer instance, given a web handler. - - aiohttp_raw_server(handler, **kwargs) - """ - servers = [] - - async def go(handler, *, port=None, **kwargs): # type: ignore[no-untyped-def] - server = RawTestServer(handler, port=port) - await server.start_server(loop=loop, **kwargs) - servers.append(server) - return server - - yield go - - async def finalize() -> None: - while servers: - await servers.pop().close() - - loop.run_until_complete(finalize()) - - -@pytest.fixture -def raw_test_server( # type: ignore[no-untyped-def] # pragma: no cover - aiohttp_raw_server, -): - warnings.warn( - "Deprecated, use aiohttp_raw_server fixture instead", - DeprecationWarning, - stacklevel=2, - ) - return aiohttp_raw_server - - -@pytest.fixture -def aiohttp_client( - loop: asyncio.AbstractEventLoop, -) -> Generator[AiohttpClient, None, None]: - """Factory to create a TestClient instance. - - aiohttp_client(app, **kwargs) - aiohttp_client(server, **kwargs) - aiohttp_client(raw_server, **kwargs) - """ - clients = [] - - async def go( - __param: Union[Application, BaseTestServer], - *args: Any, - server_kwargs: Optional[Dict[str, Any]] = None, - **kwargs: Any - ) -> TestClient: - - if isinstance(__param, Callable) and not isinstance( # type: ignore[arg-type] - __param, (Application, BaseTestServer) - ): - __param = __param(loop, *args, **kwargs) - kwargs = {} - else: - assert not args, "args should be empty" - - if isinstance(__param, Application): - server_kwargs = server_kwargs or {} - server = TestServer(__param, loop=loop, **server_kwargs) - client = TestClient(server, loop=loop, **kwargs) - elif isinstance(__param, BaseTestServer): - client = TestClient(__param, loop=loop, **kwargs) - else: - raise ValueError("Unknown argument type: %r" % type(__param)) - - await client.start_server() - clients.append(client) - return client - - yield go - - async def finalize() -> None: - while clients: - await clients.pop().close() - - loop.run_until_complete(finalize()) - - -@pytest.fixture -def test_client(aiohttp_client): # type: ignore[no-untyped-def] # pragma: no cover - warnings.warn( - "Deprecated, use aiohttp_client fixture instead", - DeprecationWarning, - stacklevel=2, - ) - return aiohttp_client diff --git a/.venv/Lib/site-packages/aiohttp/resolver.py b/.venv/Lib/site-packages/aiohttp/resolver.py deleted file mode 100644 index 531ce93..0000000 --- a/.venv/Lib/site-packages/aiohttp/resolver.py +++ /dev/null @@ -1,160 +0,0 @@ -import asyncio -import socket -from typing import Any, Dict, List, Optional, Type, Union - -from .abc import AbstractResolver -from .helpers import get_running_loop - -__all__ = ("ThreadedResolver", "AsyncResolver", "DefaultResolver") - -try: - import aiodns - - # aiodns_default = hasattr(aiodns.DNSResolver, 'gethostbyname') -except ImportError: # pragma: no cover - aiodns = None - -aiodns_default = False - - -class ThreadedResolver(AbstractResolver): - """Threaded resolver. - - Uses an Executor for synchronous getaddrinfo() calls. - concurrent.futures.ThreadPoolExecutor is used by default. - """ - - def __init__(self, loop: Optional[asyncio.AbstractEventLoop] = None) -> None: - self._loop = get_running_loop(loop) - - async def resolve( - self, hostname: str, port: int = 0, family: int = socket.AF_INET - ) -> List[Dict[str, Any]]: - infos = await self._loop.getaddrinfo( - hostname, - port, - type=socket.SOCK_STREAM, - family=family, - flags=socket.AI_ADDRCONFIG, - ) - - hosts = [] - for family, _, proto, _, address in infos: - if family == socket.AF_INET6: - if len(address) < 3: - # IPv6 is not supported by Python build, - # or IPv6 is not enabled in the host - continue - if address[3]: # type: ignore[misc] - # This is essential for link-local IPv6 addresses. - # LL IPv6 is a VERY rare case. Strictly speaking, we should use - # getnameinfo() unconditionally, but performance makes sense. - host, _port = socket.getnameinfo( - address, socket.NI_NUMERICHOST | socket.NI_NUMERICSERV - ) - port = int(_port) - else: - host, port = address[:2] - else: # IPv4 - assert family == socket.AF_INET - host, port = address # type: ignore[misc] - hosts.append( - { - "hostname": hostname, - "host": host, - "port": port, - "family": family, - "proto": proto, - "flags": socket.AI_NUMERICHOST | socket.AI_NUMERICSERV, - } - ) - - return hosts - - async def close(self) -> None: - pass - - -class AsyncResolver(AbstractResolver): - """Use the `aiodns` package to make asynchronous DNS lookups""" - - def __init__( - self, - loop: Optional[asyncio.AbstractEventLoop] = None, - *args: Any, - **kwargs: Any - ) -> None: - if aiodns is None: - raise RuntimeError("Resolver requires aiodns library") - - self._loop = get_running_loop(loop) - self._resolver = aiodns.DNSResolver(*args, loop=loop, **kwargs) - - if not hasattr(self._resolver, "gethostbyname"): - # aiodns 1.1 is not available, fallback to DNSResolver.query - self.resolve = self._resolve_with_query # type: ignore - - async def resolve( - self, host: str, port: int = 0, family: int = socket.AF_INET - ) -> List[Dict[str, Any]]: - try: - resp = await self._resolver.gethostbyname(host, family) - except aiodns.error.DNSError as exc: - msg = exc.args[1] if len(exc.args) >= 1 else "DNS lookup failed" - raise OSError(msg) from exc - hosts = [] - for address in resp.addresses: - hosts.append( - { - "hostname": host, - "host": address, - "port": port, - "family": family, - "proto": 0, - "flags": socket.AI_NUMERICHOST | socket.AI_NUMERICSERV, - } - ) - - if not hosts: - raise OSError("DNS lookup failed") - - return hosts - - async def _resolve_with_query( - self, host: str, port: int = 0, family: int = socket.AF_INET - ) -> List[Dict[str, Any]]: - if family == socket.AF_INET6: - qtype = "AAAA" - else: - qtype = "A" - - try: - resp = await self._resolver.query(host, qtype) - except aiodns.error.DNSError as exc: - msg = exc.args[1] if len(exc.args) >= 1 else "DNS lookup failed" - raise OSError(msg) from exc - - hosts = [] - for rr in resp: - hosts.append( - { - "hostname": host, - "host": rr.host, - "port": port, - "family": family, - "proto": 0, - "flags": socket.AI_NUMERICHOST, - } - ) - - if not hosts: - raise OSError("DNS lookup failed") - - return hosts - - async def close(self) -> None: - self._resolver.cancel() - - -_DefaultType = Type[Union[AsyncResolver, ThreadedResolver]] -DefaultResolver: _DefaultType = AsyncResolver if aiodns_default else ThreadedResolver diff --git a/.venv/Lib/site-packages/aiohttp/streams.py b/.venv/Lib/site-packages/aiohttp/streams.py deleted file mode 100644 index 0558488..0000000 --- a/.venv/Lib/site-packages/aiohttp/streams.py +++ /dev/null @@ -1,660 +0,0 @@ -import asyncio -import collections -import warnings -from typing import Awaitable, Callable, Deque, Generic, List, Optional, Tuple, TypeVar - -from .base_protocol import BaseProtocol -from .helpers import BaseTimerContext, set_exception, set_result -from .log import internal_logger -from .typedefs import Final - -__all__ = ( - "EMPTY_PAYLOAD", - "EofStream", - "StreamReader", - "DataQueue", - "FlowControlDataQueue", -) - -_T = TypeVar("_T") - - -class EofStream(Exception): - """eof stream indication.""" - - -class AsyncStreamIterator(Generic[_T]): - def __init__(self, read_func: Callable[[], Awaitable[_T]]) -> None: - self.read_func = read_func - - def __aiter__(self) -> "AsyncStreamIterator[_T]": - return self - - async def __anext__(self) -> _T: - try: - rv = await self.read_func() - except EofStream: - raise StopAsyncIteration - if rv == b"": - raise StopAsyncIteration - return rv - - -class ChunkTupleAsyncStreamIterator: - def __init__(self, stream: "StreamReader") -> None: - self._stream = stream - - def __aiter__(self) -> "ChunkTupleAsyncStreamIterator": - return self - - async def __anext__(self) -> Tuple[bytes, bool]: - rv = await self._stream.readchunk() - if rv == (b"", False): - raise StopAsyncIteration - return rv - - -class AsyncStreamReaderMixin: - def __aiter__(self) -> AsyncStreamIterator[bytes]: - return AsyncStreamIterator(self.readline) # type: ignore[attr-defined] - - def iter_chunked(self, n: int) -> AsyncStreamIterator[bytes]: - """Returns an asynchronous iterator that yields chunks of size n. - - Python-3.5 available for Python 3.5+ only - """ - return AsyncStreamIterator( - lambda: self.read(n) # type: ignore[attr-defined,no-any-return] - ) - - def iter_any(self) -> AsyncStreamIterator[bytes]: - """Yield all available data as soon as it is received. - - Python-3.5 available for Python 3.5+ only - """ - return AsyncStreamIterator(self.readany) # type: ignore[attr-defined] - - def iter_chunks(self) -> ChunkTupleAsyncStreamIterator: - """Yield chunks of data as they are received by the server. - - The yielded objects are tuples - of (bytes, bool) as returned by the StreamReader.readchunk method. - - Python-3.5 available for Python 3.5+ only - """ - return ChunkTupleAsyncStreamIterator(self) # type: ignore[arg-type] - - -class StreamReader(AsyncStreamReaderMixin): - """An enhancement of asyncio.StreamReader. - - Supports asynchronous iteration by line, chunk or as available:: - - async for line in reader: - ... - async for chunk in reader.iter_chunked(1024): - ... - async for slice in reader.iter_any(): - ... - - """ - - total_bytes = 0 - - def __init__( - self, - protocol: BaseProtocol, - limit: int, - *, - timer: Optional[BaseTimerContext] = None, - loop: Optional[asyncio.AbstractEventLoop] = None, - ) -> None: - self._protocol = protocol - self._low_water = limit - self._high_water = limit * 2 - if loop is None: - loop = asyncio.get_event_loop() - self._loop = loop - self._size = 0 - self._cursor = 0 - self._http_chunk_splits = None # type: Optional[List[int]] - self._buffer = collections.deque() # type: Deque[bytes] - self._buffer_offset = 0 - self._eof = False - self._waiter = None # type: Optional[asyncio.Future[None]] - self._eof_waiter = None # type: Optional[asyncio.Future[None]] - self._exception = None # type: Optional[BaseException] - self._timer = timer - self._eof_callbacks = [] # type: List[Callable[[], None]] - - def __repr__(self) -> str: - info = [self.__class__.__name__] - if self._size: - info.append("%d bytes" % self._size) - if self._eof: - info.append("eof") - if self._low_water != 2 ** 16: # default limit - info.append("low=%d high=%d" % (self._low_water, self._high_water)) - if self._waiter: - info.append("w=%r" % self._waiter) - if self._exception: - info.append("e=%r" % self._exception) - return "<%s>" % " ".join(info) - - def get_read_buffer_limits(self) -> Tuple[int, int]: - return (self._low_water, self._high_water) - - def exception(self) -> Optional[BaseException]: - return self._exception - - def set_exception(self, exc: BaseException) -> None: - self._exception = exc - self._eof_callbacks.clear() - - waiter = self._waiter - if waiter is not None: - self._waiter = None - set_exception(waiter, exc) - - waiter = self._eof_waiter - if waiter is not None: - self._eof_waiter = None - set_exception(waiter, exc) - - def on_eof(self, callback: Callable[[], None]) -> None: - if self._eof: - try: - callback() - except Exception: - internal_logger.exception("Exception in eof callback") - else: - self._eof_callbacks.append(callback) - - def feed_eof(self) -> None: - self._eof = True - - waiter = self._waiter - if waiter is not None: - self._waiter = None - set_result(waiter, None) - - waiter = self._eof_waiter - if waiter is not None: - self._eof_waiter = None - set_result(waiter, None) - - for cb in self._eof_callbacks: - try: - cb() - except Exception: - internal_logger.exception("Exception in eof callback") - - self._eof_callbacks.clear() - - def is_eof(self) -> bool: - """Return True if 'feed_eof' was called.""" - return self._eof - - def at_eof(self) -> bool: - """Return True if the buffer is empty and 'feed_eof' was called.""" - return self._eof and not self._buffer - - async def wait_eof(self) -> None: - if self._eof: - return - - assert self._eof_waiter is None - self._eof_waiter = self._loop.create_future() - try: - await self._eof_waiter - finally: - self._eof_waiter = None - - def unread_data(self, data: bytes) -> None: - """rollback reading some data from stream, inserting it to buffer head.""" - warnings.warn( - "unread_data() is deprecated " - "and will be removed in future releases (#3260)", - DeprecationWarning, - stacklevel=2, - ) - if not data: - return - - if self._buffer_offset: - self._buffer[0] = self._buffer[0][self._buffer_offset :] - self._buffer_offset = 0 - self._size += len(data) - self._cursor -= len(data) - self._buffer.appendleft(data) - self._eof_counter = 0 - - # TODO: size is ignored, remove the param later - def feed_data(self, data: bytes, size: int = 0) -> None: - assert not self._eof, "feed_data after feed_eof" - - if not data: - return - - self._size += len(data) - self._buffer.append(data) - self.total_bytes += len(data) - - waiter = self._waiter - if waiter is not None: - self._waiter = None - set_result(waiter, None) - - if self._size > self._high_water and not self._protocol._reading_paused: - self._protocol.pause_reading() - - def begin_http_chunk_receiving(self) -> None: - if self._http_chunk_splits is None: - if self.total_bytes: - raise RuntimeError( - "Called begin_http_chunk_receiving when" "some data was already fed" - ) - self._http_chunk_splits = [] - - def end_http_chunk_receiving(self) -> None: - if self._http_chunk_splits is None: - raise RuntimeError( - "Called end_chunk_receiving without calling " - "begin_chunk_receiving first" - ) - - # self._http_chunk_splits contains logical byte offsets from start of - # the body transfer. Each offset is the offset of the end of a chunk. - # "Logical" means bytes, accessible for a user. - # If no chunks containig logical data were received, current position - # is difinitely zero. - pos = self._http_chunk_splits[-1] if self._http_chunk_splits else 0 - - if self.total_bytes == pos: - # We should not add empty chunks here. So we check for that. - # Note, when chunked + gzip is used, we can receive a chunk - # of compressed data, but that data may not be enough for gzip FSM - # to yield any uncompressed data. That's why current position may - # not change after receiving a chunk. - return - - self._http_chunk_splits.append(self.total_bytes) - - # wake up readchunk when end of http chunk received - waiter = self._waiter - if waiter is not None: - self._waiter = None - set_result(waiter, None) - - async def _wait(self, func_name: str) -> None: - # StreamReader uses a future to link the protocol feed_data() method - # to a read coroutine. Running two read coroutines at the same time - # would have an unexpected behaviour. It would not possible to know - # which coroutine would get the next data. - if self._waiter is not None: - raise RuntimeError( - "%s() called while another coroutine is " - "already waiting for incoming data" % func_name - ) - - waiter = self._waiter = self._loop.create_future() - try: - if self._timer: - with self._timer: - await waiter - else: - await waiter - finally: - self._waiter = None - - async def readline(self) -> bytes: - return await self.readuntil() - - async def readuntil(self, separator: bytes = b"\n") -> bytes: - seplen = len(separator) - if seplen == 0: - raise ValueError("Separator should be at least one-byte string") - - if self._exception is not None: - raise self._exception - - chunk = b"" - chunk_size = 0 - not_enough = True - - while not_enough: - while self._buffer and not_enough: - offset = self._buffer_offset - ichar = self._buffer[0].find(separator, offset) + 1 - # Read from current offset to found separator or to the end. - data = self._read_nowait_chunk(ichar - offset if ichar else -1) - chunk += data - chunk_size += len(data) - if ichar: - not_enough = False - - if chunk_size > self._high_water: - raise ValueError("Chunk too big") - - if self._eof: - break - - if not_enough: - await self._wait("readuntil") - - return chunk - - async def read(self, n: int = -1) -> bytes: - if self._exception is not None: - raise self._exception - - # migration problem; with DataQueue you have to catch - # EofStream exception, so common way is to run payload.read() inside - # infinite loop. what can cause real infinite loop with StreamReader - # lets keep this code one major release. - if __debug__: - if self._eof and not self._buffer: - self._eof_counter = getattr(self, "_eof_counter", 0) + 1 - if self._eof_counter > 5: - internal_logger.warning( - "Multiple access to StreamReader in eof state, " - "might be infinite loop.", - stack_info=True, - ) - - if not n: - return b"" - - if n < 0: - # This used to just loop creating a new waiter hoping to - # collect everything in self._buffer, but that would - # deadlock if the subprocess sends more than self.limit - # bytes. So just call self.readany() until EOF. - blocks = [] - while True: - block = await self.readany() - if not block: - break - blocks.append(block) - return b"".join(blocks) - - # TODO: should be `if` instead of `while` - # because waiter maybe triggered on chunk end, - # without feeding any data - while not self._buffer and not self._eof: - await self._wait("read") - - return self._read_nowait(n) - - async def readany(self) -> bytes: - if self._exception is not None: - raise self._exception - - # TODO: should be `if` instead of `while` - # because waiter maybe triggered on chunk end, - # without feeding any data - while not self._buffer and not self._eof: - await self._wait("readany") - - return self._read_nowait(-1) - - async def readchunk(self) -> Tuple[bytes, bool]: - """Returns a tuple of (data, end_of_http_chunk). - - When chunked transfer - encoding is used, end_of_http_chunk is a boolean indicating if the end - of the data corresponds to the end of a HTTP chunk , otherwise it is - always False. - """ - while True: - if self._exception is not None: - raise self._exception - - while self._http_chunk_splits: - pos = self._http_chunk_splits.pop(0) - if pos == self._cursor: - return (b"", True) - if pos > self._cursor: - return (self._read_nowait(pos - self._cursor), True) - internal_logger.warning( - "Skipping HTTP chunk end due to data " - "consumption beyond chunk boundary" - ) - - if self._buffer: - return (self._read_nowait_chunk(-1), False) - # return (self._read_nowait(-1), False) - - if self._eof: - # Special case for signifying EOF. - # (b'', True) is not a final return value actually. - return (b"", False) - - await self._wait("readchunk") - - async def readexactly(self, n: int) -> bytes: - if self._exception is not None: - raise self._exception - - blocks = [] # type: List[bytes] - while n > 0: - block = await self.read(n) - if not block: - partial = b"".join(blocks) - raise asyncio.IncompleteReadError(partial, len(partial) + n) - blocks.append(block) - n -= len(block) - - return b"".join(blocks) - - def read_nowait(self, n: int = -1) -> bytes: - # default was changed to be consistent with .read(-1) - # - # I believe the most users don't know about the method and - # they are not affected. - if self._exception is not None: - raise self._exception - - if self._waiter and not self._waiter.done(): - raise RuntimeError( - "Called while some coroutine is waiting for incoming data." - ) - - return self._read_nowait(n) - - def _read_nowait_chunk(self, n: int) -> bytes: - first_buffer = self._buffer[0] - offset = self._buffer_offset - if n != -1 and len(first_buffer) - offset > n: - data = first_buffer[offset : offset + n] - self._buffer_offset += n - - elif offset: - self._buffer.popleft() - data = first_buffer[offset:] - self._buffer_offset = 0 - - else: - data = self._buffer.popleft() - - self._size -= len(data) - self._cursor += len(data) - - chunk_splits = self._http_chunk_splits - # Prevent memory leak: drop useless chunk splits - while chunk_splits and chunk_splits[0] < self._cursor: - chunk_splits.pop(0) - - if self._size < self._low_water and self._protocol._reading_paused: - self._protocol.resume_reading() - return data - - def _read_nowait(self, n: int) -> bytes: - """Read not more than n bytes, or whole buffer if n == -1""" - chunks = [] - - while self._buffer: - chunk = self._read_nowait_chunk(n) - chunks.append(chunk) - if n != -1: - n -= len(chunk) - if n == 0: - break - - return b"".join(chunks) if chunks else b"" - - -class EmptyStreamReader(StreamReader): # lgtm [py/missing-call-to-init] - def __init__(self) -> None: - pass - - def exception(self) -> Optional[BaseException]: - return None - - def set_exception(self, exc: BaseException) -> None: - pass - - def on_eof(self, callback: Callable[[], None]) -> None: - try: - callback() - except Exception: - internal_logger.exception("Exception in eof callback") - - def feed_eof(self) -> None: - pass - - def is_eof(self) -> bool: - return True - - def at_eof(self) -> bool: - return True - - async def wait_eof(self) -> None: - return - - def feed_data(self, data: bytes, n: int = 0) -> None: - pass - - async def readline(self) -> bytes: - return b"" - - async def read(self, n: int = -1) -> bytes: - return b"" - - # TODO add async def readuntil - - async def readany(self) -> bytes: - return b"" - - async def readchunk(self) -> Tuple[bytes, bool]: - return (b"", True) - - async def readexactly(self, n: int) -> bytes: - raise asyncio.IncompleteReadError(b"", n) - - def read_nowait(self, n: int = -1) -> bytes: - return b"" - - -EMPTY_PAYLOAD: Final[StreamReader] = EmptyStreamReader() - - -class DataQueue(Generic[_T]): - """DataQueue is a general-purpose blocking queue with one reader.""" - - def __init__(self, loop: asyncio.AbstractEventLoop) -> None: - self._loop = loop - self._eof = False - self._waiter = None # type: Optional[asyncio.Future[None]] - self._exception = None # type: Optional[BaseException] - self._size = 0 - self._buffer = collections.deque() # type: Deque[Tuple[_T, int]] - - def __len__(self) -> int: - return len(self._buffer) - - def is_eof(self) -> bool: - return self._eof - - def at_eof(self) -> bool: - return self._eof and not self._buffer - - def exception(self) -> Optional[BaseException]: - return self._exception - - def set_exception(self, exc: BaseException) -> None: - self._eof = True - self._exception = exc - - waiter = self._waiter - if waiter is not None: - self._waiter = None - set_exception(waiter, exc) - - def feed_data(self, data: _T, size: int = 0) -> None: - self._size += size - self._buffer.append((data, size)) - - waiter = self._waiter - if waiter is not None: - self._waiter = None - set_result(waiter, None) - - def feed_eof(self) -> None: - self._eof = True - - waiter = self._waiter - if waiter is not None: - self._waiter = None - set_result(waiter, None) - - async def read(self) -> _T: - if not self._buffer and not self._eof: - assert not self._waiter - self._waiter = self._loop.create_future() - try: - await self._waiter - except (asyncio.CancelledError, asyncio.TimeoutError): - self._waiter = None - raise - - if self._buffer: - data, size = self._buffer.popleft() - self._size -= size - return data - else: - if self._exception is not None: - raise self._exception - else: - raise EofStream - - def __aiter__(self) -> AsyncStreamIterator[_T]: - return AsyncStreamIterator(self.read) - - -class FlowControlDataQueue(DataQueue[_T]): - """FlowControlDataQueue resumes and pauses an underlying stream. - - It is a destination for parsed data. - """ - - def __init__( - self, protocol: BaseProtocol, limit: int, *, loop: asyncio.AbstractEventLoop - ) -> None: - super().__init__(loop=loop) - - self._protocol = protocol - self._limit = limit * 2 - - def feed_data(self, data: _T, size: int = 0) -> None: - super().feed_data(data, size) - - if self._size > self._limit and not self._protocol._reading_paused: - self._protocol.pause_reading() - - async def read(self) -> _T: - try: - return await super().read() - finally: - if self._size < self._limit and self._protocol._reading_paused: - self._protocol.resume_reading() diff --git a/.venv/Lib/site-packages/aiohttp/tcp_helpers.py b/.venv/Lib/site-packages/aiohttp/tcp_helpers.py deleted file mode 100644 index 0e1dbf1..0000000 --- a/.venv/Lib/site-packages/aiohttp/tcp_helpers.py +++ /dev/null @@ -1,38 +0,0 @@ -"""Helper methods to tune a TCP connection""" - -import asyncio -import socket -from contextlib import suppress -from typing import Optional # noqa - -__all__ = ("tcp_keepalive", "tcp_nodelay") - - -if hasattr(socket, "SO_KEEPALIVE"): - - def tcp_keepalive(transport: asyncio.Transport) -> None: - sock = transport.get_extra_info("socket") - if sock is not None: - sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) - - -else: - - def tcp_keepalive(transport: asyncio.Transport) -> None: # pragma: no cover - pass - - -def tcp_nodelay(transport: asyncio.Transport, value: bool) -> None: - sock = transport.get_extra_info("socket") - - if sock is None: - return - - if sock.family not in (socket.AF_INET, socket.AF_INET6): - return - - value = bool(value) - - # socket may be closed already, on windows OSError get raised - with suppress(OSError): - sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, value) diff --git a/.venv/Lib/site-packages/aiohttp/test_utils.py b/.venv/Lib/site-packages/aiohttp/test_utils.py deleted file mode 100644 index 361dae4..0000000 --- a/.venv/Lib/site-packages/aiohttp/test_utils.py +++ /dev/null @@ -1,698 +0,0 @@ -"""Utilities shared by tests.""" - -import asyncio -import contextlib -import gc -import inspect -import ipaddress -import os -import socket -import sys -import warnings -from abc import ABC, abstractmethod -from types import TracebackType -from typing import ( - TYPE_CHECKING, - Any, - Callable, - Iterator, - List, - Optional, - Type, - Union, - cast, -) -from unittest import mock - -from aiosignal import Signal -from multidict import CIMultiDict, CIMultiDictProxy -from yarl import URL - -import aiohttp -from aiohttp.client import _RequestContextManager, _WSRequestContextManager - -from . import ClientSession, hdrs -from .abc import AbstractCookieJar -from .client_reqrep import ClientResponse -from .client_ws import ClientWebSocketResponse -from .helpers import PY_38, sentinel -from .http import HttpVersion, RawRequestMessage -from .web import ( - Application, - AppRunner, - BaseRunner, - Request, - Server, - ServerRunner, - SockSite, - UrlMappingMatchInfo, -) -from .web_protocol import _RequestHandler - -if TYPE_CHECKING: # pragma: no cover - from ssl import SSLContext -else: - SSLContext = None - -if PY_38: - from unittest import IsolatedAsyncioTestCase as TestCase -else: - from asynctest import TestCase # type: ignore[no-redef] - -REUSE_ADDRESS = os.name == "posix" and sys.platform != "cygwin" - - -def get_unused_port_socket( - host: str, family: socket.AddressFamily = socket.AF_INET -) -> socket.socket: - return get_port_socket(host, 0, family) - - -def get_port_socket( - host: str, port: int, family: socket.AddressFamily -) -> socket.socket: - s = socket.socket(family, socket.SOCK_STREAM) - if REUSE_ADDRESS: - # Windows has different semantics for SO_REUSEADDR, - # so don't set it. Ref: - # https://docs.microsoft.com/en-us/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - s.bind((host, port)) - return s - - -def unused_port() -> int: - """Return a port that is unused on the current host.""" - with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: - s.bind(("127.0.0.1", 0)) - return cast(int, s.getsockname()[1]) - - -class BaseTestServer(ABC): - __test__ = False - - def __init__( - self, - *, - scheme: Union[str, object] = sentinel, - loop: Optional[asyncio.AbstractEventLoop] = None, - host: str = "127.0.0.1", - port: Optional[int] = None, - skip_url_asserts: bool = False, - socket_factory: Callable[ - [str, int, socket.AddressFamily], socket.socket - ] = get_port_socket, - **kwargs: Any, - ) -> None: - self._loop = loop - self.runner = None # type: Optional[BaseRunner] - self._root = None # type: Optional[URL] - self.host = host - self.port = port - self._closed = False - self.scheme = scheme - self.skip_url_asserts = skip_url_asserts - self.socket_factory = socket_factory - - async def start_server( - self, loop: Optional[asyncio.AbstractEventLoop] = None, **kwargs: Any - ) -> None: - if self.runner: - return - self._loop = loop - self._ssl = kwargs.pop("ssl", None) - self.runner = await self._make_runner(**kwargs) - await self.runner.setup() - if not self.port: - self.port = 0 - try: - version = ipaddress.ip_address(self.host).version - except ValueError: - version = 4 - family = socket.AF_INET6 if version == 6 else socket.AF_INET - _sock = self.socket_factory(self.host, self.port, family) - self.host, self.port = _sock.getsockname()[:2] - site = SockSite(self.runner, sock=_sock, ssl_context=self._ssl) - await site.start() - server = site._server - assert server is not None - sockets = server.sockets - assert sockets is not None - self.port = sockets[0].getsockname()[1] - if self.scheme is sentinel: - if self._ssl: - scheme = "https" - else: - scheme = "http" - self.scheme = scheme - self._root = URL(f"{self.scheme}://{self.host}:{self.port}") - - @abstractmethod # pragma: no cover - async def _make_runner(self, **kwargs: Any) -> BaseRunner: - pass - - def make_url(self, path: str) -> URL: - assert self._root is not None - url = URL(path) - if not self.skip_url_asserts: - assert not url.is_absolute() - return self._root.join(url) - else: - return URL(str(self._root) + path) - - @property - def started(self) -> bool: - return self.runner is not None - - @property - def closed(self) -> bool: - return self._closed - - @property - def handler(self) -> Server: - # for backward compatibility - # web.Server instance - runner = self.runner - assert runner is not None - assert runner.server is not None - return runner.server - - async def close(self) -> None: - """Close all fixtures created by the test client. - - After that point, the TestClient is no longer usable. - - This is an idempotent function: running close multiple times - will not have any additional effects. - - close is also run when the object is garbage collected, and on - exit when used as a context manager. - - """ - if self.started and not self.closed: - assert self.runner is not None - await self.runner.cleanup() - self._root = None - self.port = None - self._closed = True - - def __enter__(self) -> None: - raise TypeError("Use async with instead") - - def __exit__( - self, - exc_type: Optional[Type[BaseException]], - exc_value: Optional[BaseException], - traceback: Optional[TracebackType], - ) -> None: - # __exit__ should exist in pair with __enter__ but never executed - pass # pragma: no cover - - async def __aenter__(self) -> "BaseTestServer": - await self.start_server(loop=self._loop) - return self - - async def __aexit__( - self, - exc_type: Optional[Type[BaseException]], - exc_value: Optional[BaseException], - traceback: Optional[TracebackType], - ) -> None: - await self.close() - - -class TestServer(BaseTestServer): - def __init__( - self, - app: Application, - *, - scheme: Union[str, object] = sentinel, - host: str = "127.0.0.1", - port: Optional[int] = None, - **kwargs: Any, - ): - self.app = app - super().__init__(scheme=scheme, host=host, port=port, **kwargs) - - async def _make_runner(self, **kwargs: Any) -> BaseRunner: - return AppRunner(self.app, **kwargs) - - -class RawTestServer(BaseTestServer): - def __init__( - self, - handler: _RequestHandler, - *, - scheme: Union[str, object] = sentinel, - host: str = "127.0.0.1", - port: Optional[int] = None, - **kwargs: Any, - ) -> None: - self._handler = handler - super().__init__(scheme=scheme, host=host, port=port, **kwargs) - - async def _make_runner(self, debug: bool = True, **kwargs: Any) -> ServerRunner: - srv = Server(self._handler, loop=self._loop, debug=debug, **kwargs) - return ServerRunner(srv, debug=debug, **kwargs) - - -class TestClient: - """ - A test client implementation. - - To write functional tests for aiohttp based servers. - - """ - - __test__ = False - - def __init__( - self, - server: BaseTestServer, - *, - cookie_jar: Optional[AbstractCookieJar] = None, - loop: Optional[asyncio.AbstractEventLoop] = None, - **kwargs: Any, - ) -> None: - if not isinstance(server, BaseTestServer): - raise TypeError( - "server must be TestServer " "instance, found type: %r" % type(server) - ) - self._server = server - self._loop = loop - if cookie_jar is None: - cookie_jar = aiohttp.CookieJar(unsafe=True, loop=loop) - self._session = ClientSession(loop=loop, cookie_jar=cookie_jar, **kwargs) - self._closed = False - self._responses = [] # type: List[ClientResponse] - self._websockets = [] # type: List[ClientWebSocketResponse] - - async def start_server(self) -> None: - await self._server.start_server(loop=self._loop) - - @property - def host(self) -> str: - return self._server.host - - @property - def port(self) -> Optional[int]: - return self._server.port - - @property - def server(self) -> BaseTestServer: - return self._server - - @property - def app(self) -> Optional[Application]: - return cast(Optional[Application], getattr(self._server, "app", None)) - - @property - def session(self) -> ClientSession: - """An internal aiohttp.ClientSession. - - Unlike the methods on the TestClient, client session requests - do not automatically include the host in the url queried, and - will require an absolute path to the resource. - - """ - return self._session - - def make_url(self, path: str) -> URL: - return self._server.make_url(path) - - async def _request(self, method: str, path: str, **kwargs: Any) -> ClientResponse: - resp = await self._session.request(method, self.make_url(path), **kwargs) - # save it to close later - self._responses.append(resp) - return resp - - def request(self, method: str, path: str, **kwargs: Any) -> _RequestContextManager: - """Routes a request to tested http server. - - The interface is identical to aiohttp.ClientSession.request, - except the loop kwarg is overridden by the instance used by the - test server. - - """ - return _RequestContextManager(self._request(method, path, **kwargs)) - - def get(self, path: str, **kwargs: Any) -> _RequestContextManager: - """Perform an HTTP GET request.""" - return _RequestContextManager(self._request(hdrs.METH_GET, path, **kwargs)) - - def post(self, path: str, **kwargs: Any) -> _RequestContextManager: - """Perform an HTTP POST request.""" - return _RequestContextManager(self._request(hdrs.METH_POST, path, **kwargs)) - - def options(self, path: str, **kwargs: Any) -> _RequestContextManager: - """Perform an HTTP OPTIONS request.""" - return _RequestContextManager(self._request(hdrs.METH_OPTIONS, path, **kwargs)) - - def head(self, path: str, **kwargs: Any) -> _RequestContextManager: - """Perform an HTTP HEAD request.""" - return _RequestContextManager(self._request(hdrs.METH_HEAD, path, **kwargs)) - - def put(self, path: str, **kwargs: Any) -> _RequestContextManager: - """Perform an HTTP PUT request.""" - return _RequestContextManager(self._request(hdrs.METH_PUT, path, **kwargs)) - - def patch(self, path: str, **kwargs: Any) -> _RequestContextManager: - """Perform an HTTP PATCH request.""" - return _RequestContextManager(self._request(hdrs.METH_PATCH, path, **kwargs)) - - def delete(self, path: str, **kwargs: Any) -> _RequestContextManager: - """Perform an HTTP PATCH request.""" - return _RequestContextManager(self._request(hdrs.METH_DELETE, path, **kwargs)) - - def ws_connect(self, path: str, **kwargs: Any) -> _WSRequestContextManager: - """Initiate websocket connection. - - The api corresponds to aiohttp.ClientSession.ws_connect. - - """ - return _WSRequestContextManager(self._ws_connect(path, **kwargs)) - - async def _ws_connect(self, path: str, **kwargs: Any) -> ClientWebSocketResponse: - ws = await self._session.ws_connect(self.make_url(path), **kwargs) - self._websockets.append(ws) - return ws - - async def close(self) -> None: - """Close all fixtures created by the test client. - - After that point, the TestClient is no longer usable. - - This is an idempotent function: running close multiple times - will not have any additional effects. - - close is also run on exit when used as a(n) (asynchronous) - context manager. - - """ - if not self._closed: - for resp in self._responses: - resp.close() - for ws in self._websockets: - await ws.close() - await self._session.close() - await self._server.close() - self._closed = True - - def __enter__(self) -> None: - raise TypeError("Use async with instead") - - def __exit__( - self, - exc_type: Optional[Type[BaseException]], - exc: Optional[BaseException], - tb: Optional[TracebackType], - ) -> None: - # __exit__ should exist in pair with __enter__ but never executed - pass # pragma: no cover - - async def __aenter__(self) -> "TestClient": - await self.start_server() - return self - - async def __aexit__( - self, - exc_type: Optional[Type[BaseException]], - exc: Optional[BaseException], - tb: Optional[TracebackType], - ) -> None: - await self.close() - - -class AioHTTPTestCase(TestCase): - """A base class to allow for unittest web applications using aiohttp. - - Provides the following: - - * self.client (aiohttp.test_utils.TestClient): an aiohttp test client. - * self.loop (asyncio.BaseEventLoop): the event loop in which the - application and server are running. - * self.app (aiohttp.web.Application): the application returned by - self.get_application() - - Note that the TestClient's methods are asynchronous: you have to - execute function on the test client using asynchronous methods. - """ - - async def get_application(self) -> Application: - """Get application. - - This method should be overridden - to return the aiohttp.web.Application - object to test. - """ - return self.get_app() - - def get_app(self) -> Application: - """Obsolete method used to constructing web application. - - Use .get_application() coroutine instead. - """ - raise RuntimeError("Did you forget to define get_application()?") - - def setUp(self) -> None: - try: - self.loop = asyncio.get_running_loop() - except (AttributeError, RuntimeError): # AttributeError->py36 - self.loop = asyncio.get_event_loop_policy().get_event_loop() - - self.loop.run_until_complete(self.setUpAsync()) - - async def setUpAsync(self) -> None: - self.app = await self.get_application() - self.server = await self.get_server(self.app) - self.client = await self.get_client(self.server) - - await self.client.start_server() - - def tearDown(self) -> None: - self.loop.run_until_complete(self.tearDownAsync()) - - async def tearDownAsync(self) -> None: - await self.client.close() - - async def get_server(self, app: Application) -> TestServer: - """Return a TestServer instance.""" - return TestServer(app, loop=self.loop) - - async def get_client(self, server: TestServer) -> TestClient: - """Return a TestClient instance.""" - return TestClient(server, loop=self.loop) - - -def unittest_run_loop(func: Any, *args: Any, **kwargs: Any) -> Any: - """ - A decorator dedicated to use with asynchronous AioHTTPTestCase test methods. - - In 3.8+, this does nothing. - """ - warnings.warn( - "Decorator `@unittest_run_loop` is no longer needed in aiohttp 3.8+", - DeprecationWarning, - stacklevel=2, - ) - return func - - -_LOOP_FACTORY = Callable[[], asyncio.AbstractEventLoop] - - -@contextlib.contextmanager -def loop_context( - loop_factory: _LOOP_FACTORY = asyncio.new_event_loop, fast: bool = False -) -> Iterator[asyncio.AbstractEventLoop]: - """A contextmanager that creates an event_loop, for test purposes. - - Handles the creation and cleanup of a test loop. - """ - loop = setup_test_loop(loop_factory) - yield loop - teardown_test_loop(loop, fast=fast) - - -def setup_test_loop( - loop_factory: _LOOP_FACTORY = asyncio.new_event_loop, -) -> asyncio.AbstractEventLoop: - """Create and return an asyncio.BaseEventLoop instance. - - The caller should also call teardown_test_loop, - once they are done with the loop. - """ - loop = loop_factory() - try: - module = loop.__class__.__module__ - skip_watcher = "uvloop" in module - except AttributeError: # pragma: no cover - # Just in case - skip_watcher = True - asyncio.set_event_loop(loop) - if sys.platform != "win32" and not skip_watcher: - policy = asyncio.get_event_loop_policy() - watcher: asyncio.AbstractChildWatcher - try: # Python >= 3.8 - # Refs: - # * https://github.com/pytest-dev/pytest-xdist/issues/620 - # * https://stackoverflow.com/a/58614689/595220 - # * https://bugs.python.org/issue35621 - # * https://github.com/python/cpython/pull/14344 - watcher = asyncio.ThreadedChildWatcher() - except AttributeError: # Python < 3.8 - watcher = asyncio.SafeChildWatcher() - watcher.attach_loop(loop) - with contextlib.suppress(NotImplementedError): - policy.set_child_watcher(watcher) - return loop - - -def teardown_test_loop(loop: asyncio.AbstractEventLoop, fast: bool = False) -> None: - """Teardown and cleanup an event_loop created by setup_test_loop.""" - closed = loop.is_closed() - if not closed: - loop.call_soon(loop.stop) - loop.run_forever() - loop.close() - - if not fast: - gc.collect() - - asyncio.set_event_loop(None) - - -def _create_app_mock() -> mock.MagicMock: - def get_dict(app: Any, key: str) -> Any: - return app.__app_dict[key] - - def set_dict(app: Any, key: str, value: Any) -> None: - app.__app_dict[key] = value - - app = mock.MagicMock() - app.__app_dict = {} - app.__getitem__ = get_dict - app.__setitem__ = set_dict - - app._debug = False - app.on_response_prepare = Signal(app) - app.on_response_prepare.freeze() - return app - - -def _create_transport(sslcontext: Optional[SSLContext] = None) -> mock.Mock: - transport = mock.Mock() - - def get_extra_info(key: str) -> Optional[SSLContext]: - if key == "sslcontext": - return sslcontext - else: - return None - - transport.get_extra_info.side_effect = get_extra_info - return transport - - -def make_mocked_request( - method: str, - path: str, - headers: Any = None, - *, - match_info: Any = sentinel, - version: HttpVersion = HttpVersion(1, 1), - closing: bool = False, - app: Any = None, - writer: Any = sentinel, - protocol: Any = sentinel, - transport: Any = sentinel, - payload: Any = sentinel, - sslcontext: Optional[SSLContext] = None, - client_max_size: int = 1024 ** 2, - loop: Any = ..., -) -> Request: - """Creates mocked web.Request testing purposes. - - Useful in unit tests, when spinning full web server is overkill or - specific conditions and errors are hard to trigger. - """ - task = mock.Mock() - if loop is ...: - loop = mock.Mock() - loop.create_future.return_value = () - - if version < HttpVersion(1, 1): - closing = True - - if headers: - headers = CIMultiDictProxy(CIMultiDict(headers)) - raw_hdrs = tuple( - (k.encode("utf-8"), v.encode("utf-8")) for k, v in headers.items() - ) - else: - headers = CIMultiDictProxy(CIMultiDict()) - raw_hdrs = () - - chunked = "chunked" in headers.get(hdrs.TRANSFER_ENCODING, "").lower() - - message = RawRequestMessage( - method, - path, - version, - headers, - raw_hdrs, - closing, - None, - False, - chunked, - URL(path), - ) - if app is None: - app = _create_app_mock() - - if transport is sentinel: - transport = _create_transport(sslcontext) - - if protocol is sentinel: - protocol = mock.Mock() - protocol.transport = transport - - if writer is sentinel: - writer = mock.Mock() - writer.write_headers = make_mocked_coro(None) - writer.write = make_mocked_coro(None) - writer.write_eof = make_mocked_coro(None) - writer.drain = make_mocked_coro(None) - writer.transport = transport - - protocol.transport = transport - protocol.writer = writer - - if payload is sentinel: - payload = mock.Mock() - - req = Request( - message, payload, protocol, writer, task, loop, client_max_size=client_max_size - ) - - match_info = UrlMappingMatchInfo( - {} if match_info is sentinel else match_info, mock.Mock() - ) - match_info.add_app(app) - req._match_info = match_info - - return req - - -def make_mocked_coro( - return_value: Any = sentinel, raise_exception: Any = sentinel -) -> Any: - """Creates a coroutine mock.""" - - async def mock_coro(*args: Any, **kwargs: Any) -> Any: - if raise_exception is not sentinel: - raise raise_exception - if not inspect.isawaitable(return_value): - return return_value - await return_value - - return mock.Mock(wraps=mock_coro) diff --git a/.venv/Lib/site-packages/aiohttp/tracing.py b/.venv/Lib/site-packages/aiohttp/tracing.py deleted file mode 100644 index 0e118a3..0000000 --- a/.venv/Lib/site-packages/aiohttp/tracing.py +++ /dev/null @@ -1,472 +0,0 @@ -from types import SimpleNamespace -from typing import TYPE_CHECKING, Awaitable, Optional, Type, TypeVar - -import attr -from aiosignal import Signal -from multidict import CIMultiDict -from yarl import URL - -from .client_reqrep import ClientResponse - -if TYPE_CHECKING: # pragma: no cover - from .client import ClientSession - from .typedefs import Protocol - - _ParamT_contra = TypeVar("_ParamT_contra", contravariant=True) - - class _SignalCallback(Protocol[_ParamT_contra]): - def __call__( - self, - __client_session: ClientSession, - __trace_config_ctx: SimpleNamespace, - __params: _ParamT_contra, - ) -> Awaitable[None]: - ... - - -__all__ = ( - "TraceConfig", - "TraceRequestStartParams", - "TraceRequestEndParams", - "TraceRequestExceptionParams", - "TraceConnectionQueuedStartParams", - "TraceConnectionQueuedEndParams", - "TraceConnectionCreateStartParams", - "TraceConnectionCreateEndParams", - "TraceConnectionReuseconnParams", - "TraceDnsResolveHostStartParams", - "TraceDnsResolveHostEndParams", - "TraceDnsCacheHitParams", - "TraceDnsCacheMissParams", - "TraceRequestRedirectParams", - "TraceRequestChunkSentParams", - "TraceResponseChunkReceivedParams", - "TraceRequestHeadersSentParams", -) - - -class TraceConfig: - """First-class used to trace requests launched via ClientSession objects.""" - - def __init__( - self, trace_config_ctx_factory: Type[SimpleNamespace] = SimpleNamespace - ) -> None: - self._on_request_start = Signal( - self - ) # type: Signal[_SignalCallback[TraceRequestStartParams]] - self._on_request_chunk_sent = Signal( - self - ) # type: Signal[_SignalCallback[TraceRequestChunkSentParams]] - self._on_response_chunk_received = Signal( - self - ) # type: Signal[_SignalCallback[TraceResponseChunkReceivedParams]] - self._on_request_end = Signal( - self - ) # type: Signal[_SignalCallback[TraceRequestEndParams]] - self._on_request_exception = Signal( - self - ) # type: Signal[_SignalCallback[TraceRequestExceptionParams]] - self._on_request_redirect = Signal( - self - ) # type: Signal[_SignalCallback[TraceRequestRedirectParams]] - self._on_connection_queued_start = Signal( - self - ) # type: Signal[_SignalCallback[TraceConnectionQueuedStartParams]] - self._on_connection_queued_end = Signal( - self - ) # type: Signal[_SignalCallback[TraceConnectionQueuedEndParams]] - self._on_connection_create_start = Signal( - self - ) # type: Signal[_SignalCallback[TraceConnectionCreateStartParams]] - self._on_connection_create_end = Signal( - self - ) # type: Signal[_SignalCallback[TraceConnectionCreateEndParams]] - self._on_connection_reuseconn = Signal( - self - ) # type: Signal[_SignalCallback[TraceConnectionReuseconnParams]] - self._on_dns_resolvehost_start = Signal( - self - ) # type: Signal[_SignalCallback[TraceDnsResolveHostStartParams]] - self._on_dns_resolvehost_end = Signal( - self - ) # type: Signal[_SignalCallback[TraceDnsResolveHostEndParams]] - self._on_dns_cache_hit = Signal( - self - ) # type: Signal[_SignalCallback[TraceDnsCacheHitParams]] - self._on_dns_cache_miss = Signal( - self - ) # type: Signal[_SignalCallback[TraceDnsCacheMissParams]] - self._on_request_headers_sent = Signal( - self - ) # type: Signal[_SignalCallback[TraceRequestHeadersSentParams]] - - self._trace_config_ctx_factory = trace_config_ctx_factory - - def trace_config_ctx( - self, trace_request_ctx: Optional[SimpleNamespace] = None - ) -> SimpleNamespace: - """Return a new trace_config_ctx instance""" - return self._trace_config_ctx_factory(trace_request_ctx=trace_request_ctx) - - def freeze(self) -> None: - self._on_request_start.freeze() - self._on_request_chunk_sent.freeze() - self._on_response_chunk_received.freeze() - self._on_request_end.freeze() - self._on_request_exception.freeze() - self._on_request_redirect.freeze() - self._on_connection_queued_start.freeze() - self._on_connection_queued_end.freeze() - self._on_connection_create_start.freeze() - self._on_connection_create_end.freeze() - self._on_connection_reuseconn.freeze() - self._on_dns_resolvehost_start.freeze() - self._on_dns_resolvehost_end.freeze() - self._on_dns_cache_hit.freeze() - self._on_dns_cache_miss.freeze() - self._on_request_headers_sent.freeze() - - @property - def on_request_start(self) -> "Signal[_SignalCallback[TraceRequestStartParams]]": - return self._on_request_start - - @property - def on_request_chunk_sent( - self, - ) -> "Signal[_SignalCallback[TraceRequestChunkSentParams]]": - return self._on_request_chunk_sent - - @property - def on_response_chunk_received( - self, - ) -> "Signal[_SignalCallback[TraceResponseChunkReceivedParams]]": - return self._on_response_chunk_received - - @property - def on_request_end(self) -> "Signal[_SignalCallback[TraceRequestEndParams]]": - return self._on_request_end - - @property - def on_request_exception( - self, - ) -> "Signal[_SignalCallback[TraceRequestExceptionParams]]": - return self._on_request_exception - - @property - def on_request_redirect( - self, - ) -> "Signal[_SignalCallback[TraceRequestRedirectParams]]": - return self._on_request_redirect - - @property - def on_connection_queued_start( - self, - ) -> "Signal[_SignalCallback[TraceConnectionQueuedStartParams]]": - return self._on_connection_queued_start - - @property - def on_connection_queued_end( - self, - ) -> "Signal[_SignalCallback[TraceConnectionQueuedEndParams]]": - return self._on_connection_queued_end - - @property - def on_connection_create_start( - self, - ) -> "Signal[_SignalCallback[TraceConnectionCreateStartParams]]": - return self._on_connection_create_start - - @property - def on_connection_create_end( - self, - ) -> "Signal[_SignalCallback[TraceConnectionCreateEndParams]]": - return self._on_connection_create_end - - @property - def on_connection_reuseconn( - self, - ) -> "Signal[_SignalCallback[TraceConnectionReuseconnParams]]": - return self._on_connection_reuseconn - - @property - def on_dns_resolvehost_start( - self, - ) -> "Signal[_SignalCallback[TraceDnsResolveHostStartParams]]": - return self._on_dns_resolvehost_start - - @property - def on_dns_resolvehost_end( - self, - ) -> "Signal[_SignalCallback[TraceDnsResolveHostEndParams]]": - return self._on_dns_resolvehost_end - - @property - def on_dns_cache_hit(self) -> "Signal[_SignalCallback[TraceDnsCacheHitParams]]": - return self._on_dns_cache_hit - - @property - def on_dns_cache_miss(self) -> "Signal[_SignalCallback[TraceDnsCacheMissParams]]": - return self._on_dns_cache_miss - - @property - def on_request_headers_sent( - self, - ) -> "Signal[_SignalCallback[TraceRequestHeadersSentParams]]": - return self._on_request_headers_sent - - -@attr.s(auto_attribs=True, frozen=True, slots=True) -class TraceRequestStartParams: - """Parameters sent by the `on_request_start` signal""" - - method: str - url: URL - headers: "CIMultiDict[str]" - - -@attr.s(auto_attribs=True, frozen=True, slots=True) -class TraceRequestChunkSentParams: - """Parameters sent by the `on_request_chunk_sent` signal""" - - method: str - url: URL - chunk: bytes - - -@attr.s(auto_attribs=True, frozen=True, slots=True) -class TraceResponseChunkReceivedParams: - """Parameters sent by the `on_response_chunk_received` signal""" - - method: str - url: URL - chunk: bytes - - -@attr.s(auto_attribs=True, frozen=True, slots=True) -class TraceRequestEndParams: - """Parameters sent by the `on_request_end` signal""" - - method: str - url: URL - headers: "CIMultiDict[str]" - response: ClientResponse - - -@attr.s(auto_attribs=True, frozen=True, slots=True) -class TraceRequestExceptionParams: - """Parameters sent by the `on_request_exception` signal""" - - method: str - url: URL - headers: "CIMultiDict[str]" - exception: BaseException - - -@attr.s(auto_attribs=True, frozen=True, slots=True) -class TraceRequestRedirectParams: - """Parameters sent by the `on_request_redirect` signal""" - - method: str - url: URL - headers: "CIMultiDict[str]" - response: ClientResponse - - -@attr.s(auto_attribs=True, frozen=True, slots=True) -class TraceConnectionQueuedStartParams: - """Parameters sent by the `on_connection_queued_start` signal""" - - -@attr.s(auto_attribs=True, frozen=True, slots=True) -class TraceConnectionQueuedEndParams: - """Parameters sent by the `on_connection_queued_end` signal""" - - -@attr.s(auto_attribs=True, frozen=True, slots=True) -class TraceConnectionCreateStartParams: - """Parameters sent by the `on_connection_create_start` signal""" - - -@attr.s(auto_attribs=True, frozen=True, slots=True) -class TraceConnectionCreateEndParams: - """Parameters sent by the `on_connection_create_end` signal""" - - -@attr.s(auto_attribs=True, frozen=True, slots=True) -class TraceConnectionReuseconnParams: - """Parameters sent by the `on_connection_reuseconn` signal""" - - -@attr.s(auto_attribs=True, frozen=True, slots=True) -class TraceDnsResolveHostStartParams: - """Parameters sent by the `on_dns_resolvehost_start` signal""" - - host: str - - -@attr.s(auto_attribs=True, frozen=True, slots=True) -class TraceDnsResolveHostEndParams: - """Parameters sent by the `on_dns_resolvehost_end` signal""" - - host: str - - -@attr.s(auto_attribs=True, frozen=True, slots=True) -class TraceDnsCacheHitParams: - """Parameters sent by the `on_dns_cache_hit` signal""" - - host: str - - -@attr.s(auto_attribs=True, frozen=True, slots=True) -class TraceDnsCacheMissParams: - """Parameters sent by the `on_dns_cache_miss` signal""" - - host: str - - -@attr.s(auto_attribs=True, frozen=True, slots=True) -class TraceRequestHeadersSentParams: - """Parameters sent by the `on_request_headers_sent` signal""" - - method: str - url: URL - headers: "CIMultiDict[str]" - - -class Trace: - """Internal dependency holder class. - - Used to keep together the main dependencies used - at the moment of send a signal. - """ - - def __init__( - self, - session: "ClientSession", - trace_config: TraceConfig, - trace_config_ctx: SimpleNamespace, - ) -> None: - self._trace_config = trace_config - self._trace_config_ctx = trace_config_ctx - self._session = session - - async def send_request_start( - self, method: str, url: URL, headers: "CIMultiDict[str]" - ) -> None: - return await self._trace_config.on_request_start.send( - self._session, - self._trace_config_ctx, - TraceRequestStartParams(method, url, headers), - ) - - async def send_request_chunk_sent( - self, method: str, url: URL, chunk: bytes - ) -> None: - return await self._trace_config.on_request_chunk_sent.send( - self._session, - self._trace_config_ctx, - TraceRequestChunkSentParams(method, url, chunk), - ) - - async def send_response_chunk_received( - self, method: str, url: URL, chunk: bytes - ) -> None: - return await self._trace_config.on_response_chunk_received.send( - self._session, - self._trace_config_ctx, - TraceResponseChunkReceivedParams(method, url, chunk), - ) - - async def send_request_end( - self, - method: str, - url: URL, - headers: "CIMultiDict[str]", - response: ClientResponse, - ) -> None: - return await self._trace_config.on_request_end.send( - self._session, - self._trace_config_ctx, - TraceRequestEndParams(method, url, headers, response), - ) - - async def send_request_exception( - self, - method: str, - url: URL, - headers: "CIMultiDict[str]", - exception: BaseException, - ) -> None: - return await self._trace_config.on_request_exception.send( - self._session, - self._trace_config_ctx, - TraceRequestExceptionParams(method, url, headers, exception), - ) - - async def send_request_redirect( - self, - method: str, - url: URL, - headers: "CIMultiDict[str]", - response: ClientResponse, - ) -> None: - return await self._trace_config._on_request_redirect.send( - self._session, - self._trace_config_ctx, - TraceRequestRedirectParams(method, url, headers, response), - ) - - async def send_connection_queued_start(self) -> None: - return await self._trace_config.on_connection_queued_start.send( - self._session, self._trace_config_ctx, TraceConnectionQueuedStartParams() - ) - - async def send_connection_queued_end(self) -> None: - return await self._trace_config.on_connection_queued_end.send( - self._session, self._trace_config_ctx, TraceConnectionQueuedEndParams() - ) - - async def send_connection_create_start(self) -> None: - return await self._trace_config.on_connection_create_start.send( - self._session, self._trace_config_ctx, TraceConnectionCreateStartParams() - ) - - async def send_connection_create_end(self) -> None: - return await self._trace_config.on_connection_create_end.send( - self._session, self._trace_config_ctx, TraceConnectionCreateEndParams() - ) - - async def send_connection_reuseconn(self) -> None: - return await self._trace_config.on_connection_reuseconn.send( - self._session, self._trace_config_ctx, TraceConnectionReuseconnParams() - ) - - async def send_dns_resolvehost_start(self, host: str) -> None: - return await self._trace_config.on_dns_resolvehost_start.send( - self._session, self._trace_config_ctx, TraceDnsResolveHostStartParams(host) - ) - - async def send_dns_resolvehost_end(self, host: str) -> None: - return await self._trace_config.on_dns_resolvehost_end.send( - self._session, self._trace_config_ctx, TraceDnsResolveHostEndParams(host) - ) - - async def send_dns_cache_hit(self, host: str) -> None: - return await self._trace_config.on_dns_cache_hit.send( - self._session, self._trace_config_ctx, TraceDnsCacheHitParams(host) - ) - - async def send_dns_cache_miss(self, host: str) -> None: - return await self._trace_config.on_dns_cache_miss.send( - self._session, self._trace_config_ctx, TraceDnsCacheMissParams(host) - ) - - async def send_request_headers( - self, method: str, url: URL, headers: "CIMultiDict[str]" - ) -> None: - return await self._trace_config._on_request_headers_sent.send( - self._session, - self._trace_config_ctx, - TraceRequestHeadersSentParams(method, url, headers), - ) diff --git a/.venv/Lib/site-packages/aiohttp/typedefs.py b/.venv/Lib/site-packages/aiohttp/typedefs.py deleted file mode 100644 index 84283d9..0000000 --- a/.venv/Lib/site-packages/aiohttp/typedefs.py +++ /dev/null @@ -1,64 +0,0 @@ -import json -import os -import sys -from typing import ( - TYPE_CHECKING, - Any, - Awaitable, - Callable, - Iterable, - Mapping, - Tuple, - Union, -) - -from multidict import CIMultiDict, CIMultiDictProxy, MultiDict, MultiDictProxy, istr -from yarl import URL - -# These are for other modules to use (to avoid repeating the conditional import). -if sys.version_info >= (3, 8): - from typing import Final as Final, Protocol as Protocol, TypedDict as TypedDict -else: - from typing_extensions import ( # noqa: F401 - Final, - Protocol as Protocol, - TypedDict as TypedDict, - ) - -DEFAULT_JSON_ENCODER = json.dumps -DEFAULT_JSON_DECODER = json.loads - -if TYPE_CHECKING: # pragma: no cover - _CIMultiDict = CIMultiDict[str] - _CIMultiDictProxy = CIMultiDictProxy[str] - _MultiDict = MultiDict[str] - _MultiDictProxy = MultiDictProxy[str] - from http.cookies import BaseCookie, Morsel - - from .web import Request, StreamResponse -else: - _CIMultiDict = CIMultiDict - _CIMultiDictProxy = CIMultiDictProxy - _MultiDict = MultiDict - _MultiDictProxy = MultiDictProxy - -Byteish = Union[bytes, bytearray, memoryview] -JSONEncoder = Callable[[Any], str] -JSONDecoder = Callable[[str], Any] -LooseHeaders = Union[Mapping[Union[str, istr], str], _CIMultiDict, _CIMultiDictProxy] -RawHeaders = Tuple[Tuple[bytes, bytes], ...] -StrOrURL = Union[str, URL] - -LooseCookiesMappings = Mapping[str, Union[str, "BaseCookie[str]", "Morsel[Any]"]] -LooseCookiesIterables = Iterable[ - Tuple[str, Union[str, "BaseCookie[str]", "Morsel[Any]"]] -] -LooseCookies = Union[ - LooseCookiesMappings, - LooseCookiesIterables, - "BaseCookie[str]", -] - -Handler = Callable[["Request"], Awaitable["StreamResponse"]] - -PathLike = Union[str, "os.PathLike[str]"] diff --git a/.venv/Lib/site-packages/aiohttp/web.py b/.venv/Lib/site-packages/aiohttp/web.py deleted file mode 100644 index 864428b..0000000 --- a/.venv/Lib/site-packages/aiohttp/web.py +++ /dev/null @@ -1,586 +0,0 @@ -import asyncio -import logging -import socket -import sys -from argparse import ArgumentParser -from collections.abc import Iterable -from importlib import import_module -from typing import ( - Any, - Awaitable, - Callable, - Iterable as TypingIterable, - List, - Optional, - Set, - Type, - Union, - cast, -) - -from .abc import AbstractAccessLogger -from .helpers import all_tasks -from .log import access_logger -from .web_app import Application as Application, CleanupError as CleanupError -from .web_exceptions import ( - HTTPAccepted as HTTPAccepted, - HTTPBadGateway as HTTPBadGateway, - HTTPBadRequest as HTTPBadRequest, - HTTPClientError as HTTPClientError, - HTTPConflict as HTTPConflict, - HTTPCreated as HTTPCreated, - HTTPError as HTTPError, - HTTPException as HTTPException, - HTTPExpectationFailed as HTTPExpectationFailed, - HTTPFailedDependency as HTTPFailedDependency, - HTTPForbidden as HTTPForbidden, - HTTPFound as HTTPFound, - HTTPGatewayTimeout as HTTPGatewayTimeout, - HTTPGone as HTTPGone, - HTTPInsufficientStorage as HTTPInsufficientStorage, - HTTPInternalServerError as HTTPInternalServerError, - HTTPLengthRequired as HTTPLengthRequired, - HTTPMethodNotAllowed as HTTPMethodNotAllowed, - HTTPMisdirectedRequest as HTTPMisdirectedRequest, - HTTPMovedPermanently as HTTPMovedPermanently, - HTTPMultipleChoices as HTTPMultipleChoices, - HTTPNetworkAuthenticationRequired as HTTPNetworkAuthenticationRequired, - HTTPNoContent as HTTPNoContent, - HTTPNonAuthoritativeInformation as HTTPNonAuthoritativeInformation, - HTTPNotAcceptable as HTTPNotAcceptable, - HTTPNotExtended as HTTPNotExtended, - HTTPNotFound as HTTPNotFound, - HTTPNotImplemented as HTTPNotImplemented, - HTTPNotModified as HTTPNotModified, - HTTPOk as HTTPOk, - HTTPPartialContent as HTTPPartialContent, - HTTPPaymentRequired as HTTPPaymentRequired, - HTTPPermanentRedirect as HTTPPermanentRedirect, - HTTPPreconditionFailed as HTTPPreconditionFailed, - HTTPPreconditionRequired as HTTPPreconditionRequired, - HTTPProxyAuthenticationRequired as HTTPProxyAuthenticationRequired, - HTTPRedirection as HTTPRedirection, - HTTPRequestEntityTooLarge as HTTPRequestEntityTooLarge, - HTTPRequestHeaderFieldsTooLarge as HTTPRequestHeaderFieldsTooLarge, - HTTPRequestRangeNotSatisfiable as HTTPRequestRangeNotSatisfiable, - HTTPRequestTimeout as HTTPRequestTimeout, - HTTPRequestURITooLong as HTTPRequestURITooLong, - HTTPResetContent as HTTPResetContent, - HTTPSeeOther as HTTPSeeOther, - HTTPServerError as HTTPServerError, - HTTPServiceUnavailable as HTTPServiceUnavailable, - HTTPSuccessful as HTTPSuccessful, - HTTPTemporaryRedirect as HTTPTemporaryRedirect, - HTTPTooManyRequests as HTTPTooManyRequests, - HTTPUnauthorized as HTTPUnauthorized, - HTTPUnavailableForLegalReasons as HTTPUnavailableForLegalReasons, - HTTPUnprocessableEntity as HTTPUnprocessableEntity, - HTTPUnsupportedMediaType as HTTPUnsupportedMediaType, - HTTPUpgradeRequired as HTTPUpgradeRequired, - HTTPUseProxy as HTTPUseProxy, - HTTPVariantAlsoNegotiates as HTTPVariantAlsoNegotiates, - HTTPVersionNotSupported as HTTPVersionNotSupported, -) -from .web_fileresponse import FileResponse as FileResponse -from .web_log import AccessLogger -from .web_middlewares import ( - middleware as middleware, - normalize_path_middleware as normalize_path_middleware, -) -from .web_protocol import ( - PayloadAccessError as PayloadAccessError, - RequestHandler as RequestHandler, - RequestPayloadError as RequestPayloadError, -) -from .web_request import ( - BaseRequest as BaseRequest, - FileField as FileField, - Request as Request, -) -from .web_response import ( - ContentCoding as ContentCoding, - Response as Response, - StreamResponse as StreamResponse, - json_response as json_response, -) -from .web_routedef import ( - AbstractRouteDef as AbstractRouteDef, - RouteDef as RouteDef, - RouteTableDef as RouteTableDef, - StaticDef as StaticDef, - delete as delete, - get as get, - head as head, - options as options, - patch as patch, - post as post, - put as put, - route as route, - static as static, - view as view, -) -from .web_runner import ( - AppRunner as AppRunner, - BaseRunner as BaseRunner, - BaseSite as BaseSite, - GracefulExit as GracefulExit, - NamedPipeSite as NamedPipeSite, - ServerRunner as ServerRunner, - SockSite as SockSite, - TCPSite as TCPSite, - UnixSite as UnixSite, -) -from .web_server import Server as Server -from .web_urldispatcher import ( - AbstractResource as AbstractResource, - AbstractRoute as AbstractRoute, - DynamicResource as DynamicResource, - PlainResource as PlainResource, - Resource as Resource, - ResourceRoute as ResourceRoute, - StaticResource as StaticResource, - UrlDispatcher as UrlDispatcher, - UrlMappingMatchInfo as UrlMappingMatchInfo, - View as View, -) -from .web_ws import ( - WebSocketReady as WebSocketReady, - WebSocketResponse as WebSocketResponse, - WSMsgType as WSMsgType, -) - -__all__ = ( - # web_app - "Application", - "CleanupError", - # web_exceptions - "HTTPAccepted", - "HTTPBadGateway", - "HTTPBadRequest", - "HTTPClientError", - "HTTPConflict", - "HTTPCreated", - "HTTPError", - "HTTPException", - "HTTPExpectationFailed", - "HTTPFailedDependency", - "HTTPForbidden", - "HTTPFound", - "HTTPGatewayTimeout", - "HTTPGone", - "HTTPInsufficientStorage", - "HTTPInternalServerError", - "HTTPLengthRequired", - "HTTPMethodNotAllowed", - "HTTPMisdirectedRequest", - "HTTPMovedPermanently", - "HTTPMultipleChoices", - "HTTPNetworkAuthenticationRequired", - "HTTPNoContent", - "HTTPNonAuthoritativeInformation", - "HTTPNotAcceptable", - "HTTPNotExtended", - "HTTPNotFound", - "HTTPNotImplemented", - "HTTPNotModified", - "HTTPOk", - "HTTPPartialContent", - "HTTPPaymentRequired", - "HTTPPermanentRedirect", - "HTTPPreconditionFailed", - "HTTPPreconditionRequired", - "HTTPProxyAuthenticationRequired", - "HTTPRedirection", - "HTTPRequestEntityTooLarge", - "HTTPRequestHeaderFieldsTooLarge", - "HTTPRequestRangeNotSatisfiable", - "HTTPRequestTimeout", - "HTTPRequestURITooLong", - "HTTPResetContent", - "HTTPSeeOther", - "HTTPServerError", - "HTTPServiceUnavailable", - "HTTPSuccessful", - "HTTPTemporaryRedirect", - "HTTPTooManyRequests", - "HTTPUnauthorized", - "HTTPUnavailableForLegalReasons", - "HTTPUnprocessableEntity", - "HTTPUnsupportedMediaType", - "HTTPUpgradeRequired", - "HTTPUseProxy", - "HTTPVariantAlsoNegotiates", - "HTTPVersionNotSupported", - # web_fileresponse - "FileResponse", - # web_middlewares - "middleware", - "normalize_path_middleware", - # web_protocol - "PayloadAccessError", - "RequestHandler", - "RequestPayloadError", - # web_request - "BaseRequest", - "FileField", - "Request", - # web_response - "ContentCoding", - "Response", - "StreamResponse", - "json_response", - # web_routedef - "AbstractRouteDef", - "RouteDef", - "RouteTableDef", - "StaticDef", - "delete", - "get", - "head", - "options", - "patch", - "post", - "put", - "route", - "static", - "view", - # web_runner - "AppRunner", - "BaseRunner", - "BaseSite", - "GracefulExit", - "ServerRunner", - "SockSite", - "TCPSite", - "UnixSite", - "NamedPipeSite", - # web_server - "Server", - # web_urldispatcher - "AbstractResource", - "AbstractRoute", - "DynamicResource", - "PlainResource", - "Resource", - "ResourceRoute", - "StaticResource", - "UrlDispatcher", - "UrlMappingMatchInfo", - "View", - # web_ws - "WebSocketReady", - "WebSocketResponse", - "WSMsgType", - # web - "run_app", -) - - -try: - from ssl import SSLContext -except ImportError: # pragma: no cover - SSLContext = Any # type: ignore[misc,assignment] - -HostSequence = TypingIterable[str] - - -async def _run_app( - app: Union[Application, Awaitable[Application]], - *, - host: Optional[Union[str, HostSequence]] = None, - port: Optional[int] = None, - path: Optional[str] = None, - sock: Optional[socket.socket] = None, - shutdown_timeout: float = 60.0, - keepalive_timeout: float = 75.0, - ssl_context: Optional[SSLContext] = None, - print: Callable[..., None] = print, - backlog: int = 128, - access_log_class: Type[AbstractAccessLogger] = AccessLogger, - access_log_format: str = AccessLogger.LOG_FORMAT, - access_log: Optional[logging.Logger] = access_logger, - handle_signals: bool = True, - reuse_address: Optional[bool] = None, - reuse_port: Optional[bool] = None, -) -> None: - # A internal functio to actually do all dirty job for application running - if asyncio.iscoroutine(app): - app = await app # type: ignore[misc] - - app = cast(Application, app) - - runner = AppRunner( - app, - handle_signals=handle_signals, - access_log_class=access_log_class, - access_log_format=access_log_format, - access_log=access_log, - keepalive_timeout=keepalive_timeout, - ) - - await runner.setup() - - sites = [] # type: List[BaseSite] - - try: - if host is not None: - if isinstance(host, (str, bytes, bytearray, memoryview)): - sites.append( - TCPSite( - runner, - host, - port, - shutdown_timeout=shutdown_timeout, - ssl_context=ssl_context, - backlog=backlog, - reuse_address=reuse_address, - reuse_port=reuse_port, - ) - ) - else: - for h in host: - sites.append( - TCPSite( - runner, - h, - port, - shutdown_timeout=shutdown_timeout, - ssl_context=ssl_context, - backlog=backlog, - reuse_address=reuse_address, - reuse_port=reuse_port, - ) - ) - elif path is None and sock is None or port is not None: - sites.append( - TCPSite( - runner, - port=port, - shutdown_timeout=shutdown_timeout, - ssl_context=ssl_context, - backlog=backlog, - reuse_address=reuse_address, - reuse_port=reuse_port, - ) - ) - - if path is not None: - if isinstance(path, (str, bytes, bytearray, memoryview)): - sites.append( - UnixSite( - runner, - path, - shutdown_timeout=shutdown_timeout, - ssl_context=ssl_context, - backlog=backlog, - ) - ) - else: - for p in path: - sites.append( - UnixSite( - runner, - p, - shutdown_timeout=shutdown_timeout, - ssl_context=ssl_context, - backlog=backlog, - ) - ) - - if sock is not None: - if not isinstance(sock, Iterable): - sites.append( - SockSite( - runner, - sock, - shutdown_timeout=shutdown_timeout, - ssl_context=ssl_context, - backlog=backlog, - ) - ) - else: - for s in sock: - sites.append( - SockSite( - runner, - s, - shutdown_timeout=shutdown_timeout, - ssl_context=ssl_context, - backlog=backlog, - ) - ) - for site in sites: - await site.start() - - if print: # pragma: no branch - names = sorted(str(s.name) for s in runner.sites) - print( - "======== Running on {} ========\n" - "(Press CTRL+C to quit)".format(", ".join(names)) - ) - - # sleep forever by 1 hour intervals, - # on Windows before Python 3.8 wake up every 1 second to handle - # Ctrl+C smoothly - if sys.platform == "win32" and sys.version_info < (3, 8): - delay = 1 - else: - delay = 3600 - - while True: - await asyncio.sleep(delay) - finally: - await runner.cleanup() - - -def _cancel_tasks( - to_cancel: Set["asyncio.Task[Any]"], loop: asyncio.AbstractEventLoop -) -> None: - if not to_cancel: - return - - for task in to_cancel: - task.cancel() - - loop.run_until_complete(asyncio.gather(*to_cancel, return_exceptions=True)) - - for task in to_cancel: - if task.cancelled(): - continue - if task.exception() is not None: - loop.call_exception_handler( - { - "message": "unhandled exception during asyncio.run() shutdown", - "exception": task.exception(), - "task": task, - } - ) - - -def run_app( - app: Union[Application, Awaitable[Application]], - *, - host: Optional[Union[str, HostSequence]] = None, - port: Optional[int] = None, - path: Optional[str] = None, - sock: Optional[socket.socket] = None, - shutdown_timeout: float = 60.0, - keepalive_timeout: float = 75.0, - ssl_context: Optional[SSLContext] = None, - print: Callable[..., None] = print, - backlog: int = 128, - access_log_class: Type[AbstractAccessLogger] = AccessLogger, - access_log_format: str = AccessLogger.LOG_FORMAT, - access_log: Optional[logging.Logger] = access_logger, - handle_signals: bool = True, - reuse_address: Optional[bool] = None, - reuse_port: Optional[bool] = None, - loop: Optional[asyncio.AbstractEventLoop] = None, -) -> None: - """Run an app locally""" - if loop is None: - loop = asyncio.new_event_loop() - - # Configure if and only if in debugging mode and using the default logger - if loop.get_debug() and access_log and access_log.name == "aiohttp.access": - if access_log.level == logging.NOTSET: - access_log.setLevel(logging.DEBUG) - if not access_log.hasHandlers(): - access_log.addHandler(logging.StreamHandler()) - - main_task = loop.create_task( - _run_app( - app, - host=host, - port=port, - path=path, - sock=sock, - shutdown_timeout=shutdown_timeout, - keepalive_timeout=keepalive_timeout, - ssl_context=ssl_context, - print=print, - backlog=backlog, - access_log_class=access_log_class, - access_log_format=access_log_format, - access_log=access_log, - handle_signals=handle_signals, - reuse_address=reuse_address, - reuse_port=reuse_port, - ) - ) - - try: - asyncio.set_event_loop(loop) - loop.run_until_complete(main_task) - except (GracefulExit, KeyboardInterrupt): # pragma: no cover - pass - finally: - _cancel_tasks({main_task}, loop) - _cancel_tasks(all_tasks(loop), loop) - loop.run_until_complete(loop.shutdown_asyncgens()) - loop.close() - - -def main(argv: List[str]) -> None: - arg_parser = ArgumentParser( - description="aiohttp.web Application server", prog="aiohttp.web" - ) - arg_parser.add_argument( - "entry_func", - help=( - "Callable returning the `aiohttp.web.Application` instance to " - "run. Should be specified in the 'module:function' syntax." - ), - metavar="entry-func", - ) - arg_parser.add_argument( - "-H", - "--hostname", - help="TCP/IP hostname to serve on (default: %(default)r)", - default="localhost", - ) - arg_parser.add_argument( - "-P", - "--port", - help="TCP/IP port to serve on (default: %(default)r)", - type=int, - default="8080", - ) - arg_parser.add_argument( - "-U", - "--path", - help="Unix file system path to serve on. Specifying a path will cause " - "hostname and port arguments to be ignored.", - ) - args, extra_argv = arg_parser.parse_known_args(argv) - - # Import logic - mod_str, _, func_str = args.entry_func.partition(":") - if not func_str or not mod_str: - arg_parser.error("'entry-func' not in 'module:function' syntax") - if mod_str.startswith("."): - arg_parser.error("relative module names not supported") - try: - module = import_module(mod_str) - except ImportError as ex: - arg_parser.error(f"unable to import {mod_str}: {ex}") - try: - func = getattr(module, func_str) - except AttributeError: - arg_parser.error(f"module {mod_str!r} has no attribute {func_str!r}") - - # Compatibility logic - if args.path is not None and not hasattr(socket, "AF_UNIX"): - arg_parser.error( - "file system paths not supported by your operating" " environment" - ) - - logging.basicConfig(level=logging.DEBUG) - - app = func(extra_argv) - run_app(app, host=args.hostname, port=args.port, path=args.path) - arg_parser.exit(message="Stopped\n") - - -if __name__ == "__main__": # pragma: no branch - main(sys.argv[1:]) # pragma: no cover diff --git a/.venv/Lib/site-packages/aiohttp/web_app.py b/.venv/Lib/site-packages/aiohttp/web_app.py deleted file mode 100644 index d5dc90e..0000000 --- a/.venv/Lib/site-packages/aiohttp/web_app.py +++ /dev/null @@ -1,557 +0,0 @@ -import asyncio -import logging -import warnings -from functools import partial, update_wrapper -from typing import ( - TYPE_CHECKING, - Any, - AsyncIterator, - Awaitable, - Callable, - Dict, - Iterable, - Iterator, - List, - Mapping, - MutableMapping, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) - -from aiosignal import Signal -from frozenlist import FrozenList - -from . import hdrs -from .abc import ( - AbstractAccessLogger, - AbstractMatchInfo, - AbstractRouter, - AbstractStreamWriter, -) -from .helpers import DEBUG -from .http_parser import RawRequestMessage -from .log import web_logger -from .streams import StreamReader -from .web_log import AccessLogger -from .web_middlewares import _fix_request_current_app -from .web_protocol import RequestHandler -from .web_request import Request -from .web_response import StreamResponse -from .web_routedef import AbstractRouteDef -from .web_server import Server -from .web_urldispatcher import ( - AbstractResource, - AbstractRoute, - Domain, - MaskDomain, - MatchedSubAppResource, - PrefixedSubAppResource, - UrlDispatcher, -) - -__all__ = ("Application", "CleanupError") - - -if TYPE_CHECKING: # pragma: no cover - from .typedefs import Handler - - _AppSignal = Signal[Callable[["Application"], Awaitable[None]]] - _RespPrepareSignal = Signal[Callable[[Request, StreamResponse], Awaitable[None]]] - _Middleware = Union[ - Callable[[Request, Handler], Awaitable[StreamResponse]], - Callable[["Application", Handler], Awaitable[Handler]], # old-style - ] - _Middlewares = FrozenList[_Middleware] - _MiddlewaresHandlers = Optional[Sequence[Tuple[_Middleware, bool]]] - _Subapps = List["Application"] -else: - # No type checker mode, skip types - _AppSignal = Signal - _RespPrepareSignal = Signal - _Middleware = Callable - _Middlewares = FrozenList - _MiddlewaresHandlers = Optional[Sequence] - _Subapps = List - - -class Application(MutableMapping[str, Any]): - ATTRS = frozenset( - [ - "logger", - "_debug", - "_router", - "_loop", - "_handler_args", - "_middlewares", - "_middlewares_handlers", - "_run_middlewares", - "_state", - "_frozen", - "_pre_frozen", - "_subapps", - "_on_response_prepare", - "_on_startup", - "_on_shutdown", - "_on_cleanup", - "_client_max_size", - "_cleanup_ctx", - ] - ) - - def __init__( - self, - *, - logger: logging.Logger = web_logger, - router: Optional[UrlDispatcher] = None, - middlewares: Iterable[_Middleware] = (), - handler_args: Optional[Mapping[str, Any]] = None, - client_max_size: int = 1024 ** 2, - loop: Optional[asyncio.AbstractEventLoop] = None, - debug: Any = ..., # mypy doesn't support ellipsis - ) -> None: - if router is None: - router = UrlDispatcher() - else: - warnings.warn( - "router argument is deprecated", DeprecationWarning, stacklevel=2 - ) - assert isinstance(router, AbstractRouter), router - - if loop is not None: - warnings.warn( - "loop argument is deprecated", DeprecationWarning, stacklevel=2 - ) - - if debug is not ...: - warnings.warn( - "debug argument is deprecated", DeprecationWarning, stacklevel=2 - ) - self._debug = debug - self._router = router # type: UrlDispatcher - self._loop = loop - self._handler_args = handler_args - self.logger = logger - - self._middlewares = FrozenList(middlewares) # type: _Middlewares - - # initialized on freezing - self._middlewares_handlers = None # type: _MiddlewaresHandlers - # initialized on freezing - self._run_middlewares = None # type: Optional[bool] - - self._state = {} # type: Dict[str, Any] - self._frozen = False - self._pre_frozen = False - self._subapps = [] # type: _Subapps - - self._on_response_prepare = Signal(self) # type: _RespPrepareSignal - self._on_startup = Signal(self) # type: _AppSignal - self._on_shutdown = Signal(self) # type: _AppSignal - self._on_cleanup = Signal(self) # type: _AppSignal - self._cleanup_ctx = CleanupContext() - self._on_startup.append(self._cleanup_ctx._on_startup) - self._on_cleanup.append(self._cleanup_ctx._on_cleanup) - self._client_max_size = client_max_size - - def __init_subclass__(cls: Type["Application"]) -> None: - warnings.warn( - "Inheritance class {} from web.Application " - "is discouraged".format(cls.__name__), - DeprecationWarning, - stacklevel=2, - ) - - if DEBUG: # pragma: no cover - - def __setattr__(self, name: str, val: Any) -> None: - if name not in self.ATTRS: - warnings.warn( - "Setting custom web.Application.{} attribute " - "is discouraged".format(name), - DeprecationWarning, - stacklevel=2, - ) - super().__setattr__(name, val) - - # MutableMapping API - - def __eq__(self, other: object) -> bool: - return self is other - - def __getitem__(self, key: str) -> Any: - return self._state[key] - - def _check_frozen(self) -> None: - if self._frozen: - warnings.warn( - "Changing state of started or joined " "application is deprecated", - DeprecationWarning, - stacklevel=3, - ) - - def __setitem__(self, key: str, value: Any) -> None: - self._check_frozen() - self._state[key] = value - - def __delitem__(self, key: str) -> None: - self._check_frozen() - del self._state[key] - - def __len__(self) -> int: - return len(self._state) - - def __iter__(self) -> Iterator[str]: - return iter(self._state) - - ######## - @property - def loop(self) -> asyncio.AbstractEventLoop: - # Technically the loop can be None - # but we mask it by explicit type cast - # to provide more convinient type annotation - warnings.warn("loop property is deprecated", DeprecationWarning, stacklevel=2) - return cast(asyncio.AbstractEventLoop, self._loop) - - def _set_loop(self, loop: Optional[asyncio.AbstractEventLoop]) -> None: - if loop is None: - loop = asyncio.get_event_loop() - if self._loop is not None and self._loop is not loop: - raise RuntimeError( - "web.Application instance initialized with different loop" - ) - - self._loop = loop - - # set loop debug - if self._debug is ...: - self._debug = loop.get_debug() - - # set loop to sub applications - for subapp in self._subapps: - subapp._set_loop(loop) - - @property - def pre_frozen(self) -> bool: - return self._pre_frozen - - def pre_freeze(self) -> None: - if self._pre_frozen: - return - - self._pre_frozen = True - self._middlewares.freeze() - self._router.freeze() - self._on_response_prepare.freeze() - self._cleanup_ctx.freeze() - self._on_startup.freeze() - self._on_shutdown.freeze() - self._on_cleanup.freeze() - self._middlewares_handlers = tuple(self._prepare_middleware()) - - # If current app and any subapp do not have middlewares avoid run all - # of the code footprint that it implies, which have a middleware - # hardcoded per app that sets up the current_app attribute. If no - # middlewares are configured the handler will receive the proper - # current_app without needing all of this code. - self._run_middlewares = True if self.middlewares else False - - for subapp in self._subapps: - subapp.pre_freeze() - self._run_middlewares = self._run_middlewares or subapp._run_middlewares - - @property - def frozen(self) -> bool: - return self._frozen - - def freeze(self) -> None: - if self._frozen: - return - - self.pre_freeze() - self._frozen = True - for subapp in self._subapps: - subapp.freeze() - - @property - def debug(self) -> bool: - warnings.warn("debug property is deprecated", DeprecationWarning, stacklevel=2) - return self._debug # type: ignore[no-any-return] - - def _reg_subapp_signals(self, subapp: "Application") -> None: - def reg_handler(signame: str) -> None: - subsig = getattr(subapp, signame) - - async def handler(app: "Application") -> None: - await subsig.send(subapp) - - appsig = getattr(self, signame) - appsig.append(handler) - - reg_handler("on_startup") - reg_handler("on_shutdown") - reg_handler("on_cleanup") - - def add_subapp(self, prefix: str, subapp: "Application") -> AbstractResource: - if not isinstance(prefix, str): - raise TypeError("Prefix must be str") - prefix = prefix.rstrip("/") - if not prefix: - raise ValueError("Prefix cannot be empty") - factory = partial(PrefixedSubAppResource, prefix, subapp) - return self._add_subapp(factory, subapp) - - def _add_subapp( - self, resource_factory: Callable[[], AbstractResource], subapp: "Application" - ) -> AbstractResource: - if self.frozen: - raise RuntimeError("Cannot add sub application to frozen application") - if subapp.frozen: - raise RuntimeError("Cannot add frozen application") - resource = resource_factory() - self.router.register_resource(resource) - self._reg_subapp_signals(subapp) - self._subapps.append(subapp) - subapp.pre_freeze() - if self._loop is not None: - subapp._set_loop(self._loop) - return resource - - def add_domain(self, domain: str, subapp: "Application") -> AbstractResource: - if not isinstance(domain, str): - raise TypeError("Domain must be str") - elif "*" in domain: - rule = MaskDomain(domain) # type: Domain - else: - rule = Domain(domain) - factory = partial(MatchedSubAppResource, rule, subapp) - return self._add_subapp(factory, subapp) - - def add_routes(self, routes: Iterable[AbstractRouteDef]) -> List[AbstractRoute]: - return self.router.add_routes(routes) - - @property - def on_response_prepare(self) -> _RespPrepareSignal: - return self._on_response_prepare - - @property - def on_startup(self) -> _AppSignal: - return self._on_startup - - @property - def on_shutdown(self) -> _AppSignal: - return self._on_shutdown - - @property - def on_cleanup(self) -> _AppSignal: - return self._on_cleanup - - @property - def cleanup_ctx(self) -> "CleanupContext": - return self._cleanup_ctx - - @property - def router(self) -> UrlDispatcher: - return self._router - - @property - def middlewares(self) -> _Middlewares: - return self._middlewares - - def _make_handler( - self, - *, - loop: Optional[asyncio.AbstractEventLoop] = None, - access_log_class: Type[AbstractAccessLogger] = AccessLogger, - **kwargs: Any, - ) -> Server: - - if not issubclass(access_log_class, AbstractAccessLogger): - raise TypeError( - "access_log_class must be subclass of " - "aiohttp.abc.AbstractAccessLogger, got {}".format(access_log_class) - ) - - self._set_loop(loop) - self.freeze() - - kwargs["debug"] = self._debug - kwargs["access_log_class"] = access_log_class - if self._handler_args: - for k, v in self._handler_args.items(): - kwargs[k] = v - - return Server( - self._handle, # type: ignore[arg-type] - request_factory=self._make_request, - loop=self._loop, - **kwargs, - ) - - def make_handler( - self, - *, - loop: Optional[asyncio.AbstractEventLoop] = None, - access_log_class: Type[AbstractAccessLogger] = AccessLogger, - **kwargs: Any, - ) -> Server: - - warnings.warn( - "Application.make_handler(...) is deprecated, " "use AppRunner API instead", - DeprecationWarning, - stacklevel=2, - ) - - return self._make_handler( - loop=loop, access_log_class=access_log_class, **kwargs - ) - - async def startup(self) -> None: - """Causes on_startup signal - - Should be called in the event loop along with the request handler. - """ - await self.on_startup.send(self) - - async def shutdown(self) -> None: - """Causes on_shutdown signal - - Should be called before cleanup() - """ - await self.on_shutdown.send(self) - - async def cleanup(self) -> None: - """Causes on_cleanup signal - - Should be called after shutdown() - """ - if self.on_cleanup.frozen: - await self.on_cleanup.send(self) - else: - # If an exception occurs in startup, ensure cleanup contexts are completed. - await self._cleanup_ctx._on_cleanup(self) - - def _make_request( - self, - message: RawRequestMessage, - payload: StreamReader, - protocol: RequestHandler, - writer: AbstractStreamWriter, - task: "asyncio.Task[None]", - _cls: Type[Request] = Request, - ) -> Request: - return _cls( - message, - payload, - protocol, - writer, - task, - self._loop, - client_max_size=self._client_max_size, - ) - - def _prepare_middleware(self) -> Iterator[Tuple[_Middleware, bool]]: - for m in reversed(self._middlewares): - if getattr(m, "__middleware_version__", None) == 1: - yield m, True - else: - warnings.warn( - 'old-style middleware "{!r}" deprecated, ' "see #2252".format(m), - DeprecationWarning, - stacklevel=2, - ) - yield m, False - - yield _fix_request_current_app(self), True - - async def _handle(self, request: Request) -> StreamResponse: - loop = asyncio.get_event_loop() - debug = loop.get_debug() - match_info = await self._router.resolve(request) - if debug: # pragma: no cover - if not isinstance(match_info, AbstractMatchInfo): - raise TypeError( - "match_info should be AbstractMatchInfo " - "instance, not {!r}".format(match_info) - ) - match_info.add_app(self) - - match_info.freeze() - - resp = None - request._match_info = match_info - expect = request.headers.get(hdrs.EXPECT) - if expect: - resp = await match_info.expect_handler(request) - await request.writer.drain() - - if resp is None: - handler = match_info.handler - - if self._run_middlewares: - for app in match_info.apps[::-1]: - for m, new_style in app._middlewares_handlers: # type: ignore[union-attr] # noqa - if new_style: - handler = update_wrapper( - partial(m, handler=handler), handler - ) - else: - handler = await m(app, handler) # type: ignore[arg-type] - - resp = await handler(request) - - return resp - - def __call__(self) -> "Application": - """gunicorn compatibility""" - return self - - def __repr__(self) -> str: - return f"" - - def __bool__(self) -> bool: - return True - - -class CleanupError(RuntimeError): - @property - def exceptions(self) -> List[BaseException]: - return cast(List[BaseException], self.args[1]) - - -if TYPE_CHECKING: # pragma: no cover - _CleanupContextBase = FrozenList[Callable[[Application], AsyncIterator[None]]] -else: - _CleanupContextBase = FrozenList - - -class CleanupContext(_CleanupContextBase): - def __init__(self) -> None: - super().__init__() - self._exits = [] # type: List[AsyncIterator[None]] - - async def _on_startup(self, app: Application) -> None: - for cb in self: - it = cb(app).__aiter__() - await it.__anext__() - self._exits.append(it) - - async def _on_cleanup(self, app: Application) -> None: - errors = [] - for it in reversed(self._exits): - try: - await it.__anext__() - except StopAsyncIteration: - pass - except Exception as exc: - errors.append(exc) - else: - errors.append(RuntimeError(f"{it!r} has more than one 'yield'")) - if errors: - if len(errors) == 1: - raise errors[0] - else: - raise CleanupError("Multiple errors on cleanup stage", errors) diff --git a/.venv/Lib/site-packages/aiohttp/web_exceptions.py b/.venv/Lib/site-packages/aiohttp/web_exceptions.py deleted file mode 100644 index 2eadca0..0000000 --- a/.venv/Lib/site-packages/aiohttp/web_exceptions.py +++ /dev/null @@ -1,441 +0,0 @@ -import warnings -from typing import Any, Dict, Iterable, List, Optional, Set # noqa - -from yarl import URL - -from .typedefs import LooseHeaders, StrOrURL -from .web_response import Response - -__all__ = ( - "HTTPException", - "HTTPError", - "HTTPRedirection", - "HTTPSuccessful", - "HTTPOk", - "HTTPCreated", - "HTTPAccepted", - "HTTPNonAuthoritativeInformation", - "HTTPNoContent", - "HTTPResetContent", - "HTTPPartialContent", - "HTTPMultipleChoices", - "HTTPMovedPermanently", - "HTTPFound", - "HTTPSeeOther", - "HTTPNotModified", - "HTTPUseProxy", - "HTTPTemporaryRedirect", - "HTTPPermanentRedirect", - "HTTPClientError", - "HTTPBadRequest", - "HTTPUnauthorized", - "HTTPPaymentRequired", - "HTTPForbidden", - "HTTPNotFound", - "HTTPMethodNotAllowed", - "HTTPNotAcceptable", - "HTTPProxyAuthenticationRequired", - "HTTPRequestTimeout", - "HTTPConflict", - "HTTPGone", - "HTTPLengthRequired", - "HTTPPreconditionFailed", - "HTTPRequestEntityTooLarge", - "HTTPRequestURITooLong", - "HTTPUnsupportedMediaType", - "HTTPRequestRangeNotSatisfiable", - "HTTPExpectationFailed", - "HTTPMisdirectedRequest", - "HTTPUnprocessableEntity", - "HTTPFailedDependency", - "HTTPUpgradeRequired", - "HTTPPreconditionRequired", - "HTTPTooManyRequests", - "HTTPRequestHeaderFieldsTooLarge", - "HTTPUnavailableForLegalReasons", - "HTTPServerError", - "HTTPInternalServerError", - "HTTPNotImplemented", - "HTTPBadGateway", - "HTTPServiceUnavailable", - "HTTPGatewayTimeout", - "HTTPVersionNotSupported", - "HTTPVariantAlsoNegotiates", - "HTTPInsufficientStorage", - "HTTPNotExtended", - "HTTPNetworkAuthenticationRequired", -) - - -############################################################ -# HTTP Exceptions -############################################################ - - -class HTTPException(Response, Exception): - - # You should set in subclasses: - # status = 200 - - status_code = -1 - empty_body = False - - __http_exception__ = True - - def __init__( - self, - *, - headers: Optional[LooseHeaders] = None, - reason: Optional[str] = None, - body: Any = None, - text: Optional[str] = None, - content_type: Optional[str] = None, - ) -> None: - if body is not None: - warnings.warn( - "body argument is deprecated for http web exceptions", - DeprecationWarning, - ) - Response.__init__( - self, - status=self.status_code, - headers=headers, - reason=reason, - body=body, - text=text, - content_type=content_type, - ) - Exception.__init__(self, self.reason) - if self.body is None and not self.empty_body: - self.text = f"{self.status}: {self.reason}" - - def __bool__(self) -> bool: - return True - - -class HTTPError(HTTPException): - """Base class for exceptions with status codes in the 400s and 500s.""" - - -class HTTPRedirection(HTTPException): - """Base class for exceptions with status codes in the 300s.""" - - -class HTTPSuccessful(HTTPException): - """Base class for exceptions with status codes in the 200s.""" - - -class HTTPOk(HTTPSuccessful): - status_code = 200 - - -class HTTPCreated(HTTPSuccessful): - status_code = 201 - - -class HTTPAccepted(HTTPSuccessful): - status_code = 202 - - -class HTTPNonAuthoritativeInformation(HTTPSuccessful): - status_code = 203 - - -class HTTPNoContent(HTTPSuccessful): - status_code = 204 - empty_body = True - - -class HTTPResetContent(HTTPSuccessful): - status_code = 205 - empty_body = True - - -class HTTPPartialContent(HTTPSuccessful): - status_code = 206 - - -############################################################ -# 3xx redirection -############################################################ - - -class _HTTPMove(HTTPRedirection): - def __init__( - self, - location: StrOrURL, - *, - headers: Optional[LooseHeaders] = None, - reason: Optional[str] = None, - body: Any = None, - text: Optional[str] = None, - content_type: Optional[str] = None, - ) -> None: - if not location: - raise ValueError("HTTP redirects need a location to redirect to.") - super().__init__( - headers=headers, - reason=reason, - body=body, - text=text, - content_type=content_type, - ) - self.headers["Location"] = str(URL(location)) - self.location = location - - -class HTTPMultipleChoices(_HTTPMove): - status_code = 300 - - -class HTTPMovedPermanently(_HTTPMove): - status_code = 301 - - -class HTTPFound(_HTTPMove): - status_code = 302 - - -# This one is safe after a POST (the redirected location will be -# retrieved with GET): -class HTTPSeeOther(_HTTPMove): - status_code = 303 - - -class HTTPNotModified(HTTPRedirection): - # FIXME: this should include a date or etag header - status_code = 304 - empty_body = True - - -class HTTPUseProxy(_HTTPMove): - # Not a move, but looks a little like one - status_code = 305 - - -class HTTPTemporaryRedirect(_HTTPMove): - status_code = 307 - - -class HTTPPermanentRedirect(_HTTPMove): - status_code = 308 - - -############################################################ -# 4xx client error -############################################################ - - -class HTTPClientError(HTTPError): - pass - - -class HTTPBadRequest(HTTPClientError): - status_code = 400 - - -class HTTPUnauthorized(HTTPClientError): - status_code = 401 - - -class HTTPPaymentRequired(HTTPClientError): - status_code = 402 - - -class HTTPForbidden(HTTPClientError): - status_code = 403 - - -class HTTPNotFound(HTTPClientError): - status_code = 404 - - -class HTTPMethodNotAllowed(HTTPClientError): - status_code = 405 - - def __init__( - self, - method: str, - allowed_methods: Iterable[str], - *, - headers: Optional[LooseHeaders] = None, - reason: Optional[str] = None, - body: Any = None, - text: Optional[str] = None, - content_type: Optional[str] = None, - ) -> None: - allow = ",".join(sorted(allowed_methods)) - super().__init__( - headers=headers, - reason=reason, - body=body, - text=text, - content_type=content_type, - ) - self.headers["Allow"] = allow - self.allowed_methods = set(allowed_methods) # type: Set[str] - self.method = method.upper() - - -class HTTPNotAcceptable(HTTPClientError): - status_code = 406 - - -class HTTPProxyAuthenticationRequired(HTTPClientError): - status_code = 407 - - -class HTTPRequestTimeout(HTTPClientError): - status_code = 408 - - -class HTTPConflict(HTTPClientError): - status_code = 409 - - -class HTTPGone(HTTPClientError): - status_code = 410 - - -class HTTPLengthRequired(HTTPClientError): - status_code = 411 - - -class HTTPPreconditionFailed(HTTPClientError): - status_code = 412 - - -class HTTPRequestEntityTooLarge(HTTPClientError): - status_code = 413 - - def __init__(self, max_size: float, actual_size: float, **kwargs: Any) -> None: - kwargs.setdefault( - "text", - "Maximum request body size {} exceeded, " - "actual body size {}".format(max_size, actual_size), - ) - super().__init__(**kwargs) - - -class HTTPRequestURITooLong(HTTPClientError): - status_code = 414 - - -class HTTPUnsupportedMediaType(HTTPClientError): - status_code = 415 - - -class HTTPRequestRangeNotSatisfiable(HTTPClientError): - status_code = 416 - - -class HTTPExpectationFailed(HTTPClientError): - status_code = 417 - - -class HTTPMisdirectedRequest(HTTPClientError): - status_code = 421 - - -class HTTPUnprocessableEntity(HTTPClientError): - status_code = 422 - - -class HTTPFailedDependency(HTTPClientError): - status_code = 424 - - -class HTTPUpgradeRequired(HTTPClientError): - status_code = 426 - - -class HTTPPreconditionRequired(HTTPClientError): - status_code = 428 - - -class HTTPTooManyRequests(HTTPClientError): - status_code = 429 - - -class HTTPRequestHeaderFieldsTooLarge(HTTPClientError): - status_code = 431 - - -class HTTPUnavailableForLegalReasons(HTTPClientError): - status_code = 451 - - def __init__( - self, - link: str, - *, - headers: Optional[LooseHeaders] = None, - reason: Optional[str] = None, - body: Any = None, - text: Optional[str] = None, - content_type: Optional[str] = None, - ) -> None: - super().__init__( - headers=headers, - reason=reason, - body=body, - text=text, - content_type=content_type, - ) - self.headers["Link"] = '<%s>; rel="blocked-by"' % link - self.link = link - - -############################################################ -# 5xx Server Error -############################################################ -# Response status codes beginning with the digit "5" indicate cases in -# which the server is aware that it has erred or is incapable of -# performing the request. Except when responding to a HEAD request, the -# server SHOULD include an entity containing an explanation of the error -# situation, and whether it is a temporary or permanent condition. User -# agents SHOULD display any included entity to the user. These response -# codes are applicable to any request method. - - -class HTTPServerError(HTTPError): - pass - - -class HTTPInternalServerError(HTTPServerError): - status_code = 500 - - -class HTTPNotImplemented(HTTPServerError): - status_code = 501 - - -class HTTPBadGateway(HTTPServerError): - status_code = 502 - - -class HTTPServiceUnavailable(HTTPServerError): - status_code = 503 - - -class HTTPGatewayTimeout(HTTPServerError): - status_code = 504 - - -class HTTPVersionNotSupported(HTTPServerError): - status_code = 505 - - -class HTTPVariantAlsoNegotiates(HTTPServerError): - status_code = 506 - - -class HTTPInsufficientStorage(HTTPServerError): - status_code = 507 - - -class HTTPNotExtended(HTTPServerError): - status_code = 510 - - -class HTTPNetworkAuthenticationRequired(HTTPServerError): - status_code = 511 diff --git a/.venv/Lib/site-packages/aiohttp/web_fileresponse.py b/.venv/Lib/site-packages/aiohttp/web_fileresponse.py deleted file mode 100644 index f41ed3f..0000000 --- a/.venv/Lib/site-packages/aiohttp/web_fileresponse.py +++ /dev/null @@ -1,288 +0,0 @@ -import asyncio -import mimetypes -import os -import pathlib -import sys -from typing import ( # noqa - IO, - TYPE_CHECKING, - Any, - Awaitable, - Callable, - Iterator, - List, - Optional, - Tuple, - Union, - cast, -) - -from . import hdrs -from .abc import AbstractStreamWriter -from .helpers import ETAG_ANY, ETag -from .typedefs import Final, LooseHeaders -from .web_exceptions import ( - HTTPNotModified, - HTTPPartialContent, - HTTPPreconditionFailed, - HTTPRequestRangeNotSatisfiable, -) -from .web_response import StreamResponse - -__all__ = ("FileResponse",) - -if TYPE_CHECKING: # pragma: no cover - from .web_request import BaseRequest - - -_T_OnChunkSent = Optional[Callable[[bytes], Awaitable[None]]] - - -NOSENDFILE: Final[bool] = bool(os.environ.get("AIOHTTP_NOSENDFILE")) - - -class FileResponse(StreamResponse): - """A response object can be used to send files.""" - - def __init__( - self, - path: Union[str, pathlib.Path], - chunk_size: int = 256 * 1024, - status: int = 200, - reason: Optional[str] = None, - headers: Optional[LooseHeaders] = None, - ) -> None: - super().__init__(status=status, reason=reason, headers=headers) - - if isinstance(path, str): - path = pathlib.Path(path) - - self._path = path - self._chunk_size = chunk_size - - async def _sendfile_fallback( - self, writer: AbstractStreamWriter, fobj: IO[Any], offset: int, count: int - ) -> AbstractStreamWriter: - # To keep memory usage low,fobj is transferred in chunks - # controlled by the constructor's chunk_size argument. - - chunk_size = self._chunk_size - loop = asyncio.get_event_loop() - - await loop.run_in_executor(None, fobj.seek, offset) - - chunk = await loop.run_in_executor(None, fobj.read, chunk_size) - while chunk: - await writer.write(chunk) - count = count - chunk_size - if count <= 0: - break - chunk = await loop.run_in_executor(None, fobj.read, min(chunk_size, count)) - - await writer.drain() - return writer - - async def _sendfile( - self, request: "BaseRequest", fobj: IO[Any], offset: int, count: int - ) -> AbstractStreamWriter: - writer = await super().prepare(request) - assert writer is not None - - if NOSENDFILE or sys.version_info < (3, 7) or self.compression: - return await self._sendfile_fallback(writer, fobj, offset, count) - - loop = request._loop - transport = request.transport - assert transport is not None - - try: - await loop.sendfile(transport, fobj, offset, count) - except NotImplementedError: - return await self._sendfile_fallback(writer, fobj, offset, count) - - await super().write_eof() - return writer - - @staticmethod - def _strong_etag_match(etag_value: str, etags: Tuple[ETag, ...]) -> bool: - if len(etags) == 1 and etags[0].value == ETAG_ANY: - return True - return any(etag.value == etag_value for etag in etags if not etag.is_weak) - - async def _not_modified( - self, request: "BaseRequest", etag_value: str, last_modified: float - ) -> Optional[AbstractStreamWriter]: - self.set_status(HTTPNotModified.status_code) - self._length_check = False - self.etag = etag_value # type: ignore[assignment] - self.last_modified = last_modified # type: ignore[assignment] - # Delete any Content-Length headers provided by user. HTTP 304 - # should always have empty response body - return await super().prepare(request) - - async def _precondition_failed( - self, request: "BaseRequest" - ) -> Optional[AbstractStreamWriter]: - self.set_status(HTTPPreconditionFailed.status_code) - self.content_length = 0 - return await super().prepare(request) - - async def prepare(self, request: "BaseRequest") -> Optional[AbstractStreamWriter]: - filepath = self._path - - gzip = False - if "gzip" in request.headers.get(hdrs.ACCEPT_ENCODING, ""): - gzip_path = filepath.with_name(filepath.name + ".gz") - - if gzip_path.is_file(): - filepath = gzip_path - gzip = True - - loop = asyncio.get_event_loop() - st: os.stat_result = await loop.run_in_executor(None, filepath.stat) - - etag_value = f"{st.st_mtime_ns:x}-{st.st_size:x}" - last_modified = st.st_mtime - - # https://tools.ietf.org/html/rfc7232#section-6 - ifmatch = request.if_match - if ifmatch is not None and not self._strong_etag_match(etag_value, ifmatch): - return await self._precondition_failed(request) - - unmodsince = request.if_unmodified_since - if ( - unmodsince is not None - and ifmatch is None - and st.st_mtime > unmodsince.timestamp() - ): - return await self._precondition_failed(request) - - ifnonematch = request.if_none_match - if ifnonematch is not None and self._strong_etag_match(etag_value, ifnonematch): - return await self._not_modified(request, etag_value, last_modified) - - modsince = request.if_modified_since - if ( - modsince is not None - and ifnonematch is None - and st.st_mtime <= modsince.timestamp() - ): - return await self._not_modified(request, etag_value, last_modified) - - if hdrs.CONTENT_TYPE not in self.headers: - ct, encoding = mimetypes.guess_type(str(filepath)) - if not ct: - ct = "application/octet-stream" - should_set_ct = True - else: - encoding = "gzip" if gzip else None - should_set_ct = False - - status = self._status - file_size = st.st_size - count = file_size - - start = None - - ifrange = request.if_range - if ifrange is None or st.st_mtime <= ifrange.timestamp(): - # If-Range header check: - # condition = cached date >= last modification date - # return 206 if True else 200. - # if False: - # Range header would not be processed, return 200 - # if True but Range header missing - # return 200 - try: - rng = request.http_range - start = rng.start - end = rng.stop - except ValueError: - # https://tools.ietf.org/html/rfc7233: - # A server generating a 416 (Range Not Satisfiable) response to - # a byte-range request SHOULD send a Content-Range header field - # with an unsatisfied-range value. - # The complete-length in a 416 response indicates the current - # length of the selected representation. - # - # Will do the same below. Many servers ignore this and do not - # send a Content-Range header with HTTP 416 - self.headers[hdrs.CONTENT_RANGE] = f"bytes */{file_size}" - self.set_status(HTTPRequestRangeNotSatisfiable.status_code) - return await super().prepare(request) - - # If a range request has been made, convert start, end slice - # notation into file pointer offset and count - if start is not None or end is not None: - if start < 0 and end is None: # return tail of file - start += file_size - if start < 0: - # if Range:bytes=-1000 in request header but file size - # is only 200, there would be trouble without this - start = 0 - count = file_size - start - else: - # rfc7233:If the last-byte-pos value is - # absent, or if the value is greater than or equal to - # the current length of the representation data, - # the byte range is interpreted as the remainder - # of the representation (i.e., the server replaces the - # value of last-byte-pos with a value that is one less than - # the current length of the selected representation). - count = ( - min(end if end is not None else file_size, file_size) - start - ) - - if start >= file_size: - # HTTP 416 should be returned in this case. - # - # According to https://tools.ietf.org/html/rfc7233: - # If a valid byte-range-set includes at least one - # byte-range-spec with a first-byte-pos that is less than - # the current length of the representation, or at least one - # suffix-byte-range-spec with a non-zero suffix-length, - # then the byte-range-set is satisfiable. Otherwise, the - # byte-range-set is unsatisfiable. - self.headers[hdrs.CONTENT_RANGE] = f"bytes */{file_size}" - self.set_status(HTTPRequestRangeNotSatisfiable.status_code) - return await super().prepare(request) - - status = HTTPPartialContent.status_code - # Even though you are sending the whole file, you should still - # return a HTTP 206 for a Range request. - self.set_status(status) - - if should_set_ct: - self.content_type = ct # type: ignore[assignment] - if encoding: - self.headers[hdrs.CONTENT_ENCODING] = encoding - if gzip: - self.headers[hdrs.VARY] = hdrs.ACCEPT_ENCODING - - self.etag = etag_value # type: ignore[assignment] - self.last_modified = st.st_mtime # type: ignore[assignment] - self.content_length = count - - self.headers[hdrs.ACCEPT_RANGES] = "bytes" - - real_start = cast(int, start) - - if status == HTTPPartialContent.status_code: - self.headers[hdrs.CONTENT_RANGE] = "bytes {}-{}/{}".format( - real_start, real_start + count - 1, file_size - ) - - # If we are sending 0 bytes calling sendfile() will throw a ValueError - if count == 0 or request.method == hdrs.METH_HEAD or self.status in [204, 304]: - return await super().prepare(request) - - fobj = await loop.run_in_executor(None, filepath.open, "rb") - if start: # be aware that start could be None or int=0 here. - offset = start - else: - offset = 0 - - try: - return await self._sendfile(request, fobj, offset, count) - finally: - await loop.run_in_executor(None, fobj.close) diff --git a/.venv/Lib/site-packages/aiohttp/web_log.py b/.venv/Lib/site-packages/aiohttp/web_log.py deleted file mode 100644 index a977c1b..0000000 --- a/.venv/Lib/site-packages/aiohttp/web_log.py +++ /dev/null @@ -1,208 +0,0 @@ -import datetime -import functools -import logging -import os -import re -from collections import namedtuple -from typing import Any, Callable, Dict, Iterable, List, Tuple # noqa - -from .abc import AbstractAccessLogger -from .web_request import BaseRequest -from .web_response import StreamResponse - -KeyMethod = namedtuple("KeyMethod", "key method") - - -class AccessLogger(AbstractAccessLogger): - """Helper object to log access. - - Usage: - log = logging.getLogger("spam") - log_format = "%a %{User-Agent}i" - access_logger = AccessLogger(log, log_format) - access_logger.log(request, response, time) - - Format: - %% The percent sign - %a Remote IP-address (IP-address of proxy if using reverse proxy) - %t Time when the request was started to process - %P The process ID of the child that serviced the request - %r First line of request - %s Response status code - %b Size of response in bytes, including HTTP headers - %T Time taken to serve the request, in seconds - %Tf Time taken to serve the request, in seconds with floating fraction - in .06f format - %D Time taken to serve the request, in microseconds - %{FOO}i request.headers['FOO'] - %{FOO}o response.headers['FOO'] - %{FOO}e os.environ['FOO'] - - """ - - LOG_FORMAT_MAP = { - "a": "remote_address", - "t": "request_start_time", - "P": "process_id", - "r": "first_request_line", - "s": "response_status", - "b": "response_size", - "T": "request_time", - "Tf": "request_time_frac", - "D": "request_time_micro", - "i": "request_header", - "o": "response_header", - } - - LOG_FORMAT = '%a %t "%r" %s %b "%{Referer}i" "%{User-Agent}i"' - FORMAT_RE = re.compile(r"%(\{([A-Za-z0-9\-_]+)\}([ioe])|[atPrsbOD]|Tf?)") - CLEANUP_RE = re.compile(r"(%[^s])") - _FORMAT_CACHE = {} # type: Dict[str, Tuple[str, List[KeyMethod]]] - - def __init__(self, logger: logging.Logger, log_format: str = LOG_FORMAT) -> None: - """Initialise the logger. - - logger is a logger object to be used for logging. - log_format is a string with apache compatible log format description. - - """ - super().__init__(logger, log_format=log_format) - - _compiled_format = AccessLogger._FORMAT_CACHE.get(log_format) - if not _compiled_format: - _compiled_format = self.compile_format(log_format) - AccessLogger._FORMAT_CACHE[log_format] = _compiled_format - - self._log_format, self._methods = _compiled_format - - def compile_format(self, log_format: str) -> Tuple[str, List[KeyMethod]]: - """Translate log_format into form usable by modulo formatting - - All known atoms will be replaced with %s - Also methods for formatting of those atoms will be added to - _methods in appropriate order - - For example we have log_format = "%a %t" - This format will be translated to "%s %s" - Also contents of _methods will be - [self._format_a, self._format_t] - These method will be called and results will be passed - to translated string format. - - Each _format_* method receive 'args' which is list of arguments - given to self.log - - Exceptions are _format_e, _format_i and _format_o methods which - also receive key name (by functools.partial) - - """ - # list of (key, method) tuples, we don't use an OrderedDict as users - # can repeat the same key more than once - methods = list() - - for atom in self.FORMAT_RE.findall(log_format): - if atom[1] == "": - format_key1 = self.LOG_FORMAT_MAP[atom[0]] - m = getattr(AccessLogger, "_format_%s" % atom[0]) - key_method = KeyMethod(format_key1, m) - else: - format_key2 = (self.LOG_FORMAT_MAP[atom[2]], atom[1]) - m = getattr(AccessLogger, "_format_%s" % atom[2]) - key_method = KeyMethod(format_key2, functools.partial(m, atom[1])) - - methods.append(key_method) - - log_format = self.FORMAT_RE.sub(r"%s", log_format) - log_format = self.CLEANUP_RE.sub(r"%\1", log_format) - return log_format, methods - - @staticmethod - def _format_i( - key: str, request: BaseRequest, response: StreamResponse, time: float - ) -> str: - if request is None: - return "(no headers)" - - # suboptimal, make istr(key) once - return request.headers.get(key, "-") - - @staticmethod - def _format_o( - key: str, request: BaseRequest, response: StreamResponse, time: float - ) -> str: - # suboptimal, make istr(key) once - return response.headers.get(key, "-") - - @staticmethod - def _format_a(request: BaseRequest, response: StreamResponse, time: float) -> str: - if request is None: - return "-" - ip = request.remote - return ip if ip is not None else "-" - - @staticmethod - def _format_t(request: BaseRequest, response: StreamResponse, time: float) -> str: - now = datetime.datetime.utcnow() - start_time = now - datetime.timedelta(seconds=time) - return start_time.strftime("[%d/%b/%Y:%H:%M:%S +0000]") - - @staticmethod - def _format_P(request: BaseRequest, response: StreamResponse, time: float) -> str: - return "<%s>" % os.getpid() - - @staticmethod - def _format_r(request: BaseRequest, response: StreamResponse, time: float) -> str: - if request is None: - return "-" - return "{} {} HTTP/{}.{}".format( - request.method, - request.path_qs, - request.version.major, - request.version.minor, - ) - - @staticmethod - def _format_s(request: BaseRequest, response: StreamResponse, time: float) -> int: - return response.status - - @staticmethod - def _format_b(request: BaseRequest, response: StreamResponse, time: float) -> int: - return response.body_length - - @staticmethod - def _format_T(request: BaseRequest, response: StreamResponse, time: float) -> str: - return str(round(time)) - - @staticmethod - def _format_Tf(request: BaseRequest, response: StreamResponse, time: float) -> str: - return "%06f" % time - - @staticmethod - def _format_D(request: BaseRequest, response: StreamResponse, time: float) -> str: - return str(round(time * 1000000)) - - def _format_line( - self, request: BaseRequest, response: StreamResponse, time: float - ) -> Iterable[Tuple[str, Callable[[BaseRequest, StreamResponse, float], str]]]: - return [(key, method(request, response, time)) for key, method in self._methods] - - def log(self, request: BaseRequest, response: StreamResponse, time: float) -> None: - try: - fmt_info = self._format_line(request, response, time) - - values = list() - extra = dict() - for key, value in fmt_info: - values.append(value) - - if key.__class__ is str: - extra[key] = value - else: - k1, k2 = key # type: ignore[misc] - dct = extra.get(k1, {}) # type: ignore[var-annotated,has-type] - dct[k2] = value # type: ignore[index,has-type] - extra[k1] = dct # type: ignore[has-type,assignment] - - self.logger.info(self._log_format % tuple(values), extra=extra) - except Exception: - self.logger.exception("Error in logging") diff --git a/.venv/Lib/site-packages/aiohttp/web_middlewares.py b/.venv/Lib/site-packages/aiohttp/web_middlewares.py deleted file mode 100644 index fabcc44..0000000 --- a/.venv/Lib/site-packages/aiohttp/web_middlewares.py +++ /dev/null @@ -1,119 +0,0 @@ -import re -from typing import TYPE_CHECKING, Awaitable, Callable, Tuple, Type, TypeVar - -from .typedefs import Handler -from .web_exceptions import HTTPPermanentRedirect, _HTTPMove -from .web_request import Request -from .web_response import StreamResponse -from .web_urldispatcher import SystemRoute - -__all__ = ( - "middleware", - "normalize_path_middleware", -) - -if TYPE_CHECKING: # pragma: no cover - from .web_app import Application - -_Func = TypeVar("_Func") - - -async def _check_request_resolves(request: Request, path: str) -> Tuple[bool, Request]: - alt_request = request.clone(rel_url=path) - - match_info = await request.app.router.resolve(alt_request) - alt_request._match_info = match_info - - if match_info.http_exception is None: - return True, alt_request - - return False, request - - -def middleware(f: _Func) -> _Func: - f.__middleware_version__ = 1 # type: ignore[attr-defined] - return f - - -_Middleware = Callable[[Request, Handler], Awaitable[StreamResponse]] - - -def normalize_path_middleware( - *, - append_slash: bool = True, - remove_slash: bool = False, - merge_slashes: bool = True, - redirect_class: Type[_HTTPMove] = HTTPPermanentRedirect, -) -> _Middleware: - """Factory for producing a middleware that normalizes the path of a request. - - Normalizing means: - - Add or remove a trailing slash to the path. - - Double slashes are replaced by one. - - The middleware returns as soon as it finds a path that resolves - correctly. The order if both merge and append/remove are enabled is - 1) merge slashes - 2) append/remove slash - 3) both merge slashes and append/remove slash. - If the path resolves with at least one of those conditions, it will - redirect to the new path. - - Only one of `append_slash` and `remove_slash` can be enabled. If both - are `True` the factory will raise an assertion error - - If `append_slash` is `True` the middleware will append a slash when - needed. If a resource is defined with trailing slash and the request - comes without it, it will append it automatically. - - If `remove_slash` is `True`, `append_slash` must be `False`. When enabled - the middleware will remove trailing slashes and redirect if the resource - is defined - - If merge_slashes is True, merge multiple consecutive slashes in the - path into one. - """ - correct_configuration = not (append_slash and remove_slash) - assert correct_configuration, "Cannot both remove and append slash" - - @middleware - async def impl(request: Request, handler: Handler) -> StreamResponse: - if isinstance(request.match_info.route, SystemRoute): - paths_to_check = [] - if "?" in request.raw_path: - path, query = request.raw_path.split("?", 1) - query = "?" + query - else: - query = "" - path = request.raw_path - - if merge_slashes: - paths_to_check.append(re.sub("//+", "/", path)) - if append_slash and not request.path.endswith("/"): - paths_to_check.append(path + "/") - if remove_slash and request.path.endswith("/"): - paths_to_check.append(path[:-1]) - if merge_slashes and append_slash: - paths_to_check.append(re.sub("//+", "/", path + "/")) - if merge_slashes and remove_slash: - merged_slashes = re.sub("//+", "/", path) - paths_to_check.append(merged_slashes[:-1]) - - for path in paths_to_check: - path = re.sub("^//+", "/", path) # SECURITY: GHSA-v6wp-4m6f-gcjg - resolves, request = await _check_request_resolves(request, path) - if resolves: - raise redirect_class(request.raw_path + query) - - return await handler(request) - - return impl - - -def _fix_request_current_app(app: "Application") -> _Middleware: - @middleware - async def impl(request: Request, handler: Handler) -> StreamResponse: - with request.match_info.set_current_app(app): - return await handler(request) - - return impl diff --git a/.venv/Lib/site-packages/aiohttp/web_protocol.py b/.venv/Lib/site-packages/aiohttp/web_protocol.py deleted file mode 100644 index ad0c049..0000000 --- a/.venv/Lib/site-packages/aiohttp/web_protocol.py +++ /dev/null @@ -1,681 +0,0 @@ -import asyncio -import asyncio.streams -import traceback -import warnings -from collections import deque -from contextlib import suppress -from html import escape as html_escape -from http import HTTPStatus -from logging import Logger -from typing import ( - TYPE_CHECKING, - Any, - Awaitable, - Callable, - Deque, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) - -import attr -import yarl - -from .abc import AbstractAccessLogger, AbstractStreamWriter -from .base_protocol import BaseProtocol -from .helpers import ceil_timeout -from .http import ( - HttpProcessingError, - HttpRequestParser, - HttpVersion10, - RawRequestMessage, - StreamWriter, -) -from .log import access_logger, server_logger -from .streams import EMPTY_PAYLOAD, StreamReader -from .tcp_helpers import tcp_keepalive -from .web_exceptions import HTTPException -from .web_log import AccessLogger -from .web_request import BaseRequest -from .web_response import Response, StreamResponse - -__all__ = ("RequestHandler", "RequestPayloadError", "PayloadAccessError") - -if TYPE_CHECKING: # pragma: no cover - from .web_server import Server - - -_RequestFactory = Callable[ - [ - RawRequestMessage, - StreamReader, - "RequestHandler", - AbstractStreamWriter, - "asyncio.Task[None]", - ], - BaseRequest, -] - -_RequestHandler = Callable[[BaseRequest], Awaitable[StreamResponse]] - -ERROR = RawRequestMessage( - "UNKNOWN", - "/", - HttpVersion10, - {}, # type: ignore[arg-type] - {}, # type: ignore[arg-type] - True, - None, - False, - False, - yarl.URL("/"), -) - - -class RequestPayloadError(Exception): - """Payload parsing error.""" - - -class PayloadAccessError(Exception): - """Payload was accessed after response was sent.""" - - -@attr.s(auto_attribs=True, frozen=True, slots=True) -class _ErrInfo: - status: int - exc: BaseException - message: str - - -_MsgType = Tuple[Union[RawRequestMessage, _ErrInfo], StreamReader] - - -class RequestHandler(BaseProtocol): - """HTTP protocol implementation. - - RequestHandler handles incoming HTTP request. It reads request line, - request headers and request payload and calls handle_request() method. - By default it always returns with 404 response. - - RequestHandler handles errors in incoming request, like bad - status line, bad headers or incomplete payload. If any error occurs, - connection gets closed. - - keepalive_timeout -- number of seconds before closing - keep-alive connection - - tcp_keepalive -- TCP keep-alive is on, default is on - - debug -- enable debug mode - - logger -- custom logger object - - access_log_class -- custom class for access_logger - - access_log -- custom logging object - - access_log_format -- access log format string - - loop -- Optional event loop - - max_line_size -- Optional maximum header line size - - max_field_size -- Optional maximum header field size - - max_headers -- Optional maximum header size - - """ - - KEEPALIVE_RESCHEDULE_DELAY = 1 - - __slots__ = ( - "_request_count", - "_keepalive", - "_manager", - "_request_handler", - "_request_factory", - "_tcp_keepalive", - "_keepalive_time", - "_keepalive_handle", - "_keepalive_timeout", - "_lingering_time", - "_messages", - "_message_tail", - "_waiter", - "_task_handler", - "_upgrade", - "_payload_parser", - "_request_parser", - "_reading_paused", - "logger", - "debug", - "access_log", - "access_logger", - "_close", - "_force_close", - "_current_request", - ) - - def __init__( - self, - manager: "Server", - *, - loop: asyncio.AbstractEventLoop, - keepalive_timeout: float = 75.0, # NGINX default is 75 secs - tcp_keepalive: bool = True, - logger: Logger = server_logger, - access_log_class: Type[AbstractAccessLogger] = AccessLogger, - access_log: Logger = access_logger, - access_log_format: str = AccessLogger.LOG_FORMAT, - debug: bool = False, - max_line_size: int = 8190, - max_headers: int = 32768, - max_field_size: int = 8190, - lingering_time: float = 10.0, - read_bufsize: int = 2 ** 16, - auto_decompress: bool = True, - ): - super().__init__(loop) - - self._request_count = 0 - self._keepalive = False - self._current_request = None # type: Optional[BaseRequest] - self._manager = manager # type: Optional[Server] - self._request_handler: Optional[_RequestHandler] = manager.request_handler - self._request_factory: Optional[_RequestFactory] = manager.request_factory - - self._tcp_keepalive = tcp_keepalive - # placeholder to be replaced on keepalive timeout setup - self._keepalive_time = 0.0 - self._keepalive_handle = None # type: Optional[asyncio.Handle] - self._keepalive_timeout = keepalive_timeout - self._lingering_time = float(lingering_time) - - self._messages: Deque[_MsgType] = deque() - self._message_tail = b"" - - self._waiter = None # type: Optional[asyncio.Future[None]] - self._task_handler = None # type: Optional[asyncio.Task[None]] - - self._upgrade = False - self._payload_parser = None # type: Any - self._request_parser = HttpRequestParser( - self, - loop, - read_bufsize, - max_line_size=max_line_size, - max_field_size=max_field_size, - max_headers=max_headers, - payload_exception=RequestPayloadError, - auto_decompress=auto_decompress, - ) # type: Optional[HttpRequestParser] - - self.logger = logger - self.debug = debug - self.access_log = access_log - if access_log: - self.access_logger = access_log_class( - access_log, access_log_format - ) # type: Optional[AbstractAccessLogger] - else: - self.access_logger = None - - self._close = False - self._force_close = False - - def __repr__(self) -> str: - return "<{} {}>".format( - self.__class__.__name__, - "connected" if self.transport is not None else "disconnected", - ) - - @property - def keepalive_timeout(self) -> float: - return self._keepalive_timeout - - async def shutdown(self, timeout: Optional[float] = 15.0) -> None: - """Do worker process exit preparations. - - We need to clean up everything and stop accepting requests. - It is especially important for keep-alive connections. - """ - self._force_close = True - - if self._keepalive_handle is not None: - self._keepalive_handle.cancel() - - if self._waiter: - self._waiter.cancel() - - # wait for handlers - with suppress(asyncio.CancelledError, asyncio.TimeoutError): - async with ceil_timeout(timeout): - if self._current_request is not None: - self._current_request._cancel(asyncio.CancelledError()) - - if self._task_handler is not None and not self._task_handler.done(): - await self._task_handler - - # force-close non-idle handler - if self._task_handler is not None: - self._task_handler.cancel() - - if self.transport is not None: - self.transport.close() - self.transport = None - - def connection_made(self, transport: asyncio.BaseTransport) -> None: - super().connection_made(transport) - - real_transport = cast(asyncio.Transport, transport) - if self._tcp_keepalive: - tcp_keepalive(real_transport) - - self._task_handler = self._loop.create_task(self.start()) - assert self._manager is not None - self._manager.connection_made(self, real_transport) - - def connection_lost(self, exc: Optional[BaseException]) -> None: - if self._manager is None: - return - self._manager.connection_lost(self, exc) - - super().connection_lost(exc) - - self._manager = None - self._force_close = True - self._request_factory = None - self._request_handler = None - self._request_parser = None - - if self._keepalive_handle is not None: - self._keepalive_handle.cancel() - - if self._current_request is not None: - if exc is None: - exc = ConnectionResetError("Connection lost") - self._current_request._cancel(exc) - - if self._task_handler is not None: - self._task_handler.cancel() - if self._waiter is not None: - self._waiter.cancel() - - self._task_handler = None - - if self._payload_parser is not None: - self._payload_parser.feed_eof() - self._payload_parser = None - - def set_parser(self, parser: Any) -> None: - # Actual type is WebReader - assert self._payload_parser is None - - self._payload_parser = parser - - if self._message_tail: - self._payload_parser.feed_data(self._message_tail) - self._message_tail = b"" - - def eof_received(self) -> None: - pass - - def data_received(self, data: bytes) -> None: - if self._force_close or self._close: - return - # parse http messages - messages: Sequence[_MsgType] - if self._payload_parser is None and not self._upgrade: - assert self._request_parser is not None - try: - messages, upgraded, tail = self._request_parser.feed_data(data) - except HttpProcessingError as exc: - messages = [ - (_ErrInfo(status=400, exc=exc, message=exc.message), EMPTY_PAYLOAD) - ] - upgraded = False - tail = b"" - - for msg, payload in messages or (): - self._request_count += 1 - self._messages.append((msg, payload)) - - waiter = self._waiter - if messages and waiter is not None and not waiter.done(): - # don't set result twice - waiter.set_result(None) - - self._upgrade = upgraded - if upgraded and tail: - self._message_tail = tail - - # no parser, just store - elif self._payload_parser is None and self._upgrade and data: - self._message_tail += data - - # feed payload - elif data: - eof, tail = self._payload_parser.feed_data(data) - if eof: - self.close() - - def keep_alive(self, val: bool) -> None: - """Set keep-alive connection mode. - - :param bool val: new state. - """ - self._keepalive = val - if self._keepalive_handle: - self._keepalive_handle.cancel() - self._keepalive_handle = None - - def close(self) -> None: - """Close connection. - - Stop accepting new pipelining messages and close - connection when handlers done processing messages. - """ - self._close = True - if self._waiter: - self._waiter.cancel() - - def force_close(self) -> None: - """Forcefully close connection.""" - self._force_close = True - if self._waiter: - self._waiter.cancel() - if self.transport is not None: - self.transport.close() - self.transport = None - - def log_access( - self, request: BaseRequest, response: StreamResponse, time: float - ) -> None: - if self.access_logger is not None: - self.access_logger.log(request, response, self._loop.time() - time) - - def log_debug(self, *args: Any, **kw: Any) -> None: - if self.debug: - self.logger.debug(*args, **kw) - - def log_exception(self, *args: Any, **kw: Any) -> None: - self.logger.exception(*args, **kw) - - def _process_keepalive(self) -> None: - if self._force_close or not self._keepalive: - return - - next = self._keepalive_time + self._keepalive_timeout - - # handler in idle state - if self._waiter: - if self._loop.time() > next: - self.force_close() - return - - # not all request handlers are done, - # reschedule itself to next second - self._keepalive_handle = self._loop.call_later( - self.KEEPALIVE_RESCHEDULE_DELAY, self._process_keepalive - ) - - async def _handle_request( - self, - request: BaseRequest, - start_time: float, - request_handler: Callable[[BaseRequest], Awaitable[StreamResponse]], - ) -> Tuple[StreamResponse, bool]: - assert self._request_handler is not None - try: - try: - self._current_request = request - resp = await request_handler(request) - finally: - self._current_request = None - except HTTPException as exc: - resp = exc - reset = await self.finish_response(request, resp, start_time) - except asyncio.CancelledError: - raise - except asyncio.TimeoutError as exc: - self.log_debug("Request handler timed out.", exc_info=exc) - resp = self.handle_error(request, 504) - reset = await self.finish_response(request, resp, start_time) - except Exception as exc: - resp = self.handle_error(request, 500, exc) - reset = await self.finish_response(request, resp, start_time) - else: - # Deprecation warning (See #2415) - if getattr(resp, "__http_exception__", False): - warnings.warn( - "returning HTTPException object is deprecated " - "(#2415) and will be removed, " - "please raise the exception instead", - DeprecationWarning, - ) - - reset = await self.finish_response(request, resp, start_time) - - return resp, reset - - async def start(self) -> None: - """Process incoming request. - - It reads request line, request headers and request payload, then - calls handle_request() method. Subclass has to override - handle_request(). start() handles various exceptions in request - or response handling. Connection is being closed always unless - keep_alive(True) specified. - """ - loop = self._loop - handler = self._task_handler - assert handler is not None - manager = self._manager - assert manager is not None - keepalive_timeout = self._keepalive_timeout - resp = None - assert self._request_factory is not None - assert self._request_handler is not None - - while not self._force_close: - if not self._messages: - try: - # wait for next request - self._waiter = loop.create_future() - await self._waiter - except asyncio.CancelledError: - break - finally: - self._waiter = None - - message, payload = self._messages.popleft() - - start = loop.time() - - manager.requests_count += 1 - writer = StreamWriter(self, loop) - if isinstance(message, _ErrInfo): - # make request_factory work - request_handler = self._make_error_handler(message) - message = ERROR - else: - request_handler = self._request_handler - - request = self._request_factory(message, payload, self, writer, handler) - try: - # a new task is used for copy context vars (#3406) - task = self._loop.create_task( - self._handle_request(request, start, request_handler) - ) - try: - resp, reset = await task - except (asyncio.CancelledError, ConnectionError): - self.log_debug("Ignored premature client disconnection") - break - - # Drop the processed task from asyncio.Task.all_tasks() early - del task - if reset: - self.log_debug("Ignored premature client disconnection 2") - break - - # notify server about keep-alive - self._keepalive = bool(resp.keep_alive) - - # check payload - if not payload.is_eof(): - lingering_time = self._lingering_time - if not self._force_close and lingering_time: - self.log_debug( - "Start lingering close timer for %s sec.", lingering_time - ) - - now = loop.time() - end_t = now + lingering_time - - with suppress(asyncio.TimeoutError, asyncio.CancelledError): - while not payload.is_eof() and now < end_t: - async with ceil_timeout(end_t - now): - # read and ignore - await payload.readany() - now = loop.time() - - # if payload still uncompleted - if not payload.is_eof() and not self._force_close: - self.log_debug("Uncompleted request.") - self.close() - - payload.set_exception(PayloadAccessError()) - - except asyncio.CancelledError: - self.log_debug("Ignored premature client disconnection ") - break - except RuntimeError as exc: - if self.debug: - self.log_exception("Unhandled runtime exception", exc_info=exc) - self.force_close() - except Exception as exc: - self.log_exception("Unhandled exception", exc_info=exc) - self.force_close() - finally: - if self.transport is None and resp is not None: - self.log_debug("Ignored premature client disconnection.") - elif not self._force_close: - if self._keepalive and not self._close: - # start keep-alive timer - if keepalive_timeout is not None: - now = self._loop.time() - self._keepalive_time = now - if self._keepalive_handle is None: - self._keepalive_handle = loop.call_at( - now + keepalive_timeout, self._process_keepalive - ) - else: - break - - # remove handler, close transport if no handlers left - if not self._force_close: - self._task_handler = None - if self.transport is not None: - self.transport.close() - - async def finish_response( - self, request: BaseRequest, resp: StreamResponse, start_time: float - ) -> bool: - """Prepare the response and write_eof, then log access. - - This has to - be called within the context of any exception so the access logger - can get exception information. Returns True if the client disconnects - prematurely. - """ - if self._request_parser is not None: - self._request_parser.set_upgraded(False) - self._upgrade = False - if self._message_tail: - self._request_parser.feed_data(self._message_tail) - self._message_tail = b"" - try: - prepare_meth = resp.prepare - except AttributeError: - if resp is None: - raise RuntimeError("Missing return " "statement on request handler") - else: - raise RuntimeError( - "Web-handler should return " - "a response instance, " - "got {!r}".format(resp) - ) - try: - await prepare_meth(request) - await resp.write_eof() - except ConnectionError: - self.log_access(request, resp, start_time) - return True - else: - self.log_access(request, resp, start_time) - return False - - def handle_error( - self, - request: BaseRequest, - status: int = 500, - exc: Optional[BaseException] = None, - message: Optional[str] = None, - ) -> StreamResponse: - """Handle errors. - - Returns HTTP response with specific status code. Logs additional - information. It always closes current connection. - """ - self.log_exception("Error handling request", exc_info=exc) - - # some data already got sent, connection is broken - if request.writer.output_size > 0: - raise ConnectionError( - "Response is sent already, cannot send another response " - "with the error message" - ) - - ct = "text/plain" - if status == HTTPStatus.INTERNAL_SERVER_ERROR: - title = "{0.value} {0.phrase}".format(HTTPStatus.INTERNAL_SERVER_ERROR) - msg = HTTPStatus.INTERNAL_SERVER_ERROR.description - tb = None - if self.debug: - with suppress(Exception): - tb = traceback.format_exc() - - if "text/html" in request.headers.get("Accept", ""): - if tb: - tb = html_escape(tb) - msg = f"

Traceback:

\n
{tb}
" - message = ( - "" - "{title}" - "\n

{title}

" - "\n{msg}\n\n" - ).format(title=title, msg=msg) - ct = "text/html" - else: - if tb: - msg = tb - message = title + "\n\n" + msg - - resp = Response(status=status, text=message, content_type=ct) - resp.force_close() - - return resp - - def _make_error_handler( - self, err_info: _ErrInfo - ) -> Callable[[BaseRequest], Awaitable[StreamResponse]]: - async def handler(request: BaseRequest) -> StreamResponse: - return self.handle_error( - request, err_info.status, err_info.exc, err_info.message - ) - - return handler diff --git a/.venv/Lib/site-packages/aiohttp/web_request.py b/.venv/Lib/site-packages/aiohttp/web_request.py deleted file mode 100644 index b3574ca..0000000 --- a/.venv/Lib/site-packages/aiohttp/web_request.py +++ /dev/null @@ -1,874 +0,0 @@ -import asyncio -import datetime -import io -import re -import socket -import string -import tempfile -import types -import warnings -from http.cookies import SimpleCookie -from types import MappingProxyType -from typing import ( - TYPE_CHECKING, - Any, - Dict, - Iterator, - Mapping, - MutableMapping, - Optional, - Pattern, - Tuple, - Union, - cast, -) -from urllib.parse import parse_qsl - -import attr -from multidict import CIMultiDict, CIMultiDictProxy, MultiDict, MultiDictProxy -from yarl import URL - -from . import hdrs -from .abc import AbstractStreamWriter -from .helpers import ( - DEBUG, - ETAG_ANY, - LIST_QUOTED_ETAG_RE, - ChainMapProxy, - ETag, - HeadersMixin, - parse_http_date, - reify, - sentinel, -) -from .http_parser import RawRequestMessage -from .http_writer import HttpVersion -from .multipart import BodyPartReader, MultipartReader -from .streams import EmptyStreamReader, StreamReader -from .typedefs import ( - DEFAULT_JSON_DECODER, - Final, - JSONDecoder, - LooseHeaders, - RawHeaders, - StrOrURL, -) -from .web_exceptions import HTTPRequestEntityTooLarge -from .web_response import StreamResponse - -__all__ = ("BaseRequest", "FileField", "Request") - - -if TYPE_CHECKING: # pragma: no cover - from .web_app import Application - from .web_protocol import RequestHandler - from .web_urldispatcher import UrlMappingMatchInfo - - -@attr.s(auto_attribs=True, frozen=True, slots=True) -class FileField: - name: str - filename: str - file: io.BufferedReader - content_type: str - headers: "CIMultiDictProxy[str]" - - -_TCHAR: Final[str] = string.digits + string.ascii_letters + r"!#$%&'*+.^_`|~-" -# '-' at the end to prevent interpretation as range in a char class - -_TOKEN: Final[str] = fr"[{_TCHAR}]+" - -_QDTEXT: Final[str] = r"[{}]".format( - r"".join(chr(c) for c in (0x09, 0x20, 0x21) + tuple(range(0x23, 0x7F))) -) -# qdtext includes 0x5C to escape 0x5D ('\]') -# qdtext excludes obs-text (because obsoleted, and encoding not specified) - -_QUOTED_PAIR: Final[str] = r"\\[\t !-~]" - -_QUOTED_STRING: Final[str] = r'"(?:{quoted_pair}|{qdtext})*"'.format( - qdtext=_QDTEXT, quoted_pair=_QUOTED_PAIR -) - -_FORWARDED_PAIR: Final[ - str -] = r"({token})=({token}|{quoted_string})(:\d{{1,4}})?".format( - token=_TOKEN, quoted_string=_QUOTED_STRING -) - -_QUOTED_PAIR_REPLACE_RE: Final[Pattern[str]] = re.compile(r"\\([\t !-~])") -# same pattern as _QUOTED_PAIR but contains a capture group - -_FORWARDED_PAIR_RE: Final[Pattern[str]] = re.compile(_FORWARDED_PAIR) - -############################################################ -# HTTP Request -############################################################ - - -class BaseRequest(MutableMapping[str, Any], HeadersMixin): - - POST_METHODS = { - hdrs.METH_PATCH, - hdrs.METH_POST, - hdrs.METH_PUT, - hdrs.METH_TRACE, - hdrs.METH_DELETE, - } - - ATTRS = HeadersMixin.ATTRS | frozenset( - [ - "_message", - "_protocol", - "_payload_writer", - "_payload", - "_headers", - "_method", - "_version", - "_rel_url", - "_post", - "_read_bytes", - "_state", - "_cache", - "_task", - "_client_max_size", - "_loop", - "_transport_sslcontext", - "_transport_peername", - ] - ) - - def __init__( - self, - message: RawRequestMessage, - payload: StreamReader, - protocol: "RequestHandler", - payload_writer: AbstractStreamWriter, - task: "asyncio.Task[None]", - loop: asyncio.AbstractEventLoop, - *, - client_max_size: int = 1024 ** 2, - state: Optional[Dict[str, Any]] = None, - scheme: Optional[str] = None, - host: Optional[str] = None, - remote: Optional[str] = None, - ) -> None: - if state is None: - state = {} - self._message = message - self._protocol = protocol - self._payload_writer = payload_writer - - self._payload = payload - self._headers = message.headers - self._method = message.method - self._version = message.version - self._rel_url = message.url - self._post = ( - None - ) # type: Optional[MultiDictProxy[Union[str, bytes, FileField]]] - self._read_bytes = None # type: Optional[bytes] - - self._state = state - self._cache = {} # type: Dict[str, Any] - self._task = task - self._client_max_size = client_max_size - self._loop = loop - - transport = self._protocol.transport - assert transport is not None - self._transport_sslcontext = transport.get_extra_info("sslcontext") - self._transport_peername = transport.get_extra_info("peername") - - if scheme is not None: - self._cache["scheme"] = scheme - if host is not None: - self._cache["host"] = host - if remote is not None: - self._cache["remote"] = remote - - def clone( - self, - *, - method: str = sentinel, - rel_url: StrOrURL = sentinel, - headers: LooseHeaders = sentinel, - scheme: str = sentinel, - host: str = sentinel, - remote: str = sentinel, - ) -> "BaseRequest": - """Clone itself with replacement some attributes. - - Creates and returns a new instance of Request object. If no parameters - are given, an exact copy is returned. If a parameter is not passed, it - will reuse the one from the current request object. - """ - if self._read_bytes: - raise RuntimeError("Cannot clone request " "after reading its content") - - dct = {} # type: Dict[str, Any] - if method is not sentinel: - dct["method"] = method - if rel_url is not sentinel: - new_url = URL(rel_url) - dct["url"] = new_url - dct["path"] = str(new_url) - if headers is not sentinel: - # a copy semantic - dct["headers"] = CIMultiDictProxy(CIMultiDict(headers)) - dct["raw_headers"] = tuple( - (k.encode("utf-8"), v.encode("utf-8")) for k, v in headers.items() - ) - - message = self._message._replace(**dct) - - kwargs = {} - if scheme is not sentinel: - kwargs["scheme"] = scheme - if host is not sentinel: - kwargs["host"] = host - if remote is not sentinel: - kwargs["remote"] = remote - - return self.__class__( - message, - self._payload, - self._protocol, - self._payload_writer, - self._task, - self._loop, - client_max_size=self._client_max_size, - state=self._state.copy(), - **kwargs, - ) - - @property - def task(self) -> "asyncio.Task[None]": - return self._task - - @property - def protocol(self) -> "RequestHandler": - return self._protocol - - @property - def transport(self) -> Optional[asyncio.Transport]: - if self._protocol is None: - return None - return self._protocol.transport - - @property - def writer(self) -> AbstractStreamWriter: - return self._payload_writer - - @reify - def message(self) -> RawRequestMessage: - warnings.warn("Request.message is deprecated", DeprecationWarning, stacklevel=3) - return self._message - - @reify - def rel_url(self) -> URL: - return self._rel_url - - @reify - def loop(self) -> asyncio.AbstractEventLoop: - warnings.warn( - "request.loop property is deprecated", DeprecationWarning, stacklevel=2 - ) - return self._loop - - # MutableMapping API - - def __getitem__(self, key: str) -> Any: - return self._state[key] - - def __setitem__(self, key: str, value: Any) -> None: - self._state[key] = value - - def __delitem__(self, key: str) -> None: - del self._state[key] - - def __len__(self) -> int: - return len(self._state) - - def __iter__(self) -> Iterator[str]: - return iter(self._state) - - ######## - - @reify - def secure(self) -> bool: - """A bool indicating if the request is handled with SSL.""" - return self.scheme == "https" - - @reify - def forwarded(self) -> Tuple[Mapping[str, str], ...]: - """A tuple containing all parsed Forwarded header(s). - - Makes an effort to parse Forwarded headers as specified by RFC 7239: - - - It adds one (immutable) dictionary per Forwarded 'field-value', ie - per proxy. The element corresponds to the data in the Forwarded - field-value added by the first proxy encountered by the client. Each - subsequent item corresponds to those added by later proxies. - - It checks that every value has valid syntax in general as specified - in section 4: either a 'token' or a 'quoted-string'. - - It un-escapes found escape sequences. - - It does NOT validate 'by' and 'for' contents as specified in section - 6. - - It does NOT validate 'host' contents (Host ABNF). - - It does NOT validate 'proto' contents for valid URI scheme names. - - Returns a tuple containing one or more immutable dicts - """ - elems = [] - for field_value in self._message.headers.getall(hdrs.FORWARDED, ()): - length = len(field_value) - pos = 0 - need_separator = False - elem = {} # type: Dict[str, str] - elems.append(types.MappingProxyType(elem)) - while 0 <= pos < length: - match = _FORWARDED_PAIR_RE.match(field_value, pos) - if match is not None: # got a valid forwarded-pair - if need_separator: - # bad syntax here, skip to next comma - pos = field_value.find(",", pos) - else: - name, value, port = match.groups() - if value[0] == '"': - # quoted string: remove quotes and unescape - value = _QUOTED_PAIR_REPLACE_RE.sub(r"\1", value[1:-1]) - if port: - value += port - elem[name.lower()] = value - pos += len(match.group(0)) - need_separator = True - elif field_value[pos] == ",": # next forwarded-element - need_separator = False - elem = {} - elems.append(types.MappingProxyType(elem)) - pos += 1 - elif field_value[pos] == ";": # next forwarded-pair - need_separator = False - pos += 1 - elif field_value[pos] in " \t": - # Allow whitespace even between forwarded-pairs, though - # RFC 7239 doesn't. This simplifies code and is in line - # with Postel's law. - pos += 1 - else: - # bad syntax here, skip to next comma - pos = field_value.find(",", pos) - return tuple(elems) - - @reify - def scheme(self) -> str: - """A string representing the scheme of the request. - - Hostname is resolved in this order: - - - overridden value by .clone(scheme=new_scheme) call. - - type of connection to peer: HTTPS if socket is SSL, HTTP otherwise. - - 'http' or 'https'. - """ - if self._transport_sslcontext: - return "https" - else: - return "http" - - @reify - def method(self) -> str: - """Read only property for getting HTTP method. - - The value is upper-cased str like 'GET', 'POST', 'PUT' etc. - """ - return self._method - - @reify - def version(self) -> HttpVersion: - """Read only property for getting HTTP version of request. - - Returns aiohttp.protocol.HttpVersion instance. - """ - return self._version - - @reify - def host(self) -> str: - """Hostname of the request. - - Hostname is resolved in this order: - - - overridden value by .clone(host=new_host) call. - - HOST HTTP header - - socket.getfqdn() value - """ - host = self._message.headers.get(hdrs.HOST) - if host is not None: - return host - return socket.getfqdn() - - @reify - def remote(self) -> Optional[str]: - """Remote IP of client initiated HTTP request. - - The IP is resolved in this order: - - - overridden value by .clone(remote=new_remote) call. - - peername of opened socket - """ - if self._transport_peername is None: - return None - if isinstance(self._transport_peername, (list, tuple)): - return str(self._transport_peername[0]) - return str(self._transport_peername) - - @reify - def url(self) -> URL: - url = URL.build(scheme=self.scheme, host=self.host) - return url.join(self._rel_url) - - @reify - def path(self) -> str: - """The URL including *PATH INFO* without the host or scheme. - - E.g., ``/app/blog`` - """ - return self._rel_url.path - - @reify - def path_qs(self) -> str: - """The URL including PATH_INFO and the query string. - - E.g, /app/blog?id=10 - """ - return str(self._rel_url) - - @reify - def raw_path(self) -> str: - """The URL including raw *PATH INFO* without the host or scheme. - - Warning, the path is unquoted and may contains non valid URL characters - - E.g., ``/my%2Fpath%7Cwith%21some%25strange%24characters`` - """ - return self._message.path - - @reify - def query(self) -> "MultiDictProxy[str]": - """A multidict with all the variables in the query string.""" - return MultiDictProxy(self._rel_url.query) - - @reify - def query_string(self) -> str: - """The query string in the URL. - - E.g., id=10 - """ - return self._rel_url.query_string - - @reify - def headers(self) -> "CIMultiDictProxy[str]": - """A case-insensitive multidict proxy with all headers.""" - return self._headers - - @reify - def raw_headers(self) -> RawHeaders: - """A sequence of pairs for all headers.""" - return self._message.raw_headers - - @reify - def if_modified_since(self) -> Optional[datetime.datetime]: - """The value of If-Modified-Since HTTP header, or None. - - This header is represented as a `datetime` object. - """ - return parse_http_date(self.headers.get(hdrs.IF_MODIFIED_SINCE)) - - @reify - def if_unmodified_since(self) -> Optional[datetime.datetime]: - """The value of If-Unmodified-Since HTTP header, or None. - - This header is represented as a `datetime` object. - """ - return parse_http_date(self.headers.get(hdrs.IF_UNMODIFIED_SINCE)) - - @staticmethod - def _etag_values(etag_header: str) -> Iterator[ETag]: - """Extract `ETag` objects from raw header.""" - if etag_header == ETAG_ANY: - yield ETag( - is_weak=False, - value=ETAG_ANY, - ) - else: - for match in LIST_QUOTED_ETAG_RE.finditer(etag_header): - is_weak, value, garbage = match.group(2, 3, 4) - # Any symbol captured by 4th group means - # that the following sequence is invalid. - if garbage: - break - - yield ETag( - is_weak=bool(is_weak), - value=value, - ) - - @classmethod - def _if_match_or_none_impl( - cls, header_value: Optional[str] - ) -> Optional[Tuple[ETag, ...]]: - if not header_value: - return None - - return tuple(cls._etag_values(header_value)) - - @reify - def if_match(self) -> Optional[Tuple[ETag, ...]]: - """The value of If-Match HTTP header, or None. - - This header is represented as a `tuple` of `ETag` objects. - """ - return self._if_match_or_none_impl(self.headers.get(hdrs.IF_MATCH)) - - @reify - def if_none_match(self) -> Optional[Tuple[ETag, ...]]: - """The value of If-None-Match HTTP header, or None. - - This header is represented as a `tuple` of `ETag` objects. - """ - return self._if_match_or_none_impl(self.headers.get(hdrs.IF_NONE_MATCH)) - - @reify - def if_range(self) -> Optional[datetime.datetime]: - """The value of If-Range HTTP header, or None. - - This header is represented as a `datetime` object. - """ - return parse_http_date(self.headers.get(hdrs.IF_RANGE)) - - @reify - def keep_alive(self) -> bool: - """Is keepalive enabled by client?""" - return not self._message.should_close - - @reify - def cookies(self) -> Mapping[str, str]: - """Return request cookies. - - A read-only dictionary-like object. - """ - raw = self.headers.get(hdrs.COOKIE, "") - parsed = SimpleCookie(raw) # type: SimpleCookie[str] - return MappingProxyType({key: val.value for key, val in parsed.items()}) - - @reify - def http_range(self) -> slice: - """The content of Range HTTP header. - - Return a slice instance. - - """ - rng = self._headers.get(hdrs.RANGE) - start, end = None, None - if rng is not None: - try: - pattern = r"^bytes=(\d*)-(\d*)$" - start, end = re.findall(pattern, rng)[0] - except IndexError: # pattern was not found in header - raise ValueError("range not in acceptable format") - - end = int(end) if end else None - start = int(start) if start else None - - if start is None and end is not None: - # end with no start is to return tail of content - start = -end - end = None - - if start is not None and end is not None: - # end is inclusive in range header, exclusive for slice - end += 1 - - if start >= end: - raise ValueError("start cannot be after end") - - if start is end is None: # No valid range supplied - raise ValueError("No start or end of range specified") - - return slice(start, end, 1) - - @reify - def content(self) -> StreamReader: - """Return raw payload stream.""" - return self._payload - - @property - def has_body(self) -> bool: - """Return True if request's HTTP BODY can be read, False otherwise.""" - warnings.warn( - "Deprecated, use .can_read_body #2005", DeprecationWarning, stacklevel=2 - ) - return not self._payload.at_eof() - - @property - def can_read_body(self) -> bool: - """Return True if request's HTTP BODY can be read, False otherwise.""" - return not self._payload.at_eof() - - @reify - def body_exists(self) -> bool: - """Return True if request has HTTP BODY, False otherwise.""" - return type(self._payload) is not EmptyStreamReader - - async def release(self) -> None: - """Release request. - - Eat unread part of HTTP BODY if present. - """ - while not self._payload.at_eof(): - await self._payload.readany() - - async def read(self) -> bytes: - """Read request body if present. - - Returns bytes object with full request content. - """ - if self._read_bytes is None: - body = bytearray() - while True: - chunk = await self._payload.readany() - body.extend(chunk) - if self._client_max_size: - body_size = len(body) - if body_size >= self._client_max_size: - raise HTTPRequestEntityTooLarge( - max_size=self._client_max_size, actual_size=body_size - ) - if not chunk: - break - self._read_bytes = bytes(body) - return self._read_bytes - - async def text(self) -> str: - """Return BODY as text using encoding from .charset.""" - bytes_body = await self.read() - encoding = self.charset or "utf-8" - return bytes_body.decode(encoding) - - async def json(self, *, loads: JSONDecoder = DEFAULT_JSON_DECODER) -> Any: - """Return BODY as JSON.""" - body = await self.text() - return loads(body) - - async def multipart(self) -> MultipartReader: - """Return async iterator to process BODY as multipart.""" - return MultipartReader(self._headers, self._payload) - - async def post(self) -> "MultiDictProxy[Union[str, bytes, FileField]]": - """Return POST parameters.""" - if self._post is not None: - return self._post - if self._method not in self.POST_METHODS: - self._post = MultiDictProxy(MultiDict()) - return self._post - - content_type = self.content_type - if content_type not in ( - "", - "application/x-www-form-urlencoded", - "multipart/form-data", - ): - self._post = MultiDictProxy(MultiDict()) - return self._post - - out = MultiDict() # type: MultiDict[Union[str, bytes, FileField]] - - if content_type == "multipart/form-data": - multipart = await self.multipart() - max_size = self._client_max_size - - field = await multipart.next() - while field is not None: - size = 0 - field_ct = field.headers.get(hdrs.CONTENT_TYPE) - - if isinstance(field, BodyPartReader): - assert field.name is not None - - # Note that according to RFC 7578, the Content-Type header - # is optional, even for files, so we can't assume it's - # present. - # https://tools.ietf.org/html/rfc7578#section-4.4 - if field.filename: - # store file in temp file - tmp = tempfile.TemporaryFile() - chunk = await field.read_chunk(size=2 ** 16) - while chunk: - chunk = field.decode(chunk) - tmp.write(chunk) - size += len(chunk) - if 0 < max_size < size: - tmp.close() - raise HTTPRequestEntityTooLarge( - max_size=max_size, actual_size=size - ) - chunk = await field.read_chunk(size=2 ** 16) - tmp.seek(0) - - if field_ct is None: - field_ct = "application/octet-stream" - - ff = FileField( - field.name, - field.filename, - cast(io.BufferedReader, tmp), - field_ct, - field.headers, - ) - out.add(field.name, ff) - else: - # deal with ordinary data - value = await field.read(decode=True) - if field_ct is None or field_ct.startswith("text/"): - charset = field.get_charset(default="utf-8") - out.add(field.name, value.decode(charset)) - else: - out.add(field.name, value) - size += len(value) - if 0 < max_size < size: - raise HTTPRequestEntityTooLarge( - max_size=max_size, actual_size=size - ) - else: - raise ValueError( - "To decode nested multipart you need " "to use custom reader", - ) - - field = await multipart.next() - else: - data = await self.read() - if data: - charset = self.charset or "utf-8" - out.extend( - parse_qsl( - data.rstrip().decode(charset), - keep_blank_values=True, - encoding=charset, - ) - ) - - self._post = MultiDictProxy(out) - return self._post - - def get_extra_info(self, name: str, default: Any = None) -> Any: - """Extra info from protocol transport""" - protocol = self._protocol - if protocol is None: - return default - - transport = protocol.transport - if transport is None: - return default - - return transport.get_extra_info(name, default) - - def __repr__(self) -> str: - ascii_encodable_path = self.path.encode("ascii", "backslashreplace").decode( - "ascii" - ) - return "<{} {} {} >".format( - self.__class__.__name__, self._method, ascii_encodable_path - ) - - def __eq__(self, other: object) -> bool: - return id(self) == id(other) - - def __bool__(self) -> bool: - return True - - async def _prepare_hook(self, response: StreamResponse) -> None: - return - - def _cancel(self, exc: BaseException) -> None: - self._payload.set_exception(exc) - - -class Request(BaseRequest): - - ATTRS = BaseRequest.ATTRS | frozenset(["_match_info"]) - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - # matchdict, route_name, handler - # or information about traversal lookup - - # initialized after route resolving - self._match_info = None # type: Optional[UrlMappingMatchInfo] - - if DEBUG: - - def __setattr__(self, name: str, val: Any) -> None: - if name not in self.ATTRS: - warnings.warn( - "Setting custom {}.{} attribute " - "is discouraged".format(self.__class__.__name__, name), - DeprecationWarning, - stacklevel=2, - ) - super().__setattr__(name, val) - - def clone( - self, - *, - method: str = sentinel, - rel_url: StrOrURL = sentinel, - headers: LooseHeaders = sentinel, - scheme: str = sentinel, - host: str = sentinel, - remote: str = sentinel, - ) -> "Request": - ret = super().clone( - method=method, - rel_url=rel_url, - headers=headers, - scheme=scheme, - host=host, - remote=remote, - ) - new_ret = cast(Request, ret) - new_ret._match_info = self._match_info - return new_ret - - @reify - def match_info(self) -> "UrlMappingMatchInfo": - """Result of route resolving.""" - match_info = self._match_info - assert match_info is not None - return match_info - - @property - def app(self) -> "Application": - """Application instance.""" - match_info = self._match_info - assert match_info is not None - return match_info.current_app - - @property - def config_dict(self) -> ChainMapProxy: - match_info = self._match_info - assert match_info is not None - lst = match_info.apps - app = self.app - idx = lst.index(app) - sublist = list(reversed(lst[: idx + 1])) - return ChainMapProxy(sublist) - - async def _prepare_hook(self, response: StreamResponse) -> None: - match_info = self._match_info - if match_info is None: - return - for app in match_info._apps: - await app.on_response_prepare.send(self, response) diff --git a/.venv/Lib/site-packages/aiohttp/web_response.py b/.venv/Lib/site-packages/aiohttp/web_response.py deleted file mode 100644 index 7880ab2..0000000 --- a/.venv/Lib/site-packages/aiohttp/web_response.py +++ /dev/null @@ -1,825 +0,0 @@ -import asyncio -import collections.abc -import datetime -import enum -import json -import math -import time -import warnings -import zlib -from concurrent.futures import Executor -from http.cookies import Morsel, SimpleCookie -from typing import ( - TYPE_CHECKING, - Any, - Dict, - Iterator, - Mapping, - MutableMapping, - Optional, - Tuple, - Union, - cast, -) - -from multidict import CIMultiDict, istr - -from . import hdrs, payload -from .abc import AbstractStreamWriter -from .helpers import ( - ETAG_ANY, - PY_38, - QUOTED_ETAG_RE, - ETag, - HeadersMixin, - parse_http_date, - rfc822_formatted_time, - sentinel, - validate_etag_value, -) -from .http import RESPONSES, SERVER_SOFTWARE, HttpVersion10, HttpVersion11 -from .payload import Payload -from .typedefs import JSONEncoder, LooseHeaders - -__all__ = ("ContentCoding", "StreamResponse", "Response", "json_response") - - -if TYPE_CHECKING: # pragma: no cover - from .web_request import BaseRequest - - BaseClass = MutableMapping[str, Any] -else: - BaseClass = collections.abc.MutableMapping - - -if not PY_38: - # allow samesite to be used in python < 3.8 - # already permitted in python 3.8, see https://bugs.python.org/issue29613 - Morsel._reserved["samesite"] = "SameSite" # type: ignore[attr-defined] - - -class ContentCoding(enum.Enum): - # The content codings that we have support for. - # - # Additional registered codings are listed at: - # https://www.iana.org/assignments/http-parameters/http-parameters.xhtml#content-coding - deflate = "deflate" - gzip = "gzip" - identity = "identity" - - -############################################################ -# HTTP Response classes -############################################################ - - -class StreamResponse(BaseClass, HeadersMixin): - - _length_check = True - - def __init__( - self, - *, - status: int = 200, - reason: Optional[str] = None, - headers: Optional[LooseHeaders] = None, - ) -> None: - self._body = None - self._keep_alive = None # type: Optional[bool] - self._chunked = False - self._compression = False - self._compression_force = None # type: Optional[ContentCoding] - self._cookies = SimpleCookie() # type: SimpleCookie[str] - - self._req = None # type: Optional[BaseRequest] - self._payload_writer = None # type: Optional[AbstractStreamWriter] - self._eof_sent = False - self._body_length = 0 - self._state = {} # type: Dict[str, Any] - - if headers is not None: - self._headers = CIMultiDict(headers) # type: CIMultiDict[str] - else: - self._headers = CIMultiDict() - - self.set_status(status, reason) - - @property - def prepared(self) -> bool: - return self._payload_writer is not None - - @property - def task(self) -> "Optional[asyncio.Task[None]]": - if self._req: - return self._req.task - else: - return None - - @property - def status(self) -> int: - return self._status - - @property - def chunked(self) -> bool: - return self._chunked - - @property - def compression(self) -> bool: - return self._compression - - @property - def reason(self) -> str: - return self._reason - - def set_status( - self, - status: int, - reason: Optional[str] = None, - _RESPONSES: Mapping[int, Tuple[str, str]] = RESPONSES, - ) -> None: - assert not self.prepared, ( - "Cannot change the response status code after " "the headers have been sent" - ) - self._status = int(status) - if reason is None: - try: - reason = _RESPONSES[self._status][0] - except Exception: - reason = "" - self._reason = reason - - @property - def keep_alive(self) -> Optional[bool]: - return self._keep_alive - - def force_close(self) -> None: - self._keep_alive = False - - @property - def body_length(self) -> int: - return self._body_length - - @property - def output_length(self) -> int: - warnings.warn("output_length is deprecated", DeprecationWarning) - assert self._payload_writer - return self._payload_writer.buffer_size - - def enable_chunked_encoding(self, chunk_size: Optional[int] = None) -> None: - """Enables automatic chunked transfer encoding.""" - self._chunked = True - - if hdrs.CONTENT_LENGTH in self._headers: - raise RuntimeError( - "You can't enable chunked encoding when " "a content length is set" - ) - if chunk_size is not None: - warnings.warn("Chunk size is deprecated #1615", DeprecationWarning) - - def enable_compression( - self, force: Optional[Union[bool, ContentCoding]] = None - ) -> None: - """Enables response compression encoding.""" - # Backwards compatibility for when force was a bool <0.17. - if type(force) == bool: - force = ContentCoding.deflate if force else ContentCoding.identity - warnings.warn( - "Using boolean for force is deprecated #3318", DeprecationWarning - ) - elif force is not None: - assert isinstance(force, ContentCoding), ( - "force should one of " "None, bool or " "ContentEncoding" - ) - - self._compression = True - self._compression_force = force - - @property - def headers(self) -> "CIMultiDict[str]": - return self._headers - - @property - def cookies(self) -> "SimpleCookie[str]": - return self._cookies - - def set_cookie( - self, - name: str, - value: str, - *, - expires: Optional[str] = None, - domain: Optional[str] = None, - max_age: Optional[Union[int, str]] = None, - path: str = "/", - secure: Optional[bool] = None, - httponly: Optional[bool] = None, - version: Optional[str] = None, - samesite: Optional[str] = None, - ) -> None: - """Set or update response cookie. - - Sets new cookie or updates existent with new value. - Also updates only those params which are not None. - """ - old = self._cookies.get(name) - if old is not None and old.coded_value == "": - # deleted cookie - self._cookies.pop(name, None) - - self._cookies[name] = value - c = self._cookies[name] - - if expires is not None: - c["expires"] = expires - elif c.get("expires") == "Thu, 01 Jan 1970 00:00:00 GMT": - del c["expires"] - - if domain is not None: - c["domain"] = domain - - if max_age is not None: - c["max-age"] = str(max_age) - elif "max-age" in c: - del c["max-age"] - - c["path"] = path - - if secure is not None: - c["secure"] = secure - if httponly is not None: - c["httponly"] = httponly - if version is not None: - c["version"] = version - if samesite is not None: - c["samesite"] = samesite - - def del_cookie( - self, name: str, *, domain: Optional[str] = None, path: str = "/" - ) -> None: - """Delete cookie. - - Creates new empty expired cookie. - """ - # TODO: do we need domain/path here? - self._cookies.pop(name, None) - self.set_cookie( - name, - "", - max_age=0, - expires="Thu, 01 Jan 1970 00:00:00 GMT", - domain=domain, - path=path, - ) - - @property - def content_length(self) -> Optional[int]: - # Just a placeholder for adding setter - return super().content_length - - @content_length.setter - def content_length(self, value: Optional[int]) -> None: - if value is not None: - value = int(value) - if self._chunked: - raise RuntimeError( - "You can't set content length when " "chunked encoding is enable" - ) - self._headers[hdrs.CONTENT_LENGTH] = str(value) - else: - self._headers.pop(hdrs.CONTENT_LENGTH, None) - - @property - def content_type(self) -> str: - # Just a placeholder for adding setter - return super().content_type - - @content_type.setter - def content_type(self, value: str) -> None: - self.content_type # read header values if needed - self._content_type = str(value) - self._generate_content_type_header() - - @property - def charset(self) -> Optional[str]: - # Just a placeholder for adding setter - return super().charset - - @charset.setter - def charset(self, value: Optional[str]) -> None: - ctype = self.content_type # read header values if needed - if ctype == "application/octet-stream": - raise RuntimeError( - "Setting charset for application/octet-stream " - "doesn't make sense, setup content_type first" - ) - assert self._content_dict is not None - if value is None: - self._content_dict.pop("charset", None) - else: - self._content_dict["charset"] = str(value).lower() - self._generate_content_type_header() - - @property - def last_modified(self) -> Optional[datetime.datetime]: - """The value of Last-Modified HTTP header, or None. - - This header is represented as a `datetime` object. - """ - return parse_http_date(self._headers.get(hdrs.LAST_MODIFIED)) - - @last_modified.setter - def last_modified( - self, value: Optional[Union[int, float, datetime.datetime, str]] - ) -> None: - if value is None: - self._headers.pop(hdrs.LAST_MODIFIED, None) - elif isinstance(value, (int, float)): - self._headers[hdrs.LAST_MODIFIED] = time.strftime( - "%a, %d %b %Y %H:%M:%S GMT", time.gmtime(math.ceil(value)) - ) - elif isinstance(value, datetime.datetime): - self._headers[hdrs.LAST_MODIFIED] = time.strftime( - "%a, %d %b %Y %H:%M:%S GMT", value.utctimetuple() - ) - elif isinstance(value, str): - self._headers[hdrs.LAST_MODIFIED] = value - - @property - def etag(self) -> Optional[ETag]: - quoted_value = self._headers.get(hdrs.ETAG) - if not quoted_value: - return None - elif quoted_value == ETAG_ANY: - return ETag(value=ETAG_ANY) - match = QUOTED_ETAG_RE.fullmatch(quoted_value) - if not match: - return None - is_weak, value = match.group(1, 2) - return ETag( - is_weak=bool(is_weak), - value=value, - ) - - @etag.setter - def etag(self, value: Optional[Union[ETag, str]]) -> None: - if value is None: - self._headers.pop(hdrs.ETAG, None) - elif (isinstance(value, str) and value == ETAG_ANY) or ( - isinstance(value, ETag) and value.value == ETAG_ANY - ): - self._headers[hdrs.ETAG] = ETAG_ANY - elif isinstance(value, str): - validate_etag_value(value) - self._headers[hdrs.ETAG] = f'"{value}"' - elif isinstance(value, ETag) and isinstance(value.value, str): - validate_etag_value(value.value) - hdr_value = f'W/"{value.value}"' if value.is_weak else f'"{value.value}"' - self._headers[hdrs.ETAG] = hdr_value - else: - raise ValueError( - f"Unsupported etag type: {type(value)}. " - f"etag must be str, ETag or None" - ) - - def _generate_content_type_header( - self, CONTENT_TYPE: istr = hdrs.CONTENT_TYPE - ) -> None: - assert self._content_dict is not None - assert self._content_type is not None - params = "; ".join(f"{k}={v}" for k, v in self._content_dict.items()) - if params: - ctype = self._content_type + "; " + params - else: - ctype = self._content_type - self._headers[CONTENT_TYPE] = ctype - - async def _do_start_compression(self, coding: ContentCoding) -> None: - if coding != ContentCoding.identity: - assert self._payload_writer is not None - self._headers[hdrs.CONTENT_ENCODING] = coding.value - self._payload_writer.enable_compression(coding.value) - # Compressed payload may have different content length, - # remove the header - self._headers.popall(hdrs.CONTENT_LENGTH, None) - - async def _start_compression(self, request: "BaseRequest") -> None: - if self._compression_force: - await self._do_start_compression(self._compression_force) - else: - accept_encoding = request.headers.get(hdrs.ACCEPT_ENCODING, "").lower() - for coding in ContentCoding: - if coding.value in accept_encoding: - await self._do_start_compression(coding) - return - - async def prepare(self, request: "BaseRequest") -> Optional[AbstractStreamWriter]: - if self._eof_sent: - return None - if self._payload_writer is not None: - return self._payload_writer - - return await self._start(request) - - async def _start(self, request: "BaseRequest") -> AbstractStreamWriter: - self._req = request - writer = self._payload_writer = request._payload_writer - - await self._prepare_headers() - await request._prepare_hook(self) - await self._write_headers() - - return writer - - async def _prepare_headers(self) -> None: - request = self._req - assert request is not None - writer = self._payload_writer - assert writer is not None - keep_alive = self._keep_alive - if keep_alive is None: - keep_alive = request.keep_alive - self._keep_alive = keep_alive - - version = request.version - - headers = self._headers - for cookie in self._cookies.values(): - value = cookie.output(header="")[1:] - headers.add(hdrs.SET_COOKIE, value) - - if self._compression: - await self._start_compression(request) - - if self._chunked: - if version != HttpVersion11: - raise RuntimeError( - "Using chunked encoding is forbidden " - "for HTTP/{0.major}.{0.minor}".format(request.version) - ) - writer.enable_chunking() - headers[hdrs.TRANSFER_ENCODING] = "chunked" - if hdrs.CONTENT_LENGTH in headers: - del headers[hdrs.CONTENT_LENGTH] - elif self._length_check: - writer.length = self.content_length - if writer.length is None: - if version >= HttpVersion11 and self.status != 204: - writer.enable_chunking() - headers[hdrs.TRANSFER_ENCODING] = "chunked" - if hdrs.CONTENT_LENGTH in headers: - del headers[hdrs.CONTENT_LENGTH] - else: - keep_alive = False - # HTTP 1.1: https://tools.ietf.org/html/rfc7230#section-3.3.2 - # HTTP 1.0: https://tools.ietf.org/html/rfc1945#section-10.4 - elif version >= HttpVersion11 and self.status in (100, 101, 102, 103, 204): - del headers[hdrs.CONTENT_LENGTH] - - if self.status not in (204, 304): - headers.setdefault(hdrs.CONTENT_TYPE, "application/octet-stream") - headers.setdefault(hdrs.DATE, rfc822_formatted_time()) - headers.setdefault(hdrs.SERVER, SERVER_SOFTWARE) - - # connection header - if hdrs.CONNECTION not in headers: - if keep_alive: - if version == HttpVersion10: - headers[hdrs.CONNECTION] = "keep-alive" - else: - if version == HttpVersion11: - headers[hdrs.CONNECTION] = "close" - - async def _write_headers(self) -> None: - request = self._req - assert request is not None - writer = self._payload_writer - assert writer is not None - # status line - version = request.version - status_line = "HTTP/{}.{} {} {}".format( - version[0], version[1], self._status, self._reason - ) - await writer.write_headers(status_line, self._headers) - - async def write(self, data: bytes) -> None: - assert isinstance( - data, (bytes, bytearray, memoryview) - ), "data argument must be byte-ish (%r)" % type(data) - - if self._eof_sent: - raise RuntimeError("Cannot call write() after write_eof()") - if self._payload_writer is None: - raise RuntimeError("Cannot call write() before prepare()") - - await self._payload_writer.write(data) - - async def drain(self) -> None: - assert not self._eof_sent, "EOF has already been sent" - assert self._payload_writer is not None, "Response has not been started" - warnings.warn( - "drain method is deprecated, use await resp.write()", - DeprecationWarning, - stacklevel=2, - ) - await self._payload_writer.drain() - - async def write_eof(self, data: bytes = b"") -> None: - assert isinstance( - data, (bytes, bytearray, memoryview) - ), "data argument must be byte-ish (%r)" % type(data) - - if self._eof_sent: - return - - assert self._payload_writer is not None, "Response has not been started" - - await self._payload_writer.write_eof(data) - self._eof_sent = True - self._req = None - self._body_length = self._payload_writer.output_size - self._payload_writer = None - - def __repr__(self) -> str: - if self._eof_sent: - info = "eof" - elif self.prepared: - assert self._req is not None - info = f"{self._req.method} {self._req.path} " - else: - info = "not prepared" - return f"<{self.__class__.__name__} {self.reason} {info}>" - - def __getitem__(self, key: str) -> Any: - return self._state[key] - - def __setitem__(self, key: str, value: Any) -> None: - self._state[key] = value - - def __delitem__(self, key: str) -> None: - del self._state[key] - - def __len__(self) -> int: - return len(self._state) - - def __iter__(self) -> Iterator[str]: - return iter(self._state) - - def __hash__(self) -> int: - return hash(id(self)) - - def __eq__(self, other: object) -> bool: - return self is other - - -class Response(StreamResponse): - def __init__( - self, - *, - body: Any = None, - status: int = 200, - reason: Optional[str] = None, - text: Optional[str] = None, - headers: Optional[LooseHeaders] = None, - content_type: Optional[str] = None, - charset: Optional[str] = None, - zlib_executor_size: Optional[int] = None, - zlib_executor: Optional[Executor] = None, - ) -> None: - if body is not None and text is not None: - raise ValueError("body and text are not allowed together") - - if headers is None: - real_headers = CIMultiDict() # type: CIMultiDict[str] - elif not isinstance(headers, CIMultiDict): - real_headers = CIMultiDict(headers) - else: - real_headers = headers # = cast('CIMultiDict[str]', headers) - - if content_type is not None and "charset" in content_type: - raise ValueError("charset must not be in content_type " "argument") - - if text is not None: - if hdrs.CONTENT_TYPE in real_headers: - if content_type or charset: - raise ValueError( - "passing both Content-Type header and " - "content_type or charset params " - "is forbidden" - ) - else: - # fast path for filling headers - if not isinstance(text, str): - raise TypeError("text argument must be str (%r)" % type(text)) - if content_type is None: - content_type = "text/plain" - if charset is None: - charset = "utf-8" - real_headers[hdrs.CONTENT_TYPE] = content_type + "; charset=" + charset - body = text.encode(charset) - text = None - else: - if hdrs.CONTENT_TYPE in real_headers: - if content_type is not None or charset is not None: - raise ValueError( - "passing both Content-Type header and " - "content_type or charset params " - "is forbidden" - ) - else: - if content_type is not None: - if charset is not None: - content_type += "; charset=" + charset - real_headers[hdrs.CONTENT_TYPE] = content_type - - super().__init__(status=status, reason=reason, headers=real_headers) - - if text is not None: - self.text = text - else: - self.body = body - - self._compressed_body = None # type: Optional[bytes] - self._zlib_executor_size = zlib_executor_size - self._zlib_executor = zlib_executor - - @property - def body(self) -> Optional[Union[bytes, Payload]]: - return self._body - - @body.setter - def body( - self, - body: bytes, - CONTENT_TYPE: istr = hdrs.CONTENT_TYPE, - CONTENT_LENGTH: istr = hdrs.CONTENT_LENGTH, - ) -> None: - if body is None: - self._body = None # type: Optional[bytes] - self._body_payload = False # type: bool - elif isinstance(body, (bytes, bytearray)): - self._body = body - self._body_payload = False - else: - try: - self._body = body = payload.PAYLOAD_REGISTRY.get(body) - except payload.LookupError: - raise ValueError("Unsupported body type %r" % type(body)) - - self._body_payload = True - - headers = self._headers - - # set content-length header if needed - if not self._chunked and CONTENT_LENGTH not in headers: - size = body.size - if size is not None: - headers[CONTENT_LENGTH] = str(size) - - # set content-type - if CONTENT_TYPE not in headers: - headers[CONTENT_TYPE] = body.content_type - - # copy payload headers - if body.headers: - for (key, value) in body.headers.items(): - if key not in headers: - headers[key] = value - - self._compressed_body = None - - @property - def text(self) -> Optional[str]: - if self._body is None: - return None - return self._body.decode(self.charset or "utf-8") - - @text.setter - def text(self, text: str) -> None: - assert text is None or isinstance( - text, str - ), "text argument must be str (%r)" % type(text) - - if self.content_type == "application/octet-stream": - self.content_type = "text/plain" - if self.charset is None: - self.charset = "utf-8" - - self._body = text.encode(self.charset) - self._body_payload = False - self._compressed_body = None - - @property - def content_length(self) -> Optional[int]: - if self._chunked: - return None - - if hdrs.CONTENT_LENGTH in self._headers: - return super().content_length - - if self._compressed_body is not None: - # Return length of the compressed body - return len(self._compressed_body) - elif self._body_payload: - # A payload without content length, or a compressed payload - return None - elif self._body is not None: - return len(self._body) - else: - return 0 - - @content_length.setter - def content_length(self, value: Optional[int]) -> None: - raise RuntimeError("Content length is set automatically") - - async def write_eof(self, data: bytes = b"") -> None: - if self._eof_sent: - return - if self._compressed_body is None: - body = self._body # type: Optional[Union[bytes, Payload]] - else: - body = self._compressed_body - assert not data, f"data arg is not supported, got {data!r}" - assert self._req is not None - assert self._payload_writer is not None - if body is not None: - if self._req._method == hdrs.METH_HEAD or self._status in [204, 304]: - await super().write_eof() - elif self._body_payload: - payload = cast(Payload, body) - await payload.write(self._payload_writer) - await super().write_eof() - else: - await super().write_eof(cast(bytes, body)) - else: - await super().write_eof() - - async def _start(self, request: "BaseRequest") -> AbstractStreamWriter: - if not self._chunked and hdrs.CONTENT_LENGTH not in self._headers: - if not self._body_payload: - if self._body is not None: - self._headers[hdrs.CONTENT_LENGTH] = str(len(self._body)) - else: - self._headers[hdrs.CONTENT_LENGTH] = "0" - - return await super()._start(request) - - def _compress_body(self, zlib_mode: int) -> None: - assert zlib_mode > 0 - compressobj = zlib.compressobj(wbits=zlib_mode) - body_in = self._body - assert body_in is not None - self._compressed_body = compressobj.compress(body_in) + compressobj.flush() - - async def _do_start_compression(self, coding: ContentCoding) -> None: - if self._body_payload or self._chunked: - return await super()._do_start_compression(coding) - - if coding != ContentCoding.identity: - # Instead of using _payload_writer.enable_compression, - # compress the whole body - zlib_mode = ( - 16 + zlib.MAX_WBITS if coding == ContentCoding.gzip else zlib.MAX_WBITS - ) - body_in = self._body - assert body_in is not None - if ( - self._zlib_executor_size is not None - and len(body_in) > self._zlib_executor_size - ): - await asyncio.get_event_loop().run_in_executor( - self._zlib_executor, self._compress_body, zlib_mode - ) - else: - self._compress_body(zlib_mode) - - body_out = self._compressed_body - assert body_out is not None - - self._headers[hdrs.CONTENT_ENCODING] = coding.value - self._headers[hdrs.CONTENT_LENGTH] = str(len(body_out)) - - -def json_response( - data: Any = sentinel, - *, - text: Optional[str] = None, - body: Optional[bytes] = None, - status: int = 200, - reason: Optional[str] = None, - headers: Optional[LooseHeaders] = None, - content_type: str = "application/json", - dumps: JSONEncoder = json.dumps, -) -> Response: - if data is not sentinel: - if text or body: - raise ValueError("only one of data, text, or body should be specified") - else: - text = dumps(data) - return Response( - text=text, - body=body, - status=status, - reason=reason, - headers=headers, - content_type=content_type, - ) diff --git a/.venv/Lib/site-packages/aiohttp/web_routedef.py b/.venv/Lib/site-packages/aiohttp/web_routedef.py deleted file mode 100644 index 671e5c7..0000000 --- a/.venv/Lib/site-packages/aiohttp/web_routedef.py +++ /dev/null @@ -1,213 +0,0 @@ -import abc -import os # noqa -from typing import ( - TYPE_CHECKING, - Any, - Callable, - Dict, - Iterator, - List, - Optional, - Sequence, - Type, - Union, - overload, -) - -import attr - -from . import hdrs -from .abc import AbstractView -from .typedefs import Handler, PathLike - -if TYPE_CHECKING: # pragma: no cover - from .web_request import Request - from .web_response import StreamResponse - from .web_urldispatcher import AbstractRoute, UrlDispatcher -else: - Request = StreamResponse = UrlDispatcher = AbstractRoute = None - - -__all__ = ( - "AbstractRouteDef", - "RouteDef", - "StaticDef", - "RouteTableDef", - "head", - "options", - "get", - "post", - "patch", - "put", - "delete", - "route", - "view", - "static", -) - - -class AbstractRouteDef(abc.ABC): - @abc.abstractmethod - def register(self, router: UrlDispatcher) -> List[AbstractRoute]: - pass # pragma: no cover - - -_HandlerType = Union[Type[AbstractView], Handler] - - -@attr.s(auto_attribs=True, frozen=True, repr=False, slots=True) -class RouteDef(AbstractRouteDef): - method: str - path: str - handler: _HandlerType - kwargs: Dict[str, Any] - - def __repr__(self) -> str: - info = [] - for name, value in sorted(self.kwargs.items()): - info.append(f", {name}={value!r}") - return " {handler.__name__!r}" "{info}>".format( - method=self.method, path=self.path, handler=self.handler, info="".join(info) - ) - - def register(self, router: UrlDispatcher) -> List[AbstractRoute]: - if self.method in hdrs.METH_ALL: - reg = getattr(router, "add_" + self.method.lower()) - return [reg(self.path, self.handler, **self.kwargs)] - else: - return [ - router.add_route(self.method, self.path, self.handler, **self.kwargs) - ] - - -@attr.s(auto_attribs=True, frozen=True, repr=False, slots=True) -class StaticDef(AbstractRouteDef): - prefix: str - path: PathLike - kwargs: Dict[str, Any] - - def __repr__(self) -> str: - info = [] - for name, value in sorted(self.kwargs.items()): - info.append(f", {name}={value!r}") - return " {path}" "{info}>".format( - prefix=self.prefix, path=self.path, info="".join(info) - ) - - def register(self, router: UrlDispatcher) -> List[AbstractRoute]: - resource = router.add_static(self.prefix, self.path, **self.kwargs) - routes = resource.get_info().get("routes", {}) - return list(routes.values()) - - -def route(method: str, path: str, handler: _HandlerType, **kwargs: Any) -> RouteDef: - return RouteDef(method, path, handler, kwargs) - - -def head(path: str, handler: _HandlerType, **kwargs: Any) -> RouteDef: - return route(hdrs.METH_HEAD, path, handler, **kwargs) - - -def options(path: str, handler: _HandlerType, **kwargs: Any) -> RouteDef: - return route(hdrs.METH_OPTIONS, path, handler, **kwargs) - - -def get( - path: str, - handler: _HandlerType, - *, - name: Optional[str] = None, - allow_head: bool = True, - **kwargs: Any, -) -> RouteDef: - return route( - hdrs.METH_GET, path, handler, name=name, allow_head=allow_head, **kwargs - ) - - -def post(path: str, handler: _HandlerType, **kwargs: Any) -> RouteDef: - return route(hdrs.METH_POST, path, handler, **kwargs) - - -def put(path: str, handler: _HandlerType, **kwargs: Any) -> RouteDef: - return route(hdrs.METH_PUT, path, handler, **kwargs) - - -def patch(path: str, handler: _HandlerType, **kwargs: Any) -> RouteDef: - return route(hdrs.METH_PATCH, path, handler, **kwargs) - - -def delete(path: str, handler: _HandlerType, **kwargs: Any) -> RouteDef: - return route(hdrs.METH_DELETE, path, handler, **kwargs) - - -def view(path: str, handler: Type[AbstractView], **kwargs: Any) -> RouteDef: - return route(hdrs.METH_ANY, path, handler, **kwargs) - - -def static(prefix: str, path: PathLike, **kwargs: Any) -> StaticDef: - return StaticDef(prefix, path, kwargs) - - -_Deco = Callable[[_HandlerType], _HandlerType] - - -class RouteTableDef(Sequence[AbstractRouteDef]): - """Route definition table""" - - def __init__(self) -> None: - self._items = [] # type: List[AbstractRouteDef] - - def __repr__(self) -> str: - return f"" - - @overload - def __getitem__(self, index: int) -> AbstractRouteDef: - ... - - @overload - def __getitem__(self, index: slice) -> List[AbstractRouteDef]: - ... - - def __getitem__(self, index): # type: ignore[no-untyped-def] - return self._items[index] - - def __iter__(self) -> Iterator[AbstractRouteDef]: - return iter(self._items) - - def __len__(self) -> int: - return len(self._items) - - def __contains__(self, item: object) -> bool: - return item in self._items - - def route(self, method: str, path: str, **kwargs: Any) -> _Deco: - def inner(handler: _HandlerType) -> _HandlerType: - self._items.append(RouteDef(method, path, handler, kwargs)) - return handler - - return inner - - def head(self, path: str, **kwargs: Any) -> _Deco: - return self.route(hdrs.METH_HEAD, path, **kwargs) - - def get(self, path: str, **kwargs: Any) -> _Deco: - return self.route(hdrs.METH_GET, path, **kwargs) - - def post(self, path: str, **kwargs: Any) -> _Deco: - return self.route(hdrs.METH_POST, path, **kwargs) - - def put(self, path: str, **kwargs: Any) -> _Deco: - return self.route(hdrs.METH_PUT, path, **kwargs) - - def patch(self, path: str, **kwargs: Any) -> _Deco: - return self.route(hdrs.METH_PATCH, path, **kwargs) - - def delete(self, path: str, **kwargs: Any) -> _Deco: - return self.route(hdrs.METH_DELETE, path, **kwargs) - - def view(self, path: str, **kwargs: Any) -> _Deco: - return self.route(hdrs.METH_ANY, path, **kwargs) - - def static(self, prefix: str, path: PathLike, **kwargs: Any) -> None: - self._items.append(StaticDef(prefix, path, kwargs)) diff --git a/.venv/Lib/site-packages/aiohttp/web_runner.py b/.venv/Lib/site-packages/aiohttp/web_runner.py deleted file mode 100644 index f4a64bf..0000000 --- a/.venv/Lib/site-packages/aiohttp/web_runner.py +++ /dev/null @@ -1,381 +0,0 @@ -import asyncio -import signal -import socket -from abc import ABC, abstractmethod -from typing import Any, List, Optional, Set - -from yarl import URL - -from .web_app import Application -from .web_server import Server - -try: - from ssl import SSLContext -except ImportError: - SSLContext = object # type: ignore[misc,assignment] - - -__all__ = ( - "BaseSite", - "TCPSite", - "UnixSite", - "NamedPipeSite", - "SockSite", - "BaseRunner", - "AppRunner", - "ServerRunner", - "GracefulExit", -) - - -class GracefulExit(SystemExit): - code = 1 - - -def _raise_graceful_exit() -> None: - raise GracefulExit() - - -class BaseSite(ABC): - __slots__ = ("_runner", "_shutdown_timeout", "_ssl_context", "_backlog", "_server") - - def __init__( - self, - runner: "BaseRunner", - *, - shutdown_timeout: float = 60.0, - ssl_context: Optional[SSLContext] = None, - backlog: int = 128, - ) -> None: - if runner.server is None: - raise RuntimeError("Call runner.setup() before making a site") - self._runner = runner - self._shutdown_timeout = shutdown_timeout - self._ssl_context = ssl_context - self._backlog = backlog - self._server = None # type: Optional[asyncio.AbstractServer] - - @property - @abstractmethod - def name(self) -> str: - pass # pragma: no cover - - @abstractmethod - async def start(self) -> None: - self._runner._reg_site(self) - - async def stop(self) -> None: - self._runner._check_site(self) - if self._server is None: - self._runner._unreg_site(self) - return # not started yet - self._server.close() - # named pipes do not have wait_closed property - if hasattr(self._server, "wait_closed"): - await self._server.wait_closed() - await self._runner.shutdown() - assert self._runner.server - await self._runner.server.shutdown(self._shutdown_timeout) - self._runner._unreg_site(self) - - -class TCPSite(BaseSite): - __slots__ = ("_host", "_port", "_reuse_address", "_reuse_port") - - def __init__( - self, - runner: "BaseRunner", - host: Optional[str] = None, - port: Optional[int] = None, - *, - shutdown_timeout: float = 60.0, - ssl_context: Optional[SSLContext] = None, - backlog: int = 128, - reuse_address: Optional[bool] = None, - reuse_port: Optional[bool] = None, - ) -> None: - super().__init__( - runner, - shutdown_timeout=shutdown_timeout, - ssl_context=ssl_context, - backlog=backlog, - ) - self._host = host - if port is None: - port = 8443 if self._ssl_context else 8080 - self._port = port - self._reuse_address = reuse_address - self._reuse_port = reuse_port - - @property - def name(self) -> str: - scheme = "https" if self._ssl_context else "http" - host = "0.0.0.0" if self._host is None else self._host - return str(URL.build(scheme=scheme, host=host, port=self._port)) - - async def start(self) -> None: - await super().start() - loop = asyncio.get_event_loop() - server = self._runner.server - assert server is not None - self._server = await loop.create_server( - server, - self._host, - self._port, - ssl=self._ssl_context, - backlog=self._backlog, - reuse_address=self._reuse_address, - reuse_port=self._reuse_port, - ) - - -class UnixSite(BaseSite): - __slots__ = ("_path",) - - def __init__( - self, - runner: "BaseRunner", - path: str, - *, - shutdown_timeout: float = 60.0, - ssl_context: Optional[SSLContext] = None, - backlog: int = 128, - ) -> None: - super().__init__( - runner, - shutdown_timeout=shutdown_timeout, - ssl_context=ssl_context, - backlog=backlog, - ) - self._path = path - - @property - def name(self) -> str: - scheme = "https" if self._ssl_context else "http" - return f"{scheme}://unix:{self._path}:" - - async def start(self) -> None: - await super().start() - loop = asyncio.get_event_loop() - server = self._runner.server - assert server is not None - self._server = await loop.create_unix_server( - server, self._path, ssl=self._ssl_context, backlog=self._backlog - ) - - -class NamedPipeSite(BaseSite): - __slots__ = ("_path",) - - def __init__( - self, runner: "BaseRunner", path: str, *, shutdown_timeout: float = 60.0 - ) -> None: - loop = asyncio.get_event_loop() - if not isinstance( - loop, asyncio.ProactorEventLoop # type: ignore[attr-defined] - ): - raise RuntimeError( - "Named Pipes only available in proactor" "loop under windows" - ) - super().__init__(runner, shutdown_timeout=shutdown_timeout) - self._path = path - - @property - def name(self) -> str: - return self._path - - async def start(self) -> None: - await super().start() - loop = asyncio.get_event_loop() - server = self._runner.server - assert server is not None - _server = await loop.start_serving_pipe( # type: ignore[attr-defined] - server, self._path - ) - self._server = _server[0] - - -class SockSite(BaseSite): - __slots__ = ("_sock", "_name") - - def __init__( - self, - runner: "BaseRunner", - sock: socket.socket, - *, - shutdown_timeout: float = 60.0, - ssl_context: Optional[SSLContext] = None, - backlog: int = 128, - ) -> None: - super().__init__( - runner, - shutdown_timeout=shutdown_timeout, - ssl_context=ssl_context, - backlog=backlog, - ) - self._sock = sock - scheme = "https" if self._ssl_context else "http" - if hasattr(socket, "AF_UNIX") and sock.family == socket.AF_UNIX: - name = f"{scheme}://unix:{sock.getsockname()}:" - else: - host, port = sock.getsockname()[:2] - name = str(URL.build(scheme=scheme, host=host, port=port)) - self._name = name - - @property - def name(self) -> str: - return self._name - - async def start(self) -> None: - await super().start() - loop = asyncio.get_event_loop() - server = self._runner.server - assert server is not None - self._server = await loop.create_server( - server, sock=self._sock, ssl=self._ssl_context, backlog=self._backlog - ) - - -class BaseRunner(ABC): - __slots__ = ("_handle_signals", "_kwargs", "_server", "_sites") - - def __init__(self, *, handle_signals: bool = False, **kwargs: Any) -> None: - self._handle_signals = handle_signals - self._kwargs = kwargs - self._server = None # type: Optional[Server] - self._sites = [] # type: List[BaseSite] - - @property - def server(self) -> Optional[Server]: - return self._server - - @property - def addresses(self) -> List[Any]: - ret = [] # type: List[Any] - for site in self._sites: - server = site._server - if server is not None: - sockets = server.sockets - if sockets is not None: - for sock in sockets: - ret.append(sock.getsockname()) - return ret - - @property - def sites(self) -> Set[BaseSite]: - return set(self._sites) - - async def setup(self) -> None: - loop = asyncio.get_event_loop() - - if self._handle_signals: - try: - loop.add_signal_handler(signal.SIGINT, _raise_graceful_exit) - loop.add_signal_handler(signal.SIGTERM, _raise_graceful_exit) - except NotImplementedError: # pragma: no cover - # add_signal_handler is not implemented on Windows - pass - - self._server = await self._make_server() - - @abstractmethod - async def shutdown(self) -> None: - pass # pragma: no cover - - async def cleanup(self) -> None: - loop = asyncio.get_event_loop() - - # The loop over sites is intentional, an exception on gather() - # leaves self._sites in unpredictable state. - # The loop guaranties that a site is either deleted on success or - # still present on failure - for site in list(self._sites): - await site.stop() - await self._cleanup_server() - self._server = None - if self._handle_signals: - try: - loop.remove_signal_handler(signal.SIGINT) - loop.remove_signal_handler(signal.SIGTERM) - except NotImplementedError: # pragma: no cover - # remove_signal_handler is not implemented on Windows - pass - - @abstractmethod - async def _make_server(self) -> Server: - pass # pragma: no cover - - @abstractmethod - async def _cleanup_server(self) -> None: - pass # pragma: no cover - - def _reg_site(self, site: BaseSite) -> None: - if site in self._sites: - raise RuntimeError(f"Site {site} is already registered in runner {self}") - self._sites.append(site) - - def _check_site(self, site: BaseSite) -> None: - if site not in self._sites: - raise RuntimeError(f"Site {site} is not registered in runner {self}") - - def _unreg_site(self, site: BaseSite) -> None: - if site not in self._sites: - raise RuntimeError(f"Site {site} is not registered in runner {self}") - self._sites.remove(site) - - -class ServerRunner(BaseRunner): - """Low-level web server runner""" - - __slots__ = ("_web_server",) - - def __init__( - self, web_server: Server, *, handle_signals: bool = False, **kwargs: Any - ) -> None: - super().__init__(handle_signals=handle_signals, **kwargs) - self._web_server = web_server - - async def shutdown(self) -> None: - pass - - async def _make_server(self) -> Server: - return self._web_server - - async def _cleanup_server(self) -> None: - pass - - -class AppRunner(BaseRunner): - """Web Application runner""" - - __slots__ = ("_app",) - - def __init__( - self, app: Application, *, handle_signals: bool = False, **kwargs: Any - ) -> None: - super().__init__(handle_signals=handle_signals, **kwargs) - if not isinstance(app, Application): - raise TypeError( - "The first argument should be web.Application " - "instance, got {!r}".format(app) - ) - self._app = app - - @property - def app(self) -> Application: - return self._app - - async def shutdown(self) -> None: - await self._app.shutdown() - - async def _make_server(self) -> Server: - loop = asyncio.get_event_loop() - self._app._set_loop(loop) - self._app.on_startup.freeze() - await self._app.startup() - self._app.freeze() - - return self._app._make_handler(loop=loop, **self._kwargs) - - async def _cleanup_server(self) -> None: - await self._app.cleanup() diff --git a/.venv/Lib/site-packages/aiohttp/web_server.py b/.venv/Lib/site-packages/aiohttp/web_server.py deleted file mode 100644 index 5657ed9..0000000 --- a/.venv/Lib/site-packages/aiohttp/web_server.py +++ /dev/null @@ -1,62 +0,0 @@ -"""Low level HTTP server.""" -import asyncio -from typing import Any, Awaitable, Callable, Dict, List, Optional # noqa - -from .abc import AbstractStreamWriter -from .helpers import get_running_loop -from .http_parser import RawRequestMessage -from .streams import StreamReader -from .web_protocol import RequestHandler, _RequestFactory, _RequestHandler -from .web_request import BaseRequest - -__all__ = ("Server",) - - -class Server: - def __init__( - self, - handler: _RequestHandler, - *, - request_factory: Optional[_RequestFactory] = None, - loop: Optional[asyncio.AbstractEventLoop] = None, - **kwargs: Any - ) -> None: - self._loop = get_running_loop(loop) - self._connections = {} # type: Dict[RequestHandler, asyncio.Transport] - self._kwargs = kwargs - self.requests_count = 0 - self.request_handler = handler - self.request_factory = request_factory or self._make_request - - @property - def connections(self) -> List[RequestHandler]: - return list(self._connections.keys()) - - def connection_made( - self, handler: RequestHandler, transport: asyncio.Transport - ) -> None: - self._connections[handler] = transport - - def connection_lost( - self, handler: RequestHandler, exc: Optional[BaseException] = None - ) -> None: - if handler in self._connections: - del self._connections[handler] - - def _make_request( - self, - message: RawRequestMessage, - payload: StreamReader, - protocol: RequestHandler, - writer: AbstractStreamWriter, - task: "asyncio.Task[None]", - ) -> BaseRequest: - return BaseRequest(message, payload, protocol, writer, task, self._loop) - - async def shutdown(self, timeout: Optional[float] = None) -> None: - coros = [conn.shutdown(timeout) for conn in self._connections] - await asyncio.gather(*coros) - self._connections.clear() - - def __call__(self) -> RequestHandler: - return RequestHandler(self, loop=self._loop, **self._kwargs) diff --git a/.venv/Lib/site-packages/aiohttp/web_urldispatcher.py b/.venv/Lib/site-packages/aiohttp/web_urldispatcher.py deleted file mode 100644 index 73ec4c0..0000000 --- a/.venv/Lib/site-packages/aiohttp/web_urldispatcher.py +++ /dev/null @@ -1,1220 +0,0 @@ -import abc -import asyncio -import base64 -import hashlib -import inspect -import keyword -import os -import re -import warnings -from contextlib import contextmanager -from functools import wraps -from pathlib import Path -from types import MappingProxyType -from typing import ( - TYPE_CHECKING, - Any, - Awaitable, - Callable, - Container, - Dict, - Generator, - Iterable, - Iterator, - List, - Mapping, - Optional, - Pattern, - Set, - Sized, - Tuple, - Type, - Union, - cast, -) - -from yarl import URL, __version__ as yarl_version # type: ignore[attr-defined] - -from . import hdrs -from .abc import AbstractMatchInfo, AbstractRouter, AbstractView -from .helpers import DEBUG -from .http import HttpVersion11 -from .typedefs import Final, Handler, PathLike, TypedDict -from .web_exceptions import ( - HTTPException, - HTTPExpectationFailed, - HTTPForbidden, - HTTPMethodNotAllowed, - HTTPNotFound, -) -from .web_fileresponse import FileResponse -from .web_request import Request -from .web_response import Response, StreamResponse -from .web_routedef import AbstractRouteDef - -__all__ = ( - "UrlDispatcher", - "UrlMappingMatchInfo", - "AbstractResource", - "Resource", - "PlainResource", - "DynamicResource", - "AbstractRoute", - "ResourceRoute", - "StaticResource", - "View", -) - - -if TYPE_CHECKING: # pragma: no cover - from .web_app import Application - - BaseDict = Dict[str, str] -else: - BaseDict = dict - -YARL_VERSION: Final[Tuple[int, ...]] = tuple(map(int, yarl_version.split(".")[:2])) - -HTTP_METHOD_RE: Final[Pattern[str]] = re.compile( - r"^[0-9A-Za-z!#\$%&'\*\+\-\.\^_`\|~]+$" -) -ROUTE_RE: Final[Pattern[str]] = re.compile( - r"(\{[_a-zA-Z][^{}]*(?:\{[^{}]*\}[^{}]*)*\})" -) -PATH_SEP: Final[str] = re.escape("/") - - -_ExpectHandler = Callable[[Request], Awaitable[None]] -_Resolve = Tuple[Optional["UrlMappingMatchInfo"], Set[str]] - - -class _InfoDict(TypedDict, total=False): - path: str - - formatter: str - pattern: Pattern[str] - - directory: Path - prefix: str - routes: Mapping[str, "AbstractRoute"] - - app: "Application" - - domain: str - - rule: "AbstractRuleMatching" - - http_exception: HTTPException - - -class AbstractResource(Sized, Iterable["AbstractRoute"]): - def __init__(self, *, name: Optional[str] = None) -> None: - self._name = name - - @property - def name(self) -> Optional[str]: - return self._name - - @property - @abc.abstractmethod - def canonical(self) -> str: - """Exposes the resource's canonical path. - - For example '/foo/bar/{name}' - - """ - - @abc.abstractmethod # pragma: no branch - def url_for(self, **kwargs: str) -> URL: - """Construct url for resource with additional params.""" - - @abc.abstractmethod # pragma: no branch - async def resolve(self, request: Request) -> _Resolve: - """Resolve resource. - - Return (UrlMappingMatchInfo, allowed_methods) pair. - """ - - @abc.abstractmethod - def add_prefix(self, prefix: str) -> None: - """Add a prefix to processed URLs. - - Required for subapplications support. - """ - - @abc.abstractmethod - def get_info(self) -> _InfoDict: - """Return a dict with additional info useful for introspection""" - - def freeze(self) -> None: - pass - - @abc.abstractmethod - def raw_match(self, path: str) -> bool: - """Perform a raw match against path""" - - -class AbstractRoute(abc.ABC): - def __init__( - self, - method: str, - handler: Union[Handler, Type[AbstractView]], - *, - expect_handler: Optional[_ExpectHandler] = None, - resource: Optional[AbstractResource] = None, - ) -> None: - - if expect_handler is None: - expect_handler = _default_expect_handler - - assert asyncio.iscoroutinefunction( - expect_handler - ), f"Coroutine is expected, got {expect_handler!r}" - - method = method.upper() - if not HTTP_METHOD_RE.match(method): - raise ValueError(f"{method} is not allowed HTTP method") - - assert callable(handler), handler - if asyncio.iscoroutinefunction(handler): - pass - elif inspect.isgeneratorfunction(handler): - warnings.warn( - "Bare generators are deprecated, " "use @coroutine wrapper", - DeprecationWarning, - ) - elif isinstance(handler, type) and issubclass(handler, AbstractView): - pass - else: - warnings.warn( - "Bare functions are deprecated, " "use async ones", DeprecationWarning - ) - - @wraps(handler) - async def handler_wrapper(request: Request) -> StreamResponse: - result = old_handler(request) - if asyncio.iscoroutine(result): - return await result - return result # type: ignore[return-value] - - old_handler = handler - handler = handler_wrapper - - self._method = method - self._handler = handler - self._expect_handler = expect_handler - self._resource = resource - - @property - def method(self) -> str: - return self._method - - @property - def handler(self) -> Handler: - return self._handler - - @property - @abc.abstractmethod - def name(self) -> Optional[str]: - """Optional route's name, always equals to resource's name.""" - - @property - def resource(self) -> Optional[AbstractResource]: - return self._resource - - @abc.abstractmethod - def get_info(self) -> _InfoDict: - """Return a dict with additional info useful for introspection""" - - @abc.abstractmethod # pragma: no branch - def url_for(self, *args: str, **kwargs: str) -> URL: - """Construct url for route with additional params.""" - - async def handle_expect_header(self, request: Request) -> None: - await self._expect_handler(request) - - -class UrlMappingMatchInfo(BaseDict, AbstractMatchInfo): - def __init__(self, match_dict: Dict[str, str], route: AbstractRoute): - super().__init__(match_dict) - self._route = route - self._apps = [] # type: List[Application] - self._current_app = None # type: Optional[Application] - self._frozen = False - - @property - def handler(self) -> Handler: - return self._route.handler - - @property - def route(self) -> AbstractRoute: - return self._route - - @property - def expect_handler(self) -> _ExpectHandler: - return self._route.handle_expect_header - - @property - def http_exception(self) -> Optional[HTTPException]: - return None - - def get_info(self) -> _InfoDict: # type: ignore[override] - return self._route.get_info() - - @property - def apps(self) -> Tuple["Application", ...]: - return tuple(self._apps) - - def add_app(self, app: "Application") -> None: - if self._frozen: - raise RuntimeError("Cannot change apps stack after .freeze() call") - if self._current_app is None: - self._current_app = app - self._apps.insert(0, app) - - @property - def current_app(self) -> "Application": - app = self._current_app - assert app is not None - return app - - @contextmanager - def set_current_app(self, app: "Application") -> Generator[None, None, None]: - if DEBUG: # pragma: no cover - if app not in self._apps: - raise RuntimeError( - "Expected one of the following apps {!r}, got {!r}".format( - self._apps, app - ) - ) - prev = self._current_app - self._current_app = app - try: - yield - finally: - self._current_app = prev - - def freeze(self) -> None: - self._frozen = True - - def __repr__(self) -> str: - return f"" - - -class MatchInfoError(UrlMappingMatchInfo): - def __init__(self, http_exception: HTTPException) -> None: - self._exception = http_exception - super().__init__({}, SystemRoute(self._exception)) - - @property - def http_exception(self) -> HTTPException: - return self._exception - - def __repr__(self) -> str: - return "".format( - self._exception.status, self._exception.reason - ) - - -async def _default_expect_handler(request: Request) -> None: - """Default handler for Expect header. - - Just send "100 Continue" to client. - raise HTTPExpectationFailed if value of header is not "100-continue" - """ - expect = request.headers.get(hdrs.EXPECT, "") - if request.version == HttpVersion11: - if expect.lower() == "100-continue": - await request.writer.write(b"HTTP/1.1 100 Continue\r\n\r\n") - else: - raise HTTPExpectationFailed(text="Unknown Expect: %s" % expect) - - -class Resource(AbstractResource): - def __init__(self, *, name: Optional[str] = None) -> None: - super().__init__(name=name) - self._routes = [] # type: List[ResourceRoute] - - def add_route( - self, - method: str, - handler: Union[Type[AbstractView], Handler], - *, - expect_handler: Optional[_ExpectHandler] = None, - ) -> "ResourceRoute": - - for route_obj in self._routes: - if route_obj.method == method or route_obj.method == hdrs.METH_ANY: - raise RuntimeError( - "Added route will never be executed, " - "method {route.method} is already " - "registered".format(route=route_obj) - ) - - route_obj = ResourceRoute(method, handler, self, expect_handler=expect_handler) - self.register_route(route_obj) - return route_obj - - def register_route(self, route: "ResourceRoute") -> None: - assert isinstance( - route, ResourceRoute - ), f"Instance of Route class is required, got {route!r}" - self._routes.append(route) - - async def resolve(self, request: Request) -> _Resolve: - allowed_methods = set() # type: Set[str] - - match_dict = self._match(request.rel_url.raw_path) - if match_dict is None: - return None, allowed_methods - - for route_obj in self._routes: - route_method = route_obj.method - allowed_methods.add(route_method) - - if route_method == request.method or route_method == hdrs.METH_ANY: - return (UrlMappingMatchInfo(match_dict, route_obj), allowed_methods) - else: - return None, allowed_methods - - @abc.abstractmethod - def _match(self, path: str) -> Optional[Dict[str, str]]: - pass # pragma: no cover - - def __len__(self) -> int: - return len(self._routes) - - def __iter__(self) -> Iterator[AbstractRoute]: - return iter(self._routes) - - # TODO: implement all abstract methods - - -class PlainResource(Resource): - def __init__(self, path: str, *, name: Optional[str] = None) -> None: - super().__init__(name=name) - assert not path or path.startswith("/") - self._path = path - - @property - def canonical(self) -> str: - return self._path - - def freeze(self) -> None: - if not self._path: - self._path = "/" - - def add_prefix(self, prefix: str) -> None: - assert prefix.startswith("/") - assert not prefix.endswith("/") - assert len(prefix) > 1 - self._path = prefix + self._path - - def _match(self, path: str) -> Optional[Dict[str, str]]: - # string comparison is about 10 times faster than regexp matching - if self._path == path: - return {} - else: - return None - - def raw_match(self, path: str) -> bool: - return self._path == path - - def get_info(self) -> _InfoDict: - return {"path": self._path} - - def url_for(self) -> URL: # type: ignore[override] - return URL.build(path=self._path, encoded=True) - - def __repr__(self) -> str: - name = "'" + self.name + "' " if self.name is not None else "" - return f"" - - -class DynamicResource(Resource): - - DYN = re.compile(r"\{(?P[_a-zA-Z][_a-zA-Z0-9]*)\}") - DYN_WITH_RE = re.compile(r"\{(?P[_a-zA-Z][_a-zA-Z0-9]*):(?P.+)\}") - GOOD = r"[^{}/]+" - - def __init__(self, path: str, *, name: Optional[str] = None) -> None: - super().__init__(name=name) - pattern = "" - formatter = "" - for part in ROUTE_RE.split(path): - match = self.DYN.fullmatch(part) - if match: - pattern += "(?P<{}>{})".format(match.group("var"), self.GOOD) - formatter += "{" + match.group("var") + "}" - continue - - match = self.DYN_WITH_RE.fullmatch(part) - if match: - pattern += "(?P<{var}>{re})".format(**match.groupdict()) - formatter += "{" + match.group("var") + "}" - continue - - if "{" in part or "}" in part: - raise ValueError(f"Invalid path '{path}'['{part}']") - - part = _requote_path(part) - formatter += part - pattern += re.escape(part) - - try: - compiled = re.compile(pattern) - except re.error as exc: - raise ValueError(f"Bad pattern '{pattern}': {exc}") from None - assert compiled.pattern.startswith(PATH_SEP) - assert formatter.startswith("/") - self._pattern = compiled - self._formatter = formatter - - @property - def canonical(self) -> str: - return self._formatter - - def add_prefix(self, prefix: str) -> None: - assert prefix.startswith("/") - assert not prefix.endswith("/") - assert len(prefix) > 1 - self._pattern = re.compile(re.escape(prefix) + self._pattern.pattern) - self._formatter = prefix + self._formatter - - def _match(self, path: str) -> Optional[Dict[str, str]]: - match = self._pattern.fullmatch(path) - if match is None: - return None - else: - return { - key: _unquote_path(value) for key, value in match.groupdict().items() - } - - def raw_match(self, path: str) -> bool: - return self._formatter == path - - def get_info(self) -> _InfoDict: - return {"formatter": self._formatter, "pattern": self._pattern} - - def url_for(self, **parts: str) -> URL: - url = self._formatter.format_map({k: _quote_path(v) for k, v in parts.items()}) - return URL.build(path=url, encoded=True) - - def __repr__(self) -> str: - name = "'" + self.name + "' " if self.name is not None else "" - return "".format( - name=name, formatter=self._formatter - ) - - -class PrefixResource(AbstractResource): - def __init__(self, prefix: str, *, name: Optional[str] = None) -> None: - assert not prefix or prefix.startswith("/"), prefix - assert prefix in ("", "/") or not prefix.endswith("/"), prefix - super().__init__(name=name) - self._prefix = _requote_path(prefix) - self._prefix2 = self._prefix + "/" - - @property - def canonical(self) -> str: - return self._prefix - - def add_prefix(self, prefix: str) -> None: - assert prefix.startswith("/") - assert not prefix.endswith("/") - assert len(prefix) > 1 - self._prefix = prefix + self._prefix - self._prefix2 = self._prefix + "/" - - def raw_match(self, prefix: str) -> bool: - return False - - # TODO: impl missing abstract methods - - -class StaticResource(PrefixResource): - VERSION_KEY = "v" - - def __init__( - self, - prefix: str, - directory: PathLike, - *, - name: Optional[str] = None, - expect_handler: Optional[_ExpectHandler] = None, - chunk_size: int = 256 * 1024, - show_index: bool = False, - follow_symlinks: bool = False, - append_version: bool = False, - ) -> None: - super().__init__(prefix, name=name) - try: - directory = Path(directory) - if str(directory).startswith("~"): - directory = Path(os.path.expanduser(str(directory))) - directory = directory.resolve() - if not directory.is_dir(): - raise ValueError("Not a directory") - except (FileNotFoundError, ValueError) as error: - raise ValueError(f"No directory exists at '{directory}'") from error - self._directory = directory - self._show_index = show_index - self._chunk_size = chunk_size - self._follow_symlinks = follow_symlinks - self._expect_handler = expect_handler - self._append_version = append_version - - self._routes = { - "GET": ResourceRoute( - "GET", self._handle, self, expect_handler=expect_handler - ), - "HEAD": ResourceRoute( - "HEAD", self._handle, self, expect_handler=expect_handler - ), - } - - def url_for( # type: ignore[override] - self, - *, - filename: Union[str, Path], - append_version: Optional[bool] = None, - ) -> URL: - if append_version is None: - append_version = self._append_version - if isinstance(filename, Path): - filename = str(filename) - filename = filename.lstrip("/") - - url = URL.build(path=self._prefix, encoded=True) - # filename is not encoded - if YARL_VERSION < (1, 6): - url = url / filename.replace("%", "%25") - else: - url = url / filename - - if append_version: - try: - filepath = self._directory.joinpath(filename).resolve() - if not self._follow_symlinks: - filepath.relative_to(self._directory) - except (ValueError, FileNotFoundError): - # ValueError for case when path point to symlink - # with follow_symlinks is False - return url # relatively safe - if filepath.is_file(): - # TODO cache file content - # with file watcher for cache invalidation - with filepath.open("rb") as f: - file_bytes = f.read() - h = self._get_file_hash(file_bytes) - url = url.with_query({self.VERSION_KEY: h}) - return url - return url - - @staticmethod - def _get_file_hash(byte_array: bytes) -> str: - m = hashlib.sha256() # todo sha256 can be configurable param - m.update(byte_array) - b64 = base64.urlsafe_b64encode(m.digest()) - return b64.decode("ascii") - - def get_info(self) -> _InfoDict: - return { - "directory": self._directory, - "prefix": self._prefix, - "routes": self._routes, - } - - def set_options_route(self, handler: Handler) -> None: - if "OPTIONS" in self._routes: - raise RuntimeError("OPTIONS route was set already") - self._routes["OPTIONS"] = ResourceRoute( - "OPTIONS", handler, self, expect_handler=self._expect_handler - ) - - async def resolve(self, request: Request) -> _Resolve: - path = request.rel_url.raw_path - method = request.method - allowed_methods = set(self._routes) - if not path.startswith(self._prefix2) and path != self._prefix: - return None, set() - - if method not in allowed_methods: - return None, allowed_methods - - match_dict = {"filename": _unquote_path(path[len(self._prefix) + 1 :])} - return (UrlMappingMatchInfo(match_dict, self._routes[method]), allowed_methods) - - def __len__(self) -> int: - return len(self._routes) - - def __iter__(self) -> Iterator[AbstractRoute]: - return iter(self._routes.values()) - - async def _handle(self, request: Request) -> StreamResponse: - rel_url = request.match_info["filename"] - try: - filename = Path(rel_url) - if filename.anchor: - # rel_url is an absolute name like - # /static/\\machine_name\c$ or /static/D:\path - # where the static dir is totally different - raise HTTPForbidden() - filepath = self._directory.joinpath(filename).resolve() - if not self._follow_symlinks: - filepath.relative_to(self._directory) - except (ValueError, FileNotFoundError) as error: - # relatively safe - raise HTTPNotFound() from error - except HTTPForbidden: - raise - except Exception as error: - # perm error or other kind! - request.app.logger.exception(error) - raise HTTPNotFound() from error - - # on opening a dir, load its contents if allowed - if filepath.is_dir(): - if self._show_index: - try: - return Response( - text=self._directory_as_html(filepath), content_type="text/html" - ) - except PermissionError: - raise HTTPForbidden() - else: - raise HTTPForbidden() - elif filepath.is_file(): - return FileResponse(filepath, chunk_size=self._chunk_size) - else: - raise HTTPNotFound - - def _directory_as_html(self, filepath: Path) -> str: - # returns directory's index as html - - # sanity check - assert filepath.is_dir() - - relative_path_to_dir = filepath.relative_to(self._directory).as_posix() - index_of = f"Index of /{relative_path_to_dir}" - h1 = f"

{index_of}

" - - index_list = [] - dir_index = filepath.iterdir() - for _file in sorted(dir_index): - # show file url as relative to static path - rel_path = _file.relative_to(self._directory).as_posix() - file_url = self._prefix + "/" + rel_path - - # if file is a directory, add '/' to the end of the name - if _file.is_dir(): - file_name = f"{_file.name}/" - else: - file_name = _file.name - - index_list.append( - '
  • {name}
  • '.format( - url=file_url, name=file_name - ) - ) - ul = "
      \n{}\n
    ".format("\n".join(index_list)) - body = f"\n{h1}\n{ul}\n" - - head_str = f"\n{index_of}\n" - html = f"\n{head_str}\n{body}\n" - - return html - - def __repr__(self) -> str: - name = "'" + self.name + "'" if self.name is not None else "" - return " {directory!r}>".format( - name=name, path=self._prefix, directory=self._directory - ) - - -class PrefixedSubAppResource(PrefixResource): - def __init__(self, prefix: str, app: "Application") -> None: - super().__init__(prefix) - self._app = app - for resource in app.router.resources(): - resource.add_prefix(prefix) - - def add_prefix(self, prefix: str) -> None: - super().add_prefix(prefix) - for resource in self._app.router.resources(): - resource.add_prefix(prefix) - - def url_for(self, *args: str, **kwargs: str) -> URL: - raise RuntimeError(".url_for() is not supported " "by sub-application root") - - def get_info(self) -> _InfoDict: - return {"app": self._app, "prefix": self._prefix} - - async def resolve(self, request: Request) -> _Resolve: - if ( - not request.url.raw_path.startswith(self._prefix2) - and request.url.raw_path != self._prefix - ): - return None, set() - match_info = await self._app.router.resolve(request) - match_info.add_app(self._app) - if isinstance(match_info.http_exception, HTTPMethodNotAllowed): - methods = match_info.http_exception.allowed_methods - else: - methods = set() - return match_info, methods - - def __len__(self) -> int: - return len(self._app.router.routes()) - - def __iter__(self) -> Iterator[AbstractRoute]: - return iter(self._app.router.routes()) - - def __repr__(self) -> str: - return " {app!r}>".format( - prefix=self._prefix, app=self._app - ) - - -class AbstractRuleMatching(abc.ABC): - @abc.abstractmethod # pragma: no branch - async def match(self, request: Request) -> bool: - """Return bool if the request satisfies the criteria""" - - @abc.abstractmethod # pragma: no branch - def get_info(self) -> _InfoDict: - """Return a dict with additional info useful for introspection""" - - @property - @abc.abstractmethod # pragma: no branch - def canonical(self) -> str: - """Return a str""" - - -class Domain(AbstractRuleMatching): - re_part = re.compile(r"(?!-)[a-z\d-]{1,63}(? None: - super().__init__() - self._domain = self.validation(domain) - - @property - def canonical(self) -> str: - return self._domain - - def validation(self, domain: str) -> str: - if not isinstance(domain, str): - raise TypeError("Domain must be str") - domain = domain.rstrip(".").lower() - if not domain: - raise ValueError("Domain cannot be empty") - elif "://" in domain: - raise ValueError("Scheme not supported") - url = URL("http://" + domain) - assert url.raw_host is not None - if not all(self.re_part.fullmatch(x) for x in url.raw_host.split(".")): - raise ValueError("Domain not valid") - if url.port == 80: - return url.raw_host - return f"{url.raw_host}:{url.port}" - - async def match(self, request: Request) -> bool: - host = request.headers.get(hdrs.HOST) - if not host: - return False - return self.match_domain(host) - - def match_domain(self, host: str) -> bool: - return host.lower() == self._domain - - def get_info(self) -> _InfoDict: - return {"domain": self._domain} - - -class MaskDomain(Domain): - re_part = re.compile(r"(?!-)[a-z\d\*-]{1,63}(? None: - super().__init__(domain) - mask = self._domain.replace(".", r"\.").replace("*", ".*") - self._mask = re.compile(mask) - - @property - def canonical(self) -> str: - return self._mask.pattern - - def match_domain(self, host: str) -> bool: - return self._mask.fullmatch(host) is not None - - -class MatchedSubAppResource(PrefixedSubAppResource): - def __init__(self, rule: AbstractRuleMatching, app: "Application") -> None: - AbstractResource.__init__(self) - self._prefix = "" - self._app = app - self._rule = rule - - @property - def canonical(self) -> str: - return self._rule.canonical - - def get_info(self) -> _InfoDict: - return {"app": self._app, "rule": self._rule} - - async def resolve(self, request: Request) -> _Resolve: - if not await self._rule.match(request): - return None, set() - match_info = await self._app.router.resolve(request) - match_info.add_app(self._app) - if isinstance(match_info.http_exception, HTTPMethodNotAllowed): - methods = match_info.http_exception.allowed_methods - else: - methods = set() - return match_info, methods - - def __repr__(self) -> str: - return " {app!r}>" "".format(app=self._app) - - -class ResourceRoute(AbstractRoute): - """A route with resource""" - - def __init__( - self, - method: str, - handler: Union[Handler, Type[AbstractView]], - resource: AbstractResource, - *, - expect_handler: Optional[_ExpectHandler] = None, - ) -> None: - super().__init__( - method, handler, expect_handler=expect_handler, resource=resource - ) - - def __repr__(self) -> str: - return " {handler!r}".format( - method=self.method, resource=self._resource, handler=self.handler - ) - - @property - def name(self) -> Optional[str]: - if self._resource is None: - return None - return self._resource.name - - def url_for(self, *args: str, **kwargs: str) -> URL: - """Construct url for route with additional params.""" - assert self._resource is not None - return self._resource.url_for(*args, **kwargs) - - def get_info(self) -> _InfoDict: - assert self._resource is not None - return self._resource.get_info() - - -class SystemRoute(AbstractRoute): - def __init__(self, http_exception: HTTPException) -> None: - super().__init__(hdrs.METH_ANY, self._handle) - self._http_exception = http_exception - - def url_for(self, *args: str, **kwargs: str) -> URL: - raise RuntimeError(".url_for() is not allowed for SystemRoute") - - @property - def name(self) -> Optional[str]: - return None - - def get_info(self) -> _InfoDict: - return {"http_exception": self._http_exception} - - async def _handle(self, request: Request) -> StreamResponse: - raise self._http_exception - - @property - def status(self) -> int: - return self._http_exception.status - - @property - def reason(self) -> str: - return self._http_exception.reason - - def __repr__(self) -> str: - return "".format(self=self) - - -class View(AbstractView): - async def _iter(self) -> StreamResponse: - if self.request.method not in hdrs.METH_ALL: - self._raise_allowed_methods() - method: Callable[[], Awaitable[StreamResponse]] = getattr( - self, self.request.method.lower(), None - ) - if method is None: - self._raise_allowed_methods() - resp = await method() - return resp - - def __await__(self) -> Generator[Any, None, StreamResponse]: - return self._iter().__await__() - - def _raise_allowed_methods(self) -> None: - allowed_methods = {m for m in hdrs.METH_ALL if hasattr(self, m.lower())} - raise HTTPMethodNotAllowed(self.request.method, allowed_methods) - - -class ResourcesView(Sized, Iterable[AbstractResource], Container[AbstractResource]): - def __init__(self, resources: List[AbstractResource]) -> None: - self._resources = resources - - def __len__(self) -> int: - return len(self._resources) - - def __iter__(self) -> Iterator[AbstractResource]: - yield from self._resources - - def __contains__(self, resource: object) -> bool: - return resource in self._resources - - -class RoutesView(Sized, Iterable[AbstractRoute], Container[AbstractRoute]): - def __init__(self, resources: List[AbstractResource]): - self._routes = [] # type: List[AbstractRoute] - for resource in resources: - for route in resource: - self._routes.append(route) - - def __len__(self) -> int: - return len(self._routes) - - def __iter__(self) -> Iterator[AbstractRoute]: - yield from self._routes - - def __contains__(self, route: object) -> bool: - return route in self._routes - - -class UrlDispatcher(AbstractRouter, Mapping[str, AbstractResource]): - - NAME_SPLIT_RE = re.compile(r"[.:-]") - - def __init__(self) -> None: - super().__init__() - self._resources = [] # type: List[AbstractResource] - self._named_resources = {} # type: Dict[str, AbstractResource] - - async def resolve(self, request: Request) -> UrlMappingMatchInfo: - method = request.method - allowed_methods = set() # type: Set[str] - - for resource in self._resources: - match_dict, allowed = await resource.resolve(request) - if match_dict is not None: - return match_dict - else: - allowed_methods |= allowed - - if allowed_methods: - return MatchInfoError(HTTPMethodNotAllowed(method, allowed_methods)) - else: - return MatchInfoError(HTTPNotFound()) - - def __iter__(self) -> Iterator[str]: - return iter(self._named_resources) - - def __len__(self) -> int: - return len(self._named_resources) - - def __contains__(self, resource: object) -> bool: - return resource in self._named_resources - - def __getitem__(self, name: str) -> AbstractResource: - return self._named_resources[name] - - def resources(self) -> ResourcesView: - return ResourcesView(self._resources) - - def routes(self) -> RoutesView: - return RoutesView(self._resources) - - def named_resources(self) -> Mapping[str, AbstractResource]: - return MappingProxyType(self._named_resources) - - def register_resource(self, resource: AbstractResource) -> None: - assert isinstance( - resource, AbstractResource - ), f"Instance of AbstractResource class is required, got {resource!r}" - if self.frozen: - raise RuntimeError("Cannot register a resource into frozen router.") - - name = resource.name - - if name is not None: - parts = self.NAME_SPLIT_RE.split(name) - for part in parts: - if keyword.iskeyword(part): - raise ValueError( - f"Incorrect route name {name!r}, " - "python keywords cannot be used " - "for route name" - ) - if not part.isidentifier(): - raise ValueError( - "Incorrect route name {!r}, " - "the name should be a sequence of " - "python identifiers separated " - "by dash, dot or column".format(name) - ) - if name in self._named_resources: - raise ValueError( - "Duplicate {!r}, " - "already handled by {!r}".format(name, self._named_resources[name]) - ) - self._named_resources[name] = resource - self._resources.append(resource) - - def add_resource(self, path: str, *, name: Optional[str] = None) -> Resource: - if path and not path.startswith("/"): - raise ValueError("path should be started with / or be empty") - # Reuse last added resource if path and name are the same - if self._resources: - resource = self._resources[-1] - if resource.name == name and resource.raw_match(path): - return cast(Resource, resource) - if not ("{" in path or "}" in path or ROUTE_RE.search(path)): - resource = PlainResource(_requote_path(path), name=name) - self.register_resource(resource) - return resource - resource = DynamicResource(path, name=name) - self.register_resource(resource) - return resource - - def add_route( - self, - method: str, - path: str, - handler: Union[Handler, Type[AbstractView]], - *, - name: Optional[str] = None, - expect_handler: Optional[_ExpectHandler] = None, - ) -> AbstractRoute: - resource = self.add_resource(path, name=name) - return resource.add_route(method, handler, expect_handler=expect_handler) - - def add_static( - self, - prefix: str, - path: PathLike, - *, - name: Optional[str] = None, - expect_handler: Optional[_ExpectHandler] = None, - chunk_size: int = 256 * 1024, - show_index: bool = False, - follow_symlinks: bool = False, - append_version: bool = False, - ) -> AbstractResource: - """Add static files view. - - prefix - url prefix - path - folder with files - - """ - assert prefix.startswith("/") - if prefix.endswith("/"): - prefix = prefix[:-1] - resource = StaticResource( - prefix, - path, - name=name, - expect_handler=expect_handler, - chunk_size=chunk_size, - show_index=show_index, - follow_symlinks=follow_symlinks, - append_version=append_version, - ) - self.register_resource(resource) - return resource - - def add_head(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute: - """Shortcut for add_route with method HEAD.""" - return self.add_route(hdrs.METH_HEAD, path, handler, **kwargs) - - def add_options(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute: - """Shortcut for add_route with method OPTIONS.""" - return self.add_route(hdrs.METH_OPTIONS, path, handler, **kwargs) - - def add_get( - self, - path: str, - handler: Handler, - *, - name: Optional[str] = None, - allow_head: bool = True, - **kwargs: Any, - ) -> AbstractRoute: - """Shortcut for add_route with method GET. - - If allow_head is true, another - route is added allowing head requests to the same endpoint. - """ - resource = self.add_resource(path, name=name) - if allow_head: - resource.add_route(hdrs.METH_HEAD, handler, **kwargs) - return resource.add_route(hdrs.METH_GET, handler, **kwargs) - - def add_post(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute: - """Shortcut for add_route with method POST.""" - return self.add_route(hdrs.METH_POST, path, handler, **kwargs) - - def add_put(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute: - """Shortcut for add_route with method PUT.""" - return self.add_route(hdrs.METH_PUT, path, handler, **kwargs) - - def add_patch(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute: - """Shortcut for add_route with method PATCH.""" - return self.add_route(hdrs.METH_PATCH, path, handler, **kwargs) - - def add_delete(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute: - """Shortcut for add_route with method DELETE.""" - return self.add_route(hdrs.METH_DELETE, path, handler, **kwargs) - - def add_view( - self, path: str, handler: Type[AbstractView], **kwargs: Any - ) -> AbstractRoute: - """Shortcut for add_route with ANY methods for a class-based view.""" - return self.add_route(hdrs.METH_ANY, path, handler, **kwargs) - - def freeze(self) -> None: - super().freeze() - for resource in self._resources: - resource.freeze() - - def add_routes(self, routes: Iterable[AbstractRouteDef]) -> List[AbstractRoute]: - """Append routes to route table. - - Parameter should be a sequence of RouteDef objects. - - Returns a list of registered AbstractRoute instances. - """ - registered_routes = [] - for route_def in routes: - registered_routes.extend(route_def.register(self)) - return registered_routes - - -def _quote_path(value: str) -> str: - if YARL_VERSION < (1, 6): - value = value.replace("%", "%25") - return URL.build(path=value, encoded=False).raw_path - - -def _unquote_path(value: str) -> str: - return URL.build(path=value, encoded=True).path - - -def _requote_path(value: str) -> str: - # Quote non-ascii characters and other characters which must be quoted, - # but preserve existing %-sequences. - result = _quote_path(value) - if "%" in value: - result = result.replace("%25", "%") - return result diff --git a/.venv/Lib/site-packages/aiohttp/web_ws.py b/.venv/Lib/site-packages/aiohttp/web_ws.py deleted file mode 100644 index 16b0a17..0000000 --- a/.venv/Lib/site-packages/aiohttp/web_ws.py +++ /dev/null @@ -1,487 +0,0 @@ -import asyncio -import base64 -import binascii -import hashlib -import json -from typing import Any, Iterable, Optional, Tuple, cast - -import async_timeout -import attr -from multidict import CIMultiDict - -from . import hdrs -from .abc import AbstractStreamWriter -from .helpers import call_later, set_result -from .http import ( - WS_CLOSED_MESSAGE, - WS_CLOSING_MESSAGE, - WS_KEY, - WebSocketError, - WebSocketReader, - WebSocketWriter, - WSCloseCode, - WSMessage, - WSMsgType as WSMsgType, - ws_ext_gen, - ws_ext_parse, -) -from .log import ws_logger -from .streams import EofStream, FlowControlDataQueue -from .typedefs import Final, JSONDecoder, JSONEncoder -from .web_exceptions import HTTPBadRequest, HTTPException -from .web_request import BaseRequest -from .web_response import StreamResponse - -__all__ = ( - "WebSocketResponse", - "WebSocketReady", - "WSMsgType", -) - -THRESHOLD_CONNLOST_ACCESS: Final[int] = 5 - - -@attr.s(auto_attribs=True, frozen=True, slots=True) -class WebSocketReady: - ok: bool - protocol: Optional[str] - - def __bool__(self) -> bool: - return self.ok - - -class WebSocketResponse(StreamResponse): - - _length_check = False - - def __init__( - self, - *, - timeout: float = 10.0, - receive_timeout: Optional[float] = None, - autoclose: bool = True, - autoping: bool = True, - heartbeat: Optional[float] = None, - protocols: Iterable[str] = (), - compress: bool = True, - max_msg_size: int = 4 * 1024 * 1024, - ) -> None: - super().__init__(status=101) - self._protocols = protocols - self._ws_protocol = None # type: Optional[str] - self._writer = None # type: Optional[WebSocketWriter] - self._reader = None # type: Optional[FlowControlDataQueue[WSMessage]] - self._closed = False - self._closing = False - self._conn_lost = 0 - self._close_code = None # type: Optional[int] - self._loop = None # type: Optional[asyncio.AbstractEventLoop] - self._waiting = None # type: Optional[asyncio.Future[bool]] - self._exception = None # type: Optional[BaseException] - self._timeout = timeout - self._receive_timeout = receive_timeout - self._autoclose = autoclose - self._autoping = autoping - self._heartbeat = heartbeat - self._heartbeat_cb: Optional[asyncio.TimerHandle] = None - if heartbeat is not None: - self._pong_heartbeat = heartbeat / 2.0 - self._pong_response_cb: Optional[asyncio.TimerHandle] = None - self._compress = compress - self._max_msg_size = max_msg_size - - def _cancel_heartbeat(self) -> None: - if self._pong_response_cb is not None: - self._pong_response_cb.cancel() - self._pong_response_cb = None - - if self._heartbeat_cb is not None: - self._heartbeat_cb.cancel() - self._heartbeat_cb = None - - def _reset_heartbeat(self) -> None: - self._cancel_heartbeat() - - if self._heartbeat is not None: - assert self._loop is not None - self._heartbeat_cb = call_later( - self._send_heartbeat, self._heartbeat, self._loop - ) - - def _send_heartbeat(self) -> None: - if self._heartbeat is not None and not self._closed: - assert self._loop is not None - # fire-and-forget a task is not perfect but maybe ok for - # sending ping. Otherwise we need a long-living heartbeat - # task in the class. - self._loop.create_task(self._writer.ping()) # type: ignore[union-attr] - - if self._pong_response_cb is not None: - self._pong_response_cb.cancel() - self._pong_response_cb = call_later( - self._pong_not_received, self._pong_heartbeat, self._loop - ) - - def _pong_not_received(self) -> None: - if self._req is not None and self._req.transport is not None: - self._closed = True - self._close_code = WSCloseCode.ABNORMAL_CLOSURE - self._exception = asyncio.TimeoutError() - self._req.transport.close() - - async def prepare(self, request: BaseRequest) -> AbstractStreamWriter: - # make pre-check to don't hide it by do_handshake() exceptions - if self._payload_writer is not None: - return self._payload_writer - - protocol, writer = self._pre_start(request) - payload_writer = await super().prepare(request) - assert payload_writer is not None - self._post_start(request, protocol, writer) - await payload_writer.drain() - return payload_writer - - def _handshake( - self, request: BaseRequest - ) -> Tuple["CIMultiDict[str]", str, bool, bool]: - headers = request.headers - if "websocket" != headers.get(hdrs.UPGRADE, "").lower().strip(): - raise HTTPBadRequest( - text=( - "No WebSocket UPGRADE hdr: {}\n Can " - '"Upgrade" only to "WebSocket".' - ).format(headers.get(hdrs.UPGRADE)) - ) - - if "upgrade" not in headers.get(hdrs.CONNECTION, "").lower(): - raise HTTPBadRequest( - text="No CONNECTION upgrade hdr: {}".format( - headers.get(hdrs.CONNECTION) - ) - ) - - # find common sub-protocol between client and server - protocol = None - if hdrs.SEC_WEBSOCKET_PROTOCOL in headers: - req_protocols = [ - str(proto.strip()) - for proto in headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(",") - ] - - for proto in req_protocols: - if proto in self._protocols: - protocol = proto - break - else: - # No overlap found: Return no protocol as per spec - ws_logger.warning( - "Client protocols %r don’t overlap server-known ones %r", - req_protocols, - self._protocols, - ) - - # check supported version - version = headers.get(hdrs.SEC_WEBSOCKET_VERSION, "") - if version not in ("13", "8", "7"): - raise HTTPBadRequest(text=f"Unsupported version: {version}") - - # check client handshake for validity - key = headers.get(hdrs.SEC_WEBSOCKET_KEY) - try: - if not key or len(base64.b64decode(key)) != 16: - raise HTTPBadRequest(text=f"Handshake error: {key!r}") - except binascii.Error: - raise HTTPBadRequest(text=f"Handshake error: {key!r}") from None - - accept_val = base64.b64encode( - hashlib.sha1(key.encode() + WS_KEY).digest() - ).decode() - response_headers = CIMultiDict( # type: ignore[var-annotated] - { - hdrs.UPGRADE: "websocket", # type: ignore[arg-type] - hdrs.CONNECTION: "upgrade", - hdrs.SEC_WEBSOCKET_ACCEPT: accept_val, - } - ) - - notakeover = False - compress = 0 - if self._compress: - extensions = headers.get(hdrs.SEC_WEBSOCKET_EXTENSIONS) - # Server side always get return with no exception. - # If something happened, just drop compress extension - compress, notakeover = ws_ext_parse(extensions, isserver=True) - if compress: - enabledext = ws_ext_gen( - compress=compress, isserver=True, server_notakeover=notakeover - ) - response_headers[hdrs.SEC_WEBSOCKET_EXTENSIONS] = enabledext - - if protocol: - response_headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = protocol - return ( - response_headers, - protocol, - compress, - notakeover, - ) # type: ignore[return-value] - - def _pre_start(self, request: BaseRequest) -> Tuple[str, WebSocketWriter]: - self._loop = request._loop - - headers, protocol, compress, notakeover = self._handshake(request) - - self.set_status(101) - self.headers.update(headers) - self.force_close() - self._compress = compress - transport = request._protocol.transport - assert transport is not None - writer = WebSocketWriter( - request._protocol, transport, compress=compress, notakeover=notakeover - ) - - return protocol, writer - - def _post_start( - self, request: BaseRequest, protocol: str, writer: WebSocketWriter - ) -> None: - self._ws_protocol = protocol - self._writer = writer - - self._reset_heartbeat() - - loop = self._loop - assert loop is not None - self._reader = FlowControlDataQueue(request._protocol, 2 ** 16, loop=loop) - request.protocol.set_parser( - WebSocketReader(self._reader, self._max_msg_size, compress=self._compress) - ) - # disable HTTP keepalive for WebSocket - request.protocol.keep_alive(False) - - def can_prepare(self, request: BaseRequest) -> WebSocketReady: - if self._writer is not None: - raise RuntimeError("Already started") - try: - _, protocol, _, _ = self._handshake(request) - except HTTPException: - return WebSocketReady(False, None) - else: - return WebSocketReady(True, protocol) - - @property - def closed(self) -> bool: - return self._closed - - @property - def close_code(self) -> Optional[int]: - return self._close_code - - @property - def ws_protocol(self) -> Optional[str]: - return self._ws_protocol - - @property - def compress(self) -> bool: - return self._compress - - def exception(self) -> Optional[BaseException]: - return self._exception - - async def ping(self, message: bytes = b"") -> None: - if self._writer is None: - raise RuntimeError("Call .prepare() first") - await self._writer.ping(message) - - async def pong(self, message: bytes = b"") -> None: - # unsolicited pong - if self._writer is None: - raise RuntimeError("Call .prepare() first") - await self._writer.pong(message) - - async def send_str(self, data: str, compress: Optional[bool] = None) -> None: - if self._writer is None: - raise RuntimeError("Call .prepare() first") - if not isinstance(data, str): - raise TypeError("data argument must be str (%r)" % type(data)) - await self._writer.send(data, binary=False, compress=compress) - - async def send_bytes(self, data: bytes, compress: Optional[bool] = None) -> None: - if self._writer is None: - raise RuntimeError("Call .prepare() first") - if not isinstance(data, (bytes, bytearray, memoryview)): - raise TypeError("data argument must be byte-ish (%r)" % type(data)) - await self._writer.send(data, binary=True, compress=compress) - - async def send_json( - self, - data: Any, - compress: Optional[bool] = None, - *, - dumps: JSONEncoder = json.dumps, - ) -> None: - await self.send_str(dumps(data), compress=compress) - - async def write_eof(self) -> None: # type: ignore[override] - if self._eof_sent: - return - if self._payload_writer is None: - raise RuntimeError("Response has not been started") - - await self.close() - self._eof_sent = True - - async def close(self, *, code: int = WSCloseCode.OK, message: bytes = b"") -> bool: - if self._writer is None: - raise RuntimeError("Call .prepare() first") - - self._cancel_heartbeat() - reader = self._reader - assert reader is not None - - # we need to break `receive()` cycle first, - # `close()` may be called from different task - if self._waiting is not None and not self._closed: - reader.feed_data(WS_CLOSING_MESSAGE, 0) - await self._waiting - - if not self._closed: - self._closed = True - try: - await self._writer.close(code, message) - writer = self._payload_writer - assert writer is not None - await writer.drain() - except (asyncio.CancelledError, asyncio.TimeoutError): - self._close_code = WSCloseCode.ABNORMAL_CLOSURE - raise - except Exception as exc: - self._close_code = WSCloseCode.ABNORMAL_CLOSURE - self._exception = exc - return True - - if self._closing: - return True - - reader = self._reader - assert reader is not None - try: - async with async_timeout.timeout(self._timeout): - msg = await reader.read() - except asyncio.CancelledError: - self._close_code = WSCloseCode.ABNORMAL_CLOSURE - raise - except Exception as exc: - self._close_code = WSCloseCode.ABNORMAL_CLOSURE - self._exception = exc - return True - - if msg.type == WSMsgType.CLOSE: - self._close_code = msg.data - return True - - self._close_code = WSCloseCode.ABNORMAL_CLOSURE - self._exception = asyncio.TimeoutError() - return True - else: - return False - - async def receive(self, timeout: Optional[float] = None) -> WSMessage: - if self._reader is None: - raise RuntimeError("Call .prepare() first") - - loop = self._loop - assert loop is not None - while True: - if self._waiting is not None: - raise RuntimeError("Concurrent call to receive() is not allowed") - - if self._closed: - self._conn_lost += 1 - if self._conn_lost >= THRESHOLD_CONNLOST_ACCESS: - raise RuntimeError("WebSocket connection is closed.") - return WS_CLOSED_MESSAGE - elif self._closing: - return WS_CLOSING_MESSAGE - - try: - self._waiting = loop.create_future() - try: - async with async_timeout.timeout(timeout or self._receive_timeout): - msg = await self._reader.read() - self._reset_heartbeat() - finally: - waiter = self._waiting - set_result(waiter, True) - self._waiting = None - except (asyncio.CancelledError, asyncio.TimeoutError): - self._close_code = WSCloseCode.ABNORMAL_CLOSURE - raise - except EofStream: - self._close_code = WSCloseCode.OK - await self.close() - return WSMessage(WSMsgType.CLOSED, None, None) - except WebSocketError as exc: - self._close_code = exc.code - await self.close(code=exc.code) - return WSMessage(WSMsgType.ERROR, exc, None) - except Exception as exc: - self._exception = exc - self._closing = True - self._close_code = WSCloseCode.ABNORMAL_CLOSURE - await self.close() - return WSMessage(WSMsgType.ERROR, exc, None) - - if msg.type == WSMsgType.CLOSE: - self._closing = True - self._close_code = msg.data - if not self._closed and self._autoclose: - await self.close() - elif msg.type == WSMsgType.CLOSING: - self._closing = True - elif msg.type == WSMsgType.PING and self._autoping: - await self.pong(msg.data) - continue - elif msg.type == WSMsgType.PONG and self._autoping: - continue - - return msg - - async def receive_str(self, *, timeout: Optional[float] = None) -> str: - msg = await self.receive(timeout) - if msg.type != WSMsgType.TEXT: - raise TypeError( - "Received message {}:{!r} is not WSMsgType.TEXT".format( - msg.type, msg.data - ) - ) - return cast(str, msg.data) - - async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes: - msg = await self.receive(timeout) - if msg.type != WSMsgType.BINARY: - raise TypeError(f"Received message {msg.type}:{msg.data!r} is not bytes") - return cast(bytes, msg.data) - - async def receive_json( - self, *, loads: JSONDecoder = json.loads, timeout: Optional[float] = None - ) -> Any: - data = await self.receive_str(timeout=timeout) - return loads(data) - - async def write(self, data: bytes) -> None: - raise RuntimeError("Cannot call .write() for websocket") - - def __aiter__(self) -> "WebSocketResponse": - return self - - async def __anext__(self) -> WSMessage: - msg = await self.receive() - if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED): - raise StopAsyncIteration - return msg - - def _cancel(self, exc: BaseException) -> None: - if self._reader is not None: - self._reader.set_exception(exc) diff --git a/.venv/Lib/site-packages/aiohttp/worker.py b/.venv/Lib/site-packages/aiohttp/worker.py deleted file mode 100644 index 08945bc..0000000 --- a/.venv/Lib/site-packages/aiohttp/worker.py +++ /dev/null @@ -1,269 +0,0 @@ -"""Async gunicorn worker for aiohttp.web""" - -import asyncio -import os -import re -import signal -import sys -from types import FrameType -from typing import Any, Awaitable, Callable, Optional, Union # noqa - -from gunicorn.config import AccessLogFormat as GunicornAccessLogFormat -from gunicorn.workers import base - -from aiohttp import web - -from .helpers import set_result -from .web_app import Application -from .web_log import AccessLogger - -try: - import ssl - - SSLContext = ssl.SSLContext -except ImportError: # pragma: no cover - ssl = None # type: ignore[assignment] - SSLContext = object # type: ignore[misc,assignment] - - -__all__ = ("GunicornWebWorker", "GunicornUVLoopWebWorker", "GunicornTokioWebWorker") - - -class GunicornWebWorker(base.Worker): # type: ignore[misc,no-any-unimported] - - DEFAULT_AIOHTTP_LOG_FORMAT = AccessLogger.LOG_FORMAT - DEFAULT_GUNICORN_LOG_FORMAT = GunicornAccessLogFormat.default - - def __init__(self, *args: Any, **kw: Any) -> None: # pragma: no cover - super().__init__(*args, **kw) - - self._task = None # type: Optional[asyncio.Task[None]] - self.exit_code = 0 - self._notify_waiter = None # type: Optional[asyncio.Future[bool]] - - def init_process(self) -> None: - # create new event_loop after fork - asyncio.get_event_loop().close() - - self.loop = asyncio.new_event_loop() - asyncio.set_event_loop(self.loop) - - super().init_process() - - def run(self) -> None: - self._task = self.loop.create_task(self._run()) - - try: # ignore all finalization problems - self.loop.run_until_complete(self._task) - except Exception: - self.log.exception("Exception in gunicorn worker") - self.loop.run_until_complete(self.loop.shutdown_asyncgens()) - self.loop.close() - - sys.exit(self.exit_code) - - async def _run(self) -> None: - runner = None - if isinstance(self.wsgi, Application): - app = self.wsgi - elif asyncio.iscoroutinefunction(self.wsgi): - wsgi = await self.wsgi() - if isinstance(wsgi, web.AppRunner): - runner = wsgi - app = runner.app - else: - app = wsgi - else: - raise RuntimeError( - "wsgi app should be either Application or " - "async function returning Application, got {}".format(self.wsgi) - ) - - if runner is None: - access_log = self.log.access_log if self.cfg.accesslog else None - runner = web.AppRunner( - app, - logger=self.log, - keepalive_timeout=self.cfg.keepalive, - access_log=access_log, - access_log_format=self._get_valid_log_format( - self.cfg.access_log_format - ), - ) - await runner.setup() - - ctx = self._create_ssl_context(self.cfg) if self.cfg.is_ssl else None - - runner = runner - assert runner is not None - server = runner.server - assert server is not None - for sock in self.sockets: - site = web.SockSite( - runner, - sock, - ssl_context=ctx, - shutdown_timeout=self.cfg.graceful_timeout / 100 * 95, - ) - await site.start() - - # If our parent changed then we shut down. - pid = os.getpid() - try: - while self.alive: # type: ignore[has-type] - self.notify() - - cnt = server.requests_count - if self.cfg.max_requests and cnt > self.cfg.max_requests: - self.alive = False - self.log.info("Max requests, shutting down: %s", self) - - elif pid == os.getpid() and self.ppid != os.getppid(): - self.alive = False - self.log.info("Parent changed, shutting down: %s", self) - else: - await self._wait_next_notify() - except BaseException: - pass - - await runner.cleanup() - - def _wait_next_notify(self) -> "asyncio.Future[bool]": - self._notify_waiter_done() - - loop = self.loop - assert loop is not None - self._notify_waiter = waiter = loop.create_future() - self.loop.call_later(1.0, self._notify_waiter_done, waiter) - - return waiter - - def _notify_waiter_done( - self, waiter: Optional["asyncio.Future[bool]"] = None - ) -> None: - if waiter is None: - waiter = self._notify_waiter - if waiter is not None: - set_result(waiter, True) - - if waiter is self._notify_waiter: - self._notify_waiter = None - - def init_signals(self) -> None: - # Set up signals through the event loop API. - - self.loop.add_signal_handler( - signal.SIGQUIT, self.handle_quit, signal.SIGQUIT, None - ) - - self.loop.add_signal_handler( - signal.SIGTERM, self.handle_exit, signal.SIGTERM, None - ) - - self.loop.add_signal_handler( - signal.SIGINT, self.handle_quit, signal.SIGINT, None - ) - - self.loop.add_signal_handler( - signal.SIGWINCH, self.handle_winch, signal.SIGWINCH, None - ) - - self.loop.add_signal_handler( - signal.SIGUSR1, self.handle_usr1, signal.SIGUSR1, None - ) - - self.loop.add_signal_handler( - signal.SIGABRT, self.handle_abort, signal.SIGABRT, None - ) - - # Don't let SIGTERM and SIGUSR1 disturb active requests - # by interrupting system calls - signal.siginterrupt(signal.SIGTERM, False) - signal.siginterrupt(signal.SIGUSR1, False) - # Reset signals so Gunicorn doesn't swallow subprocess return codes - # See: https://github.com/aio-libs/aiohttp/issues/6130 - if sys.version_info < (3, 8): - # Starting from Python 3.8, - # the default child watcher is ThreadedChildWatcher. - # The watcher doesn't depend on SIGCHLD signal, - # there is no need to reset it. - signal.signal(signal.SIGCHLD, signal.SIG_DFL) - - def handle_quit(self, sig: int, frame: FrameType) -> None: - self.alive = False - - # worker_int callback - self.cfg.worker_int(self) - - # wakeup closing process - self._notify_waiter_done() - - def handle_abort(self, sig: int, frame: FrameType) -> None: - self.alive = False - self.exit_code = 1 - self.cfg.worker_abort(self) - sys.exit(1) - - @staticmethod - def _create_ssl_context(cfg: Any) -> "SSLContext": - """Creates SSLContext instance for usage in asyncio.create_server. - - See ssl.SSLSocket.__init__ for more details. - """ - if ssl is None: # pragma: no cover - raise RuntimeError("SSL is not supported.") - - ctx = ssl.SSLContext(cfg.ssl_version) - ctx.load_cert_chain(cfg.certfile, cfg.keyfile) - ctx.verify_mode = cfg.cert_reqs - if cfg.ca_certs: - ctx.load_verify_locations(cfg.ca_certs) - if cfg.ciphers: - ctx.set_ciphers(cfg.ciphers) - return ctx - - def _get_valid_log_format(self, source_format: str) -> str: - if source_format == self.DEFAULT_GUNICORN_LOG_FORMAT: - return self.DEFAULT_AIOHTTP_LOG_FORMAT - elif re.search(r"%\([^\)]+\)", source_format): - raise ValueError( - "Gunicorn's style options in form of `%(name)s` are not " - "supported for the log formatting. Please use aiohttp's " - "format specification to configure access log formatting: " - "http://docs.aiohttp.org/en/stable/logging.html" - "#format-specification" - ) - else: - return source_format - - -class GunicornUVLoopWebWorker(GunicornWebWorker): - def init_process(self) -> None: - import uvloop - - # Close any existing event loop before setting a - # new policy. - asyncio.get_event_loop().close() - - # Setup uvloop policy, so that every - # asyncio.get_event_loop() will create an instance - # of uvloop event loop. - asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) - - super().init_process() - - -class GunicornTokioWebWorker(GunicornWebWorker): - def init_process(self) -> None: # pragma: no cover - import tokio - - # Close any existing event loop before setting a - # new policy. - asyncio.get_event_loop().close() - - # Setup tokio policy, so that every - # asyncio.get_event_loop() will create an instance - # of tokio event loop. - asyncio.set_event_loop_policy(tokio.EventLoopPolicy()) - - super().init_process() diff --git a/.venv/Lib/site-packages/aiosignal-1.2.0.dist-info/INSTALLER b/.venv/Lib/site-packages/aiosignal-1.2.0.dist-info/INSTALLER deleted file mode 100644 index a1b589e..0000000 --- a/.venv/Lib/site-packages/aiosignal-1.2.0.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/.venv/Lib/site-packages/aiosignal-1.2.0.dist-info/LICENSE b/.venv/Lib/site-packages/aiosignal-1.2.0.dist-info/LICENSE deleted file mode 100644 index 7082a2d..0000000 --- a/.venv/Lib/site-packages/aiosignal-1.2.0.dist-info/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ -Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2013-2019 Nikolay Kim and Andrew Svetlov - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/.venv/Lib/site-packages/aiosignal-1.2.0.dist-info/METADATA b/.venv/Lib/site-packages/aiosignal-1.2.0.dist-info/METADATA deleted file mode 100644 index aa63d49..0000000 --- a/.venv/Lib/site-packages/aiosignal-1.2.0.dist-info/METADATA +++ /dev/null @@ -1,208 +0,0 @@ -Metadata-Version: 2.1 -Name: aiosignal -Version: 1.2.0 -Summary: aiosignal: a list of registered asynchronous callbacks -Home-page: https://github.com/aio-libs/aiosignal -Author: Nikolay Kim -Author-email: fafhrd91@gmail.com -Maintainer: Martijn Pieters -Maintainer-email: aio-libs@googlegroups.com -License: Apache 2 -Project-URL: Chat: Gitter, https://gitter.im/aio-libs/Lobby -Project-URL: CI: GitHub Actions, https://github.com/aio-libs/aiosignal/actions -Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/aiosignal -Project-URL: Docs: RTD, https://docs.aiosignal.org -Project-URL: GitHub: issues, https://github.com/aio-libs/aiosignal/issues -Project-URL: GitHub: repo, https://github.com/aio-libs/aiosignal -Platform: UNKNOWN -Classifier: License :: OSI Approved :: Apache Software License -Classifier: Intended Audience :: Developers -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: 3.6 -Classifier: Programming Language :: Python :: 3.7 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Development Status :: 5 - Production/Stable -Classifier: Operating System :: POSIX -Classifier: Operating System :: MacOS :: MacOS X -Classifier: Operating System :: Microsoft :: Windows -Classifier: Framework :: AsyncIO -Requires-Python: >=3.6 -Description-Content-Type: text/x-rst -License-File: LICENSE -Requires-Dist: frozenlist (>=1.1.0) - -========= -aiosignal -========= - -.. image:: https://github.com/aio-libs/aiosignal/workflows/CI/badge.svg - :target: https://github.com/aio-libs/aiosignal/actions?query=workflow%3ACI - :alt: GitHub status for master branch - -.. image:: https://codecov.io/gh/aio-libs/aiosignal/branch/master/graph/badge.svg - :target: https://codecov.io/gh/aio-libs/aiosignal - :alt: codecov.io status for master branch - -.. image:: https://badge.fury.io/py/aiosignal.svg - :target: https://pypi.org/project/aiosignal - :alt: Latest PyPI package version - -.. image:: https://readthedocs.org/projects/aiosignal/badge/?version=latest - :target: https://aiosignal.readthedocs.io/ - :alt: Latest Read The Docs - -.. image:: https://img.shields.io/discourse/topics?server=https%3A%2F%2Faio-libs.discourse.group%2F - :target: https://aio-libs.discourse.group/ - :alt: Discourse group for io-libs - -.. image:: https://badges.gitter.im/Join%20Chat.svg - :target: https://gitter.im/aio-libs/Lobby - :alt: Chat on Gitter - -Introduction -============ - -A project to manage callbacks in `asyncio` projects. - -``Signal`` is a list of registered asynchronous callbacks. - -The signal's life-cycle has two stages: after creation its content -could be filled by using standard list operations: ``sig.append()`` -etc. - -After you call ``sig.freeze()`` the signal is *frozen*: adding, removing -and dropping callbacks is forbidden. - -The only available operation is calling the previously registered -callbacks by using ``await sig.send(data)``. - -For concrete usage examples see the `Signals - -section of the `Web Server Advanced -` chapter of the `aiohttp -documentation`_. - - -Installation ------------- - -:: - - $ pip install aiosignal - -The library requires Python 3.6 or newer. - - -Documentation -============= - -https://aiosignal.readthedocs.io/ - -Communication channels -====================== - -*aio-libs* google group: https://groups.google.com/forum/#!forum/aio-libs - -Feel free to post your questions and ideas here. - -*gitter chat* https://gitter.im/aio-libs/Lobby - -Requirements -============ - -- Python >= 3.6 -- frozenlist >= 1.0.0 - -License -======= - -``aiosignal`` is offered under the Apache 2 license. - -Source code -=========== - -The project is hosted on GitHub_ - -Please file an issue in the `bug tracker -`_ if you have found a bug -or have some suggestions to improve the library. - -.. _GitHub: https://github.com/aio-libs/aiosignal -.. _aiohttp documentation: https://docs.aiohttp.org/ - -========= -Changelog -========= - -.. - You should *NOT* be adding new change log entries to this file, this - file is managed by towncrier. You *may* edit previous change logs to - fix problems like typo corrections or such. - To add a new change log entry, please see - https://pip.pypa.io/en/latest/development/contributing/#news-entries - we named the news folder "changes". - - WARNING: Don't drop the next directive! - -.. towncrier release notes start - - -1.2.0 (2021-10-16) -================== - -Features --------- - -- Added support for Python 3.10. - `#328 `_ - - -Bugfixes --------- - -- Mark aiosignal as Python3-only package - `#165 `_ - - ----- - - -1.1.2 (2020-11-27) -================== - -Features --------- - -- Fix MANIFEST.in to include ``aiosignal/py.typed`` marker - - -1.1.1 (2020-11-27) -================== - -Features --------- - -- Support type hints - -1.1.0 (2020-10-13) -================== - -Features --------- - -- Added support of Python 3.8 and 3.9 - - -1.0.0 (2019-11-11) -================== - -Deprecations and Removals -------------------------- - -- Dropped support for Python 3.5; only 3.6, 3.7 and 3.8 are supported going forward. - `#23 `_ - diff --git a/.venv/Lib/site-packages/aiosignal-1.2.0.dist-info/RECORD b/.venv/Lib/site-packages/aiosignal-1.2.0.dist-info/RECORD deleted file mode 100644 index 015823c..0000000 --- a/.venv/Lib/site-packages/aiosignal-1.2.0.dist-info/RECORD +++ /dev/null @@ -1,10 +0,0 @@ -aiosignal-1.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -aiosignal-1.2.0.dist-info/LICENSE,sha256=b9UkPpLdf5jsacesN3co50kFcJ_1J6W_mNbQJjwE9bY,11332 -aiosignal-1.2.0.dist-info/METADATA,sha256=_mpNKRs47LsjeAv7Hv0LpexfFiH1B74eOtJhDA8w6-I,5500 -aiosignal-1.2.0.dist-info/RECORD,, -aiosignal-1.2.0.dist-info/WHEEL,sha256=ewwEueio1C2XeHTvT17n8dZUJgOvyCWCt0WVNLClP9o,92 -aiosignal-1.2.0.dist-info/top_level.txt,sha256=z45aNOKGDdrI1roqZY3BGXQ22kJFPHBmVdwtLYLtXC0,10 -aiosignal/__init__.py,sha256=MGQyLD_0xNqLqPpBqxPj0CHKQjCIY1UFUK5PtHvCWbU,867 -aiosignal/__init__.pyi,sha256=xeCddYSS8fZAkz8S4HuKSR2IDe3N7RW_LKcXDPPA1Xk,311 -aiosignal/__pycache__/__init__.cpython-38.pyc,, -aiosignal/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/.venv/Lib/site-packages/aiosignal-1.2.0.dist-info/WHEEL b/.venv/Lib/site-packages/aiosignal-1.2.0.dist-info/WHEEL deleted file mode 100644 index 5bad85f..0000000 --- a/.venv/Lib/site-packages/aiosignal-1.2.0.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: bdist_wheel (0.37.0) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/.venv/Lib/site-packages/aiosignal-1.2.0.dist-info/top_level.txt b/.venv/Lib/site-packages/aiosignal-1.2.0.dist-info/top_level.txt deleted file mode 100644 index ac6df3a..0000000 --- a/.venv/Lib/site-packages/aiosignal-1.2.0.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -aiosignal diff --git a/.venv/Lib/site-packages/aiosignal/__init__.py b/.venv/Lib/site-packages/aiosignal/__init__.py deleted file mode 100644 index f3b9085..0000000 --- a/.venv/Lib/site-packages/aiosignal/__init__.py +++ /dev/null @@ -1,36 +0,0 @@ -from frozenlist import FrozenList - -__version__ = "1.2.0" - -__all__ = ("Signal",) - - -class Signal(FrozenList): - """Coroutine-based signal implementation. - - To connect a callback to a signal, use any list method. - - Signals are fired using the send() coroutine, which takes named - arguments. - """ - - __slots__ = ("_owner",) - - def __init__(self, owner): - super().__init__() - self._owner = owner - - def __repr__(self): - return "".format( - self._owner, self.frozen, list(self) - ) - - async def send(self, *args, **kwargs): - """ - Sends data to all registered receivers. - """ - if not self.frozen: - raise RuntimeError("Cannot send non-frozen signal.") - - for receiver in self: - await receiver(*args, **kwargs) # type: ignore diff --git a/.venv/Lib/site-packages/aiosignal/__init__.pyi b/.venv/Lib/site-packages/aiosignal/__init__.pyi deleted file mode 100644 index d4e3416..0000000 --- a/.venv/Lib/site-packages/aiosignal/__init__.pyi +++ /dev/null @@ -1,12 +0,0 @@ -from typing import Any, Generic, TypeVar - -from frozenlist import FrozenList - -__all__ = ("Signal",) - -_T = TypeVar("_T") - -class Signal(FrozenList[_T], Generic[_T]): - def __init__(self, owner: Any) -> None: ... - def __repr__(self) -> str: ... - async def send(self, *args: Any, **kwargs: Any) -> None: ... diff --git a/.venv/Lib/site-packages/aiosignal/__pycache__/__init__.cpython-38.pyc b/.venv/Lib/site-packages/aiosignal/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index 7126252..0000000 Binary files a/.venv/Lib/site-packages/aiosignal/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/arrow-1.2.3.dist-info/INSTALLER b/.venv/Lib/site-packages/arrow-1.2.3.dist-info/INSTALLER deleted file mode 100644 index a1b589e..0000000 --- a/.venv/Lib/site-packages/arrow-1.2.3.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/.venv/Lib/site-packages/arrow-1.2.3.dist-info/LICENSE b/.venv/Lib/site-packages/arrow-1.2.3.dist-info/LICENSE deleted file mode 100644 index 4f9eea5..0000000 --- a/.venv/Lib/site-packages/arrow-1.2.3.dist-info/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2021 Chris Smith - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/.venv/Lib/site-packages/arrow-1.2.3.dist-info/METADATA b/.venv/Lib/site-packages/arrow-1.2.3.dist-info/METADATA deleted file mode 100644 index b3f89db..0000000 --- a/.venv/Lib/site-packages/arrow-1.2.3.dist-info/METADATA +++ /dev/null @@ -1,163 +0,0 @@ -Metadata-Version: 2.1 -Name: arrow -Version: 1.2.3 -Summary: Better dates & times for Python -Home-page: https://arrow.readthedocs.io -Author: Chris Smith -Author-email: crsmithdev@gmail.com -License: Apache 2.0 -Project-URL: Repository, https://github.com/arrow-py/arrow -Project-URL: Bug Reports, https://github.com/arrow-py/arrow/issues -Project-URL: Documentation, https://arrow.readthedocs.io -Keywords: arrow date time datetime timestamp timezone humanize -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: Apache Software License -Classifier: Topic :: Software Development :: Libraries :: Python Modules -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: 3.6 -Classifier: Programming Language :: Python :: 3.7 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Requires-Python: >=3.6 -Description-Content-Type: text/x-rst -License-File: LICENSE -Requires-Dist: python-dateutil (>=2.7.0) -Requires-Dist: typing-extensions ; python_version < "3.8" - -Arrow: Better dates & times for Python -====================================== - -.. start-inclusion-marker-do-not-remove - -.. image:: https://github.com/arrow-py/arrow/workflows/tests/badge.svg?branch=master - :alt: Build Status - :target: https://github.com/arrow-py/arrow/actions?query=workflow%3Atests+branch%3Amaster - -.. image:: https://codecov.io/gh/arrow-py/arrow/branch/master/graph/badge.svg - :alt: Coverage - :target: https://codecov.io/gh/arrow-py/arrow - -.. image:: https://img.shields.io/pypi/v/arrow.svg - :alt: PyPI Version - :target: https://pypi.python.org/pypi/arrow - -.. image:: https://img.shields.io/pypi/pyversions/arrow.svg - :alt: Supported Python Versions - :target: https://pypi.python.org/pypi/arrow - -.. image:: https://img.shields.io/pypi/l/arrow.svg - :alt: License - :target: https://pypi.python.org/pypi/arrow - -.. image:: https://img.shields.io/badge/code%20style-black-000000.svg - :alt: Code Style: Black - :target: https://github.com/psf/black - - -**Arrow** is a Python library that offers a sensible and human-friendly approach to creating, manipulating, formatting and converting dates, times and timestamps. It implements and updates the datetime type, plugging gaps in functionality and providing an intelligent module API that supports many common creation scenarios. Simply put, it helps you work with dates and times with fewer imports and a lot less code. - -Arrow is named after the `arrow of time `_ and is heavily inspired by `moment.js `_ and `requests `_. - -Why use Arrow over built-in modules? ------------------------------------- - -Python's standard library and some other low-level modules have near-complete date, time and timezone functionality, but don't work very well from a usability perspective: - -- Too many modules: datetime, time, calendar, dateutil, pytz and more -- Too many types: date, time, datetime, tzinfo, timedelta, relativedelta, etc. -- Timezones and timestamp conversions are verbose and unpleasant -- Timezone naivety is the norm -- Gaps in functionality: ISO 8601 parsing, timespans, humanization - -Features --------- - -- Fully-implemented, drop-in replacement for datetime -- Support for Python 3.6+ -- Timezone-aware and UTC by default -- Super-simple creation options for many common input scenarios -- ``shift`` method with support for relative offsets, including weeks -- Format and parse strings automatically -- Wide support for the `ISO 8601 `_ standard -- Timezone conversion -- Support for ``dateutil``, ``pytz``, and ``ZoneInfo`` tzinfo objects -- Generates time spans, ranges, floors and ceilings for time frames ranging from microsecond to year -- Humanize dates and times with a growing list of contributed locales -- Extensible for your own Arrow-derived types -- Full support for PEP 484-style type hints - -Quick Start ------------ - -Installation -~~~~~~~~~~~~ - -To install Arrow, use `pip `_ or `pipenv `_: - -.. code-block:: console - - $ pip install -U arrow - -Example Usage -~~~~~~~~~~~~~ - -.. code-block:: python - - >>> import arrow - >>> arrow.get('2013-05-11T21:23:58.970460+07:00') - - - >>> utc = arrow.utcnow() - >>> utc - - - >>> utc = utc.shift(hours=-1) - >>> utc - - - >>> local = utc.to('US/Pacific') - >>> local - - - >>> local.timestamp() - 1368303838.970460 - - >>> local.format() - '2013-05-11 13:23:58 -07:00' - - >>> local.format('YYYY-MM-DD HH:mm:ss ZZ') - '2013-05-11 13:23:58 -07:00' - - >>> local.humanize() - 'an hour ago' - - >>> local.humanize(locale='ko-kr') - '한시간 전' - -.. end-inclusion-marker-do-not-remove - -Documentation -------------- - -For full documentation, please visit `arrow.readthedocs.io `_. - -Contributing ------------- - -Contributions are welcome for both code and localizations (adding and updating locales). Begin by gaining familiarity with the Arrow library and its features. Then, jump into contributing: - -#. Find an issue or feature to tackle on the `issue tracker `_. Issues marked with the `"good first issue" label `_ may be a great place to start! -#. Fork `this repository `_ on GitHub and begin making changes in a branch. -#. Add a few tests to ensure that the bug was fixed or the feature works as expected. -#. Run the entire test suite and linting checks by running one of the following commands: ``tox && tox -e lint,docs`` (if you have `tox `_ installed) **OR** ``make build39 && make test && make lint`` (if you do not have Python 3.9 installed, replace ``build39`` with the latest Python version on your system). -#. Submit a pull request and await feedback 😃. - -If you have any questions along the way, feel free to ask them `here `_. - -Support Arrow -------------- - -`Open Collective `_ is an online funding platform that provides tools to raise money and share your finances with full transparency. It is the platform of choice for individuals and companies to make one-time or recurring donations directly to the project. If you are interested in making a financial contribution, please visit the `Arrow collective `_. diff --git a/.venv/Lib/site-packages/arrow-1.2.3.dist-info/RECORD b/.venv/Lib/site-packages/arrow-1.2.3.dist-info/RECORD deleted file mode 100644 index c1052f5..0000000 --- a/.venv/Lib/site-packages/arrow-1.2.3.dist-info/RECORD +++ /dev/null @@ -1,27 +0,0 @@ -arrow-1.2.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -arrow-1.2.3.dist-info/LICENSE,sha256=QNbhJV1xUfXwQaUUcl08lP-owYgeWgwptr6pPwPi47s,11341 -arrow-1.2.3.dist-info/METADATA,sha256=gg8GFdfHjX15F_yMrLsluJwKUXTaQi5ECUvwBlZYe9o,6938 -arrow-1.2.3.dist-info/RECORD,, -arrow-1.2.3.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92 -arrow-1.2.3.dist-info/top_level.txt,sha256=aCBThK2RIB824ctI3l9i6z94l8UYpFF-BC4m3dDzFFo,6 -arrow/__init__.py,sha256=HxsSJGl56GoeHB__No-kdGmC_Wes_Ttf0ohOy7OoFig,872 -arrow/__pycache__/__init__.cpython-38.pyc,, -arrow/__pycache__/_version.cpython-38.pyc,, -arrow/__pycache__/api.cpython-38.pyc,, -arrow/__pycache__/arrow.cpython-38.pyc,, -arrow/__pycache__/constants.cpython-38.pyc,, -arrow/__pycache__/factory.cpython-38.pyc,, -arrow/__pycache__/formatter.cpython-38.pyc,, -arrow/__pycache__/locales.cpython-38.pyc,, -arrow/__pycache__/parser.cpython-38.pyc,, -arrow/__pycache__/util.cpython-38.pyc,, -arrow/_version.py,sha256=C-D_WWrVkBDmQmApLcm0sWNh2CgIrwWfc8_sB5vvU-Q,22 -arrow/api.py,sha256=6tdqrG0NjrKO22_eWHU4a5xerfR6IrZPY-yynGpnvTM,2755 -arrow/arrow.py,sha256=CnSXk3GCi1DroUvElSxlwQy9Y-2lCUSV5GKLLrBFmRA,63570 -arrow/constants.py,sha256=y3scgWgxiFuQg4DeFlhmexy1BA7K8LFNZyqK-VWPQJs,3238 -arrow/factory.py,sha256=dWP3XIYfYjqp7DCOdEYAD7PQfsbpQE70Ph9OS1A1LnE,11435 -arrow/formatter.py,sha256=YpYY8jeGZH0sgjc23PBm8HKf-EMHLp-8Ua52XfrVgPQ,5271 -arrow/locales.py,sha256=QSi6FJTVdmxDxAUIDMhUp3sJ13tHhF2tB50fA_mve0I,156276 -arrow/parser.py,sha256=ingY4axAO40kEYUL8MwqTIhFegCAVouDZk3c4YOs9aI,25720 -arrow/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -arrow/util.py,sha256=xnDevqRyNeYWbl3x-n_Tyo4cOgHcdgbxFECFsJ1XoEc,3679 diff --git a/.venv/Lib/site-packages/arrow-1.2.3.dist-info/WHEEL b/.venv/Lib/site-packages/arrow-1.2.3.dist-info/WHEEL deleted file mode 100644 index becc9a6..0000000 --- a/.venv/Lib/site-packages/arrow-1.2.3.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: bdist_wheel (0.37.1) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/.venv/Lib/site-packages/arrow-1.2.3.dist-info/top_level.txt b/.venv/Lib/site-packages/arrow-1.2.3.dist-info/top_level.txt deleted file mode 100644 index e2dc747..0000000 --- a/.venv/Lib/site-packages/arrow-1.2.3.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -arrow diff --git a/.venv/Lib/site-packages/arrow/__init__.py b/.venv/Lib/site-packages/arrow/__init__.py deleted file mode 100644 index bc59709..0000000 --- a/.venv/Lib/site-packages/arrow/__init__.py +++ /dev/null @@ -1,39 +0,0 @@ -from ._version import __version__ -from .api import get, now, utcnow -from .arrow import Arrow -from .factory import ArrowFactory -from .formatter import ( - FORMAT_ATOM, - FORMAT_COOKIE, - FORMAT_RFC822, - FORMAT_RFC850, - FORMAT_RFC1036, - FORMAT_RFC1123, - FORMAT_RFC2822, - FORMAT_RFC3339, - FORMAT_RSS, - FORMAT_W3C, -) -from .parser import ParserError - -# https://mypy.readthedocs.io/en/stable/command_line.html#cmdoption-mypy-no-implicit-reexport -# Mypy with --strict or --no-implicit-reexport requires an explicit reexport. -__all__ = [ - "__version__", - "get", - "now", - "utcnow", - "Arrow", - "ArrowFactory", - "FORMAT_ATOM", - "FORMAT_COOKIE", - "FORMAT_RFC822", - "FORMAT_RFC850", - "FORMAT_RFC1036", - "FORMAT_RFC1123", - "FORMAT_RFC2822", - "FORMAT_RFC3339", - "FORMAT_RSS", - "FORMAT_W3C", - "ParserError", -] diff --git a/.venv/Lib/site-packages/arrow/__pycache__/__init__.cpython-38.pyc b/.venv/Lib/site-packages/arrow/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index 14d7140..0000000 Binary files a/.venv/Lib/site-packages/arrow/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/arrow/__pycache__/_version.cpython-38.pyc b/.venv/Lib/site-packages/arrow/__pycache__/_version.cpython-38.pyc deleted file mode 100644 index 58164dc..0000000 Binary files a/.venv/Lib/site-packages/arrow/__pycache__/_version.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/arrow/__pycache__/api.cpython-38.pyc b/.venv/Lib/site-packages/arrow/__pycache__/api.cpython-38.pyc deleted file mode 100644 index bec73eb..0000000 Binary files a/.venv/Lib/site-packages/arrow/__pycache__/api.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/arrow/__pycache__/arrow.cpython-38.pyc b/.venv/Lib/site-packages/arrow/__pycache__/arrow.cpython-38.pyc deleted file mode 100644 index 87342af..0000000 Binary files a/.venv/Lib/site-packages/arrow/__pycache__/arrow.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/arrow/__pycache__/constants.cpython-38.pyc b/.venv/Lib/site-packages/arrow/__pycache__/constants.cpython-38.pyc deleted file mode 100644 index afd7f82..0000000 Binary files a/.venv/Lib/site-packages/arrow/__pycache__/constants.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/arrow/__pycache__/factory.cpython-38.pyc b/.venv/Lib/site-packages/arrow/__pycache__/factory.cpython-38.pyc deleted file mode 100644 index 590e21d..0000000 Binary files a/.venv/Lib/site-packages/arrow/__pycache__/factory.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/arrow/__pycache__/formatter.cpython-38.pyc b/.venv/Lib/site-packages/arrow/__pycache__/formatter.cpython-38.pyc deleted file mode 100644 index 1de9c42..0000000 Binary files a/.venv/Lib/site-packages/arrow/__pycache__/formatter.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/arrow/__pycache__/locales.cpython-38.pyc b/.venv/Lib/site-packages/arrow/__pycache__/locales.cpython-38.pyc deleted file mode 100644 index 2b99831..0000000 Binary files a/.venv/Lib/site-packages/arrow/__pycache__/locales.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/arrow/__pycache__/parser.cpython-38.pyc b/.venv/Lib/site-packages/arrow/__pycache__/parser.cpython-38.pyc deleted file mode 100644 index 9327461..0000000 Binary files a/.venv/Lib/site-packages/arrow/__pycache__/parser.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/arrow/__pycache__/util.cpython-38.pyc b/.venv/Lib/site-packages/arrow/__pycache__/util.cpython-38.pyc deleted file mode 100644 index 21b18ae..0000000 Binary files a/.venv/Lib/site-packages/arrow/__pycache__/util.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/arrow/_version.py b/.venv/Lib/site-packages/arrow/_version.py deleted file mode 100644 index 10aa336..0000000 --- a/.venv/Lib/site-packages/arrow/_version.py +++ /dev/null @@ -1 +0,0 @@ -__version__ = "1.2.3" diff --git a/.venv/Lib/site-packages/arrow/api.py b/.venv/Lib/site-packages/arrow/api.py deleted file mode 100644 index d8ed24b..0000000 --- a/.venv/Lib/site-packages/arrow/api.py +++ /dev/null @@ -1,126 +0,0 @@ -""" -Provides the default implementation of :class:`ArrowFactory ` -methods for use as a module API. - -""" - -from datetime import date, datetime -from datetime import tzinfo as dt_tzinfo -from time import struct_time -from typing import Any, List, Optional, Tuple, Type, Union, overload - -from arrow.arrow import TZ_EXPR, Arrow -from arrow.constants import DEFAULT_LOCALE -from arrow.factory import ArrowFactory - -# internal default factory. -_factory = ArrowFactory() - -# TODO: Use Positional Only Argument (https://www.python.org/dev/peps/pep-0570/) -# after Python 3.7 deprecation - - -@overload -def get( - *, - locale: str = DEFAULT_LOCALE, - tzinfo: Optional[TZ_EXPR] = None, - normalize_whitespace: bool = False, -) -> Arrow: - ... # pragma: no cover - - -@overload -def get( - *args: int, - locale: str = DEFAULT_LOCALE, - tzinfo: Optional[TZ_EXPR] = None, - normalize_whitespace: bool = False, -) -> Arrow: - ... # pragma: no cover - - -@overload -def get( - __obj: Union[ - Arrow, - datetime, - date, - struct_time, - dt_tzinfo, - int, - float, - str, - Tuple[int, int, int], - ], - *, - locale: str = DEFAULT_LOCALE, - tzinfo: Optional[TZ_EXPR] = None, - normalize_whitespace: bool = False, -) -> Arrow: - ... # pragma: no cover - - -@overload -def get( - __arg1: Union[datetime, date], - __arg2: TZ_EXPR, - *, - locale: str = DEFAULT_LOCALE, - tzinfo: Optional[TZ_EXPR] = None, - normalize_whitespace: bool = False, -) -> Arrow: - ... # pragma: no cover - - -@overload -def get( - __arg1: str, - __arg2: Union[str, List[str]], - *, - locale: str = DEFAULT_LOCALE, - tzinfo: Optional[TZ_EXPR] = None, - normalize_whitespace: bool = False, -) -> Arrow: - ... # pragma: no cover - - -def get(*args: Any, **kwargs: Any) -> Arrow: - """Calls the default :class:`ArrowFactory ` ``get`` method.""" - - return _factory.get(*args, **kwargs) - - -get.__doc__ = _factory.get.__doc__ - - -def utcnow() -> Arrow: - """Calls the default :class:`ArrowFactory ` ``utcnow`` method.""" - - return _factory.utcnow() - - -utcnow.__doc__ = _factory.utcnow.__doc__ - - -def now(tz: Optional[TZ_EXPR] = None) -> Arrow: - """Calls the default :class:`ArrowFactory ` ``now`` method.""" - - return _factory.now(tz) - - -now.__doc__ = _factory.now.__doc__ - - -def factory(type: Type[Arrow]) -> ArrowFactory: - """Returns an :class:`.ArrowFactory` for the specified :class:`Arrow ` - or derived type. - - :param type: the type, :class:`Arrow ` or derived. - - """ - - return ArrowFactory(type) - - -__all__ = ["get", "utcnow", "now", "factory"] diff --git a/.venv/Lib/site-packages/arrow/arrow.py b/.venv/Lib/site-packages/arrow/arrow.py deleted file mode 100644 index 1ede107..0000000 --- a/.venv/Lib/site-packages/arrow/arrow.py +++ /dev/null @@ -1,1886 +0,0 @@ -""" -Provides the :class:`Arrow ` class, an enhanced ``datetime`` -replacement. - -""" - - -import calendar -import re -import sys -from datetime import date -from datetime import datetime as dt_datetime -from datetime import time as dt_time -from datetime import timedelta -from datetime import tzinfo as dt_tzinfo -from math import trunc -from time import struct_time -from typing import ( - Any, - ClassVar, - Generator, - Iterable, - List, - Mapping, - Optional, - Tuple, - Union, - cast, - overload, -) - -from dateutil import tz as dateutil_tz -from dateutil.relativedelta import relativedelta - -from arrow import formatter, locales, parser, util -from arrow.constants import DEFAULT_LOCALE, DEHUMANIZE_LOCALES -from arrow.locales import TimeFrameLiteral - -if sys.version_info < (3, 8): # pragma: no cover - from typing_extensions import Final, Literal -else: - from typing import Final, Literal # pragma: no cover - - -TZ_EXPR = Union[dt_tzinfo, str] - -_T_FRAMES = Literal[ - "year", - "years", - "month", - "months", - "day", - "days", - "hour", - "hours", - "minute", - "minutes", - "second", - "seconds", - "microsecond", - "microseconds", - "week", - "weeks", - "quarter", - "quarters", -] - -_BOUNDS = Literal["[)", "()", "(]", "[]"] - -_GRANULARITY = Literal[ - "auto", - "second", - "minute", - "hour", - "day", - "week", - "month", - "quarter", - "year", -] - - -class Arrow: - """An :class:`Arrow ` object. - - Implements the ``datetime`` interface, behaving as an aware ``datetime`` while implementing - additional functionality. - - :param year: the calendar year. - :param month: the calendar month. - :param day: the calendar day. - :param hour: (optional) the hour. Defaults to 0. - :param minute: (optional) the minute, Defaults to 0. - :param second: (optional) the second, Defaults to 0. - :param microsecond: (optional) the microsecond. Defaults to 0. - :param tzinfo: (optional) A timezone expression. Defaults to UTC. - :param fold: (optional) 0 or 1, used to disambiguate repeated wall times. Defaults to 0. - - .. _tz-expr: - - Recognized timezone expressions: - - - A ``tzinfo`` object. - - A ``str`` describing a timezone, similar to 'US/Pacific', or 'Europe/Berlin'. - - A ``str`` in ISO 8601 style, as in '+07:00'. - - A ``str``, one of the following: 'local', 'utc', 'UTC'. - - Usage:: - - >>> import arrow - >>> arrow.Arrow(2013, 5, 5, 12, 30, 45) - - - """ - - resolution: ClassVar[timedelta] = dt_datetime.resolution - min: ClassVar["Arrow"] - max: ClassVar["Arrow"] - - _ATTRS: Final[List[str]] = [ - "year", - "month", - "day", - "hour", - "minute", - "second", - "microsecond", - ] - _ATTRS_PLURAL: Final[List[str]] = [f"{a}s" for a in _ATTRS] - _MONTHS_PER_QUARTER: Final[int] = 3 - _SECS_PER_MINUTE: Final[int] = 60 - _SECS_PER_HOUR: Final[int] = 60 * 60 - _SECS_PER_DAY: Final[int] = 60 * 60 * 24 - _SECS_PER_WEEK: Final[int] = 60 * 60 * 24 * 7 - _SECS_PER_MONTH: Final[float] = 60 * 60 * 24 * 30.5 - _SECS_PER_QUARTER: Final[float] = 60 * 60 * 24 * 30.5 * 3 - _SECS_PER_YEAR: Final[int] = 60 * 60 * 24 * 365 - - _SECS_MAP: Final[Mapping[TimeFrameLiteral, float]] = { - "second": 1.0, - "minute": _SECS_PER_MINUTE, - "hour": _SECS_PER_HOUR, - "day": _SECS_PER_DAY, - "week": _SECS_PER_WEEK, - "month": _SECS_PER_MONTH, - "quarter": _SECS_PER_QUARTER, - "year": _SECS_PER_YEAR, - } - - _datetime: dt_datetime - - def __init__( - self, - year: int, - month: int, - day: int, - hour: int = 0, - minute: int = 0, - second: int = 0, - microsecond: int = 0, - tzinfo: Optional[TZ_EXPR] = None, - **kwargs: Any, - ) -> None: - if tzinfo is None: - tzinfo = dateutil_tz.tzutc() - # detect that tzinfo is a pytz object (issue #626) - elif ( - isinstance(tzinfo, dt_tzinfo) - and hasattr(tzinfo, "localize") - and hasattr(tzinfo, "zone") - and tzinfo.zone # type: ignore[attr-defined] - ): - tzinfo = parser.TzinfoParser.parse(tzinfo.zone) # type: ignore[attr-defined] - elif isinstance(tzinfo, str): - tzinfo = parser.TzinfoParser.parse(tzinfo) - - fold = kwargs.get("fold", 0) - - self._datetime = dt_datetime( - year, month, day, hour, minute, second, microsecond, tzinfo, fold=fold - ) - - # factories: single object, both original and from datetime. - - @classmethod - def now(cls, tzinfo: Optional[dt_tzinfo] = None) -> "Arrow": - """Constructs an :class:`Arrow ` object, representing "now" in the given - timezone. - - :param tzinfo: (optional) a ``tzinfo`` object. Defaults to local time. - - Usage:: - - >>> arrow.now('Asia/Baku') - - - """ - - if tzinfo is None: - tzinfo = dateutil_tz.tzlocal() - - dt = dt_datetime.now(tzinfo) - - return cls( - dt.year, - dt.month, - dt.day, - dt.hour, - dt.minute, - dt.second, - dt.microsecond, - dt.tzinfo, - fold=getattr(dt, "fold", 0), - ) - - @classmethod - def utcnow(cls) -> "Arrow": - """Constructs an :class:`Arrow ` object, representing "now" in UTC - time. - - Usage:: - - >>> arrow.utcnow() - - - """ - - dt = dt_datetime.now(dateutil_tz.tzutc()) - - return cls( - dt.year, - dt.month, - dt.day, - dt.hour, - dt.minute, - dt.second, - dt.microsecond, - dt.tzinfo, - fold=getattr(dt, "fold", 0), - ) - - @classmethod - def fromtimestamp( - cls, - timestamp: Union[int, float, str], - tzinfo: Optional[TZ_EXPR] = None, - ) -> "Arrow": - """Constructs an :class:`Arrow ` object from a timestamp, converted to - the given timezone. - - :param timestamp: an ``int`` or ``float`` timestamp, or a ``str`` that converts to either. - :param tzinfo: (optional) a ``tzinfo`` object. Defaults to local time. - - """ - - if tzinfo is None: - tzinfo = dateutil_tz.tzlocal() - elif isinstance(tzinfo, str): - tzinfo = parser.TzinfoParser.parse(tzinfo) - - if not util.is_timestamp(timestamp): - raise ValueError(f"The provided timestamp {timestamp!r} is invalid.") - - timestamp = util.normalize_timestamp(float(timestamp)) - dt = dt_datetime.fromtimestamp(timestamp, tzinfo) - - return cls( - dt.year, - dt.month, - dt.day, - dt.hour, - dt.minute, - dt.second, - dt.microsecond, - dt.tzinfo, - fold=getattr(dt, "fold", 0), - ) - - @classmethod - def utcfromtimestamp(cls, timestamp: Union[int, float, str]) -> "Arrow": - """Constructs an :class:`Arrow ` object from a timestamp, in UTC time. - - :param timestamp: an ``int`` or ``float`` timestamp, or a ``str`` that converts to either. - - """ - - if not util.is_timestamp(timestamp): - raise ValueError(f"The provided timestamp {timestamp!r} is invalid.") - - timestamp = util.normalize_timestamp(float(timestamp)) - dt = dt_datetime.utcfromtimestamp(timestamp) - - return cls( - dt.year, - dt.month, - dt.day, - dt.hour, - dt.minute, - dt.second, - dt.microsecond, - dateutil_tz.tzutc(), - fold=getattr(dt, "fold", 0), - ) - - @classmethod - def fromdatetime(cls, dt: dt_datetime, tzinfo: Optional[TZ_EXPR] = None) -> "Arrow": - """Constructs an :class:`Arrow ` object from a ``datetime`` and - optional replacement timezone. - - :param dt: the ``datetime`` - :param tzinfo: (optional) A :ref:`timezone expression `. Defaults to ``dt``'s - timezone, or UTC if naive. - - Usage:: - - >>> dt - datetime.datetime(2021, 4, 7, 13, 48, tzinfo=tzfile('/usr/share/zoneinfo/US/Pacific')) - >>> arrow.Arrow.fromdatetime(dt) - - - """ - - if tzinfo is None: - if dt.tzinfo is None: - tzinfo = dateutil_tz.tzutc() - else: - tzinfo = dt.tzinfo - - return cls( - dt.year, - dt.month, - dt.day, - dt.hour, - dt.minute, - dt.second, - dt.microsecond, - tzinfo, - fold=getattr(dt, "fold", 0), - ) - - @classmethod - def fromdate(cls, date: date, tzinfo: Optional[TZ_EXPR] = None) -> "Arrow": - """Constructs an :class:`Arrow ` object from a ``date`` and optional - replacement timezone. All time values are set to 0. - - :param date: the ``date`` - :param tzinfo: (optional) A :ref:`timezone expression `. Defaults to UTC. - - """ - - if tzinfo is None: - tzinfo = dateutil_tz.tzutc() - - return cls(date.year, date.month, date.day, tzinfo=tzinfo) - - @classmethod - def strptime( - cls, date_str: str, fmt: str, tzinfo: Optional[TZ_EXPR] = None - ) -> "Arrow": - """Constructs an :class:`Arrow ` object from a date string and format, - in the style of ``datetime.strptime``. Optionally replaces the parsed timezone. - - :param date_str: the date string. - :param fmt: the format string using datetime format codes. - :param tzinfo: (optional) A :ref:`timezone expression `. Defaults to the parsed - timezone if ``fmt`` contains a timezone directive, otherwise UTC. - - Usage:: - - >>> arrow.Arrow.strptime('20-01-2019 15:49:10', '%d-%m-%Y %H:%M:%S') - - - """ - - dt = dt_datetime.strptime(date_str, fmt) - if tzinfo is None: - tzinfo = dt.tzinfo - - return cls( - dt.year, - dt.month, - dt.day, - dt.hour, - dt.minute, - dt.second, - dt.microsecond, - tzinfo, - fold=getattr(dt, "fold", 0), - ) - - @classmethod - def fromordinal(cls, ordinal: int) -> "Arrow": - """Constructs an :class:`Arrow ` object corresponding - to the Gregorian Ordinal. - - :param ordinal: an ``int`` corresponding to a Gregorian Ordinal. - - Usage:: - - >>> arrow.fromordinal(737741) - - - """ - - util.validate_ordinal(ordinal) - dt = dt_datetime.fromordinal(ordinal) - return cls( - dt.year, - dt.month, - dt.day, - dt.hour, - dt.minute, - dt.second, - dt.microsecond, - dt.tzinfo, - fold=getattr(dt, "fold", 0), - ) - - # factories: ranges and spans - - @classmethod - def range( - cls, - frame: _T_FRAMES, - start: Union["Arrow", dt_datetime], - end: Union["Arrow", dt_datetime, None] = None, - tz: Optional[TZ_EXPR] = None, - limit: Optional[int] = None, - ) -> Generator["Arrow", None, None]: - """Returns an iterator of :class:`Arrow ` objects, representing - points in time between two inputs. - - :param frame: The timeframe. Can be any ``datetime`` property (day, hour, minute...). - :param start: A datetime expression, the start of the range. - :param end: (optional) A datetime expression, the end of the range. - :param tz: (optional) A :ref:`timezone expression `. Defaults to - ``start``'s timezone, or UTC if ``start`` is naive. - :param limit: (optional) A maximum number of tuples to return. - - **NOTE**: The ``end`` or ``limit`` must be provided. Call with ``end`` alone to - return the entire range. Call with ``limit`` alone to return a maximum # of results from - the start. Call with both to cap a range at a maximum # of results. - - **NOTE**: ``tz`` internally **replaces** the timezones of both ``start`` and ``end`` before - iterating. As such, either call with naive objects and ``tz``, or aware objects from the - same timezone and no ``tz``. - - Supported frame values: year, quarter, month, week, day, hour, minute, second, microsecond. - - Recognized datetime expressions: - - - An :class:`Arrow ` object. - - A ``datetime`` object. - - Usage:: - - >>> start = datetime(2013, 5, 5, 12, 30) - >>> end = datetime(2013, 5, 5, 17, 15) - >>> for r in arrow.Arrow.range('hour', start, end): - ... print(repr(r)) - ... - - - - - - - **NOTE**: Unlike Python's ``range``, ``end`` *may* be included in the returned iterator:: - - >>> start = datetime(2013, 5, 5, 12, 30) - >>> end = datetime(2013, 5, 5, 13, 30) - >>> for r in arrow.Arrow.range('hour', start, end): - ... print(repr(r)) - ... - - - - """ - - _, frame_relative, relative_steps = cls._get_frames(frame) - - tzinfo = cls._get_tzinfo(start.tzinfo if tz is None else tz) - - start = cls._get_datetime(start).replace(tzinfo=tzinfo) - end, limit = cls._get_iteration_params(end, limit) - end = cls._get_datetime(end).replace(tzinfo=tzinfo) - - current = cls.fromdatetime(start) - original_day = start.day - day_is_clipped = False - i = 0 - - while current <= end and i < limit: - i += 1 - yield current - - values = [getattr(current, f) for f in cls._ATTRS] - current = cls(*values, tzinfo=tzinfo).shift( # type: ignore - **{frame_relative: relative_steps} - ) - - if frame in ["month", "quarter", "year"] and current.day < original_day: - day_is_clipped = True - - if day_is_clipped and not cls._is_last_day_of_month(current): - current = current.replace(day=original_day) - - def span( - self, - frame: _T_FRAMES, - count: int = 1, - bounds: _BOUNDS = "[)", - exact: bool = False, - week_start: int = 1, - ) -> Tuple["Arrow", "Arrow"]: - """Returns a tuple of two new :class:`Arrow ` objects, representing the timespan - of the :class:`Arrow ` object in a given timeframe. - - :param frame: the timeframe. Can be any ``datetime`` property (day, hour, minute...). - :param count: (optional) the number of frames to span. - :param bounds: (optional) a ``str`` of either '()', '(]', '[)', or '[]' that specifies - whether to include or exclude the start and end values in the span. '(' excludes - the start, '[' includes the start, ')' excludes the end, and ']' includes the end. - If the bounds are not specified, the default bound '[)' is used. - :param exact: (optional) whether to have the start of the timespan begin exactly - at the time specified by ``start`` and the end of the timespan truncated - so as not to extend beyond ``end``. - :param week_start: (optional) only used in combination with the week timeframe. Follows isoweekday() where - Monday is 1 and Sunday is 7. - - Supported frame values: year, quarter, month, week, day, hour, minute, second. - - Usage:: - - >>> arrow.utcnow() - - - >>> arrow.utcnow().span('hour') - (, ) - - >>> arrow.utcnow().span('day') - (, ) - - >>> arrow.utcnow().span('day', count=2) - (, ) - - >>> arrow.utcnow().span('day', bounds='[]') - (, ) - - >>> arrow.utcnow().span('week') - (, ) - - >>> arrow.utcnow().span('week', week_start=6) - (, ) - - """ - if not 1 <= week_start <= 7: - raise ValueError("week_start argument must be between 1 and 7.") - - util.validate_bounds(bounds) - - frame_absolute, frame_relative, relative_steps = self._get_frames(frame) - - if frame_absolute == "week": - attr = "day" - elif frame_absolute == "quarter": - attr = "month" - else: - attr = frame_absolute - - floor = self - if not exact: - index = self._ATTRS.index(attr) - frames = self._ATTRS[: index + 1] - - values = [getattr(self, f) for f in frames] - - for _ in range(3 - len(values)): - values.append(1) - - floor = self.__class__(*values, tzinfo=self.tzinfo) # type: ignore - - if frame_absolute == "week": - # if week_start is greater than self.isoweekday() go back one week by setting delta = 7 - delta = 7 if week_start > self.isoweekday() else 0 - floor = floor.shift(days=-(self.isoweekday() - week_start) - delta) - elif frame_absolute == "quarter": - floor = floor.shift(months=-((self.month - 1) % 3)) - - ceil = floor.shift(**{frame_relative: count * relative_steps}) - - if bounds[0] == "(": - floor = floor.shift(microseconds=+1) - - if bounds[1] == ")": - ceil = ceil.shift(microseconds=-1) - - return floor, ceil - - def floor(self, frame: _T_FRAMES) -> "Arrow": - """Returns a new :class:`Arrow ` object, representing the "floor" - of the timespan of the :class:`Arrow ` object in a given timeframe. - Equivalent to the first element in the 2-tuple returned by - :func:`span `. - - :param frame: the timeframe. Can be any ``datetime`` property (day, hour, minute...). - - Usage:: - - >>> arrow.utcnow().floor('hour') - - - """ - - return self.span(frame)[0] - - def ceil(self, frame: _T_FRAMES) -> "Arrow": - """Returns a new :class:`Arrow ` object, representing the "ceiling" - of the timespan of the :class:`Arrow ` object in a given timeframe. - Equivalent to the second element in the 2-tuple returned by - :func:`span `. - - :param frame: the timeframe. Can be any ``datetime`` property (day, hour, minute...). - - Usage:: - - >>> arrow.utcnow().ceil('hour') - - - """ - - return self.span(frame)[1] - - @classmethod - def span_range( - cls, - frame: _T_FRAMES, - start: dt_datetime, - end: dt_datetime, - tz: Optional[TZ_EXPR] = None, - limit: Optional[int] = None, - bounds: _BOUNDS = "[)", - exact: bool = False, - ) -> Iterable[Tuple["Arrow", "Arrow"]]: - """Returns an iterator of tuples, each :class:`Arrow ` objects, - representing a series of timespans between two inputs. - - :param frame: The timeframe. Can be any ``datetime`` property (day, hour, minute...). - :param start: A datetime expression, the start of the range. - :param end: (optional) A datetime expression, the end of the range. - :param tz: (optional) A :ref:`timezone expression `. Defaults to - ``start``'s timezone, or UTC if ``start`` is naive. - :param limit: (optional) A maximum number of tuples to return. - :param bounds: (optional) a ``str`` of either '()', '(]', '[)', or '[]' that specifies - whether to include or exclude the start and end values in each span in the range. '(' excludes - the start, '[' includes the start, ')' excludes the end, and ']' includes the end. - If the bounds are not specified, the default bound '[)' is used. - :param exact: (optional) whether to have the first timespan start exactly - at the time specified by ``start`` and the final span truncated - so as not to extend beyond ``end``. - - **NOTE**: The ``end`` or ``limit`` must be provided. Call with ``end`` alone to - return the entire range. Call with ``limit`` alone to return a maximum # of results from - the start. Call with both to cap a range at a maximum # of results. - - **NOTE**: ``tz`` internally **replaces** the timezones of both ``start`` and ``end`` before - iterating. As such, either call with naive objects and ``tz``, or aware objects from the - same timezone and no ``tz``. - - Supported frame values: year, quarter, month, week, day, hour, minute, second, microsecond. - - Recognized datetime expressions: - - - An :class:`Arrow ` object. - - A ``datetime`` object. - - **NOTE**: Unlike Python's ``range``, ``end`` will *always* be included in the returned - iterator of timespans. - - Usage: - - >>> start = datetime(2013, 5, 5, 12, 30) - >>> end = datetime(2013, 5, 5, 17, 15) - >>> for r in arrow.Arrow.span_range('hour', start, end): - ... print(r) - ... - (, ) - (, ) - (, ) - (, ) - (, ) - (, ) - - """ - - tzinfo = cls._get_tzinfo(start.tzinfo if tz is None else tz) - start = cls.fromdatetime(start, tzinfo).span(frame, exact=exact)[0] - end = cls.fromdatetime(end, tzinfo) - _range = cls.range(frame, start, end, tz, limit) - if not exact: - for r in _range: - yield r.span(frame, bounds=bounds, exact=exact) - - for r in _range: - floor, ceil = r.span(frame, bounds=bounds, exact=exact) - if ceil > end: - ceil = end - if bounds[1] == ")": - ceil += relativedelta(microseconds=-1) - if floor == end: - break - elif floor + relativedelta(microseconds=-1) == end: - break - yield floor, ceil - - @classmethod - def interval( - cls, - frame: _T_FRAMES, - start: dt_datetime, - end: dt_datetime, - interval: int = 1, - tz: Optional[TZ_EXPR] = None, - bounds: _BOUNDS = "[)", - exact: bool = False, - ) -> Iterable[Tuple["Arrow", "Arrow"]]: - """Returns an iterator of tuples, each :class:`Arrow ` objects, - representing a series of intervals between two inputs. - - :param frame: The timeframe. Can be any ``datetime`` property (day, hour, minute...). - :param start: A datetime expression, the start of the range. - :param end: (optional) A datetime expression, the end of the range. - :param interval: (optional) Time interval for the given time frame. - :param tz: (optional) A timezone expression. Defaults to UTC. - :param bounds: (optional) a ``str`` of either '()', '(]', '[)', or '[]' that specifies - whether to include or exclude the start and end values in the intervals. '(' excludes - the start, '[' includes the start, ')' excludes the end, and ']' includes the end. - If the bounds are not specified, the default bound '[)' is used. - :param exact: (optional) whether to have the first timespan start exactly - at the time specified by ``start`` and the final interval truncated - so as not to extend beyond ``end``. - - Supported frame values: year, quarter, month, week, day, hour, minute, second - - Recognized datetime expressions: - - - An :class:`Arrow ` object. - - A ``datetime`` object. - - Recognized timezone expressions: - - - A ``tzinfo`` object. - - A ``str`` describing a timezone, similar to 'US/Pacific', or 'Europe/Berlin'. - - A ``str`` in ISO 8601 style, as in '+07:00'. - - A ``str``, one of the following: 'local', 'utc', 'UTC'. - - Usage: - - >>> start = datetime(2013, 5, 5, 12, 30) - >>> end = datetime(2013, 5, 5, 17, 15) - >>> for r in arrow.Arrow.interval('hour', start, end, 2): - ... print(r) - ... - (, ) - (, ) - (, ) - """ - if interval < 1: - raise ValueError("interval has to be a positive integer") - - spanRange = iter( - cls.span_range(frame, start, end, tz, bounds=bounds, exact=exact) - ) - while True: - try: - intvlStart, intvlEnd = next(spanRange) - for _ in range(interval - 1): - try: - _, intvlEnd = next(spanRange) - except StopIteration: - continue - yield intvlStart, intvlEnd - except StopIteration: - return - - # representations - - def __repr__(self) -> str: - return f"<{self.__class__.__name__} [{self.__str__()}]>" - - def __str__(self) -> str: - return self._datetime.isoformat() - - def __format__(self, formatstr: str) -> str: - - if len(formatstr) > 0: - return self.format(formatstr) - - return str(self) - - def __hash__(self) -> int: - return self._datetime.__hash__() - - # attributes and properties - - def __getattr__(self, name: str) -> int: - - if name == "week": - return self.isocalendar()[1] - - if name == "quarter": - return int((self.month - 1) / self._MONTHS_PER_QUARTER) + 1 - - if not name.startswith("_"): - value: Optional[int] = getattr(self._datetime, name, None) - - if value is not None: - return value - - return cast(int, object.__getattribute__(self, name)) - - @property - def tzinfo(self) -> dt_tzinfo: - """Gets the ``tzinfo`` of the :class:`Arrow ` object. - - Usage:: - - >>> arw=arrow.utcnow() - >>> arw.tzinfo - tzutc() - - """ - - # In Arrow, `_datetime` cannot be naive. - return cast(dt_tzinfo, self._datetime.tzinfo) - - @property - def datetime(self) -> dt_datetime: - """Returns a datetime representation of the :class:`Arrow ` object. - - Usage:: - - >>> arw=arrow.utcnow() - >>> arw.datetime - datetime.datetime(2019, 1, 24, 16, 35, 27, 276649, tzinfo=tzutc()) - - """ - - return self._datetime - - @property - def naive(self) -> dt_datetime: - """Returns a naive datetime representation of the :class:`Arrow ` - object. - - Usage:: - - >>> nairobi = arrow.now('Africa/Nairobi') - >>> nairobi - - >>> nairobi.naive - datetime.datetime(2019, 1, 23, 19, 27, 12, 297999) - - """ - - return self._datetime.replace(tzinfo=None) - - def timestamp(self) -> float: - """Returns a timestamp representation of the :class:`Arrow ` object, in - UTC time. - - Usage:: - - >>> arrow.utcnow().timestamp() - 1616882340.256501 - - """ - - return self._datetime.timestamp() - - @property - def int_timestamp(self) -> int: - """Returns an integer timestamp representation of the :class:`Arrow ` object, in - UTC time. - - Usage:: - - >>> arrow.utcnow().int_timestamp - 1548260567 - - """ - - return int(self.timestamp()) - - @property - def float_timestamp(self) -> float: - """Returns a floating-point timestamp representation of the :class:`Arrow ` - object, in UTC time. - - Usage:: - - >>> arrow.utcnow().float_timestamp - 1548260516.830896 - - """ - - return self.timestamp() - - @property - def fold(self) -> int: - """Returns the ``fold`` value of the :class:`Arrow ` object.""" - - return self._datetime.fold - - @property - def ambiguous(self) -> bool: - """Indicates whether the :class:`Arrow ` object is a repeated wall time in the current - timezone. - - """ - - return dateutil_tz.datetime_ambiguous(self._datetime) - - @property - def imaginary(self) -> bool: - """Indicates whether the :class: `Arrow ` object exists in the current timezone.""" - - return not dateutil_tz.datetime_exists(self._datetime) - - # mutation and duplication. - - def clone(self) -> "Arrow": - """Returns a new :class:`Arrow ` object, cloned from the current one. - - Usage: - - >>> arw = arrow.utcnow() - >>> cloned = arw.clone() - - """ - - return self.fromdatetime(self._datetime) - - def replace(self, **kwargs: Any) -> "Arrow": - """Returns a new :class:`Arrow ` object with attributes updated - according to inputs. - - Use property names to set their value absolutely:: - - >>> import arrow - >>> arw = arrow.utcnow() - >>> arw - - >>> arw.replace(year=2014, month=6) - - - You can also replace the timezone without conversion, using a - :ref:`timezone expression `:: - - >>> arw.replace(tzinfo=tz.tzlocal()) - - - """ - - absolute_kwargs = {} - - for key, value in kwargs.items(): - - if key in self._ATTRS: - absolute_kwargs[key] = value - elif key in ["week", "quarter"]: - raise ValueError(f"Setting absolute {key} is not supported.") - elif key not in ["tzinfo", "fold"]: - raise ValueError(f"Unknown attribute: {key!r}.") - - current = self._datetime.replace(**absolute_kwargs) - - tzinfo = kwargs.get("tzinfo") - - if tzinfo is not None: - tzinfo = self._get_tzinfo(tzinfo) - current = current.replace(tzinfo=tzinfo) - - fold = kwargs.get("fold") - - if fold is not None: - current = current.replace(fold=fold) - - return self.fromdatetime(current) - - def shift(self, **kwargs: Any) -> "Arrow": - """Returns a new :class:`Arrow ` object with attributes updated - according to inputs. - - Use pluralized property names to relatively shift their current value: - - >>> import arrow - >>> arw = arrow.utcnow() - >>> arw - - >>> arw.shift(years=1, months=-1) - - - Day-of-the-week relative shifting can use either Python's weekday numbers - (Monday = 0, Tuesday = 1 .. Sunday = 6) or using dateutil.relativedelta's - day instances (MO, TU .. SU). When using weekday numbers, the returned - date will always be greater than or equal to the starting date. - - Using the above code (which is a Saturday) and asking it to shift to Saturday: - - >>> arw.shift(weekday=5) - - - While asking for a Monday: - - >>> arw.shift(weekday=0) - - - """ - - relative_kwargs = {} - additional_attrs = ["weeks", "quarters", "weekday"] - - for key, value in kwargs.items(): - - if key in self._ATTRS_PLURAL or key in additional_attrs: - relative_kwargs[key] = value - else: - supported_attr = ", ".join(self._ATTRS_PLURAL + additional_attrs) - raise ValueError( - f"Invalid shift time frame. Please select one of the following: {supported_attr}." - ) - - # core datetime does not support quarters, translate to months. - relative_kwargs.setdefault("months", 0) - relative_kwargs["months"] += ( - relative_kwargs.pop("quarters", 0) * self._MONTHS_PER_QUARTER - ) - - current = self._datetime + relativedelta(**relative_kwargs) - - if not dateutil_tz.datetime_exists(current): - current = dateutil_tz.resolve_imaginary(current) - - return self.fromdatetime(current) - - def to(self, tz: TZ_EXPR) -> "Arrow": - """Returns a new :class:`Arrow ` object, converted - to the target timezone. - - :param tz: A :ref:`timezone expression `. - - Usage:: - - >>> utc = arrow.utcnow() - >>> utc - - - >>> utc.to('US/Pacific') - - - >>> utc.to(tz.tzlocal()) - - - >>> utc.to('-07:00') - - - >>> utc.to('local') - - - >>> utc.to('local').to('utc') - - - """ - - if not isinstance(tz, dt_tzinfo): - tz = parser.TzinfoParser.parse(tz) - - dt = self._datetime.astimezone(tz) - - return self.__class__( - dt.year, - dt.month, - dt.day, - dt.hour, - dt.minute, - dt.second, - dt.microsecond, - dt.tzinfo, - fold=getattr(dt, "fold", 0), - ) - - # string output and formatting - - def format( - self, fmt: str = "YYYY-MM-DD HH:mm:ssZZ", locale: str = DEFAULT_LOCALE - ) -> str: - """Returns a string representation of the :class:`Arrow ` object, - formatted according to the provided format string. - - :param fmt: the format string. - :param locale: the locale to format. - - Usage:: - - >>> arrow.utcnow().format('YYYY-MM-DD HH:mm:ss ZZ') - '2013-05-09 03:56:47 -00:00' - - >>> arrow.utcnow().format('X') - '1368071882' - - >>> arrow.utcnow().format('MMMM DD, YYYY') - 'May 09, 2013' - - >>> arrow.utcnow().format() - '2013-05-09 03:56:47 -00:00' - - """ - - return formatter.DateTimeFormatter(locale).format(self._datetime, fmt) - - def humanize( - self, - other: Union["Arrow", dt_datetime, None] = None, - locale: str = DEFAULT_LOCALE, - only_distance: bool = False, - granularity: Union[_GRANULARITY, List[_GRANULARITY]] = "auto", - ) -> str: - """Returns a localized, humanized representation of a relative difference in time. - - :param other: (optional) an :class:`Arrow ` or ``datetime`` object. - Defaults to now in the current :class:`Arrow ` object's timezone. - :param locale: (optional) a ``str`` specifying a locale. Defaults to 'en-us'. - :param only_distance: (optional) returns only time difference eg: "11 seconds" without "in" or "ago" part. - :param granularity: (optional) defines the precision of the output. Set it to strings 'second', 'minute', - 'hour', 'day', 'week', 'month' or 'year' or a list of any combination of these strings - - Usage:: - - >>> earlier = arrow.utcnow().shift(hours=-2) - >>> earlier.humanize() - '2 hours ago' - - >>> later = earlier.shift(hours=4) - >>> later.humanize(earlier) - 'in 4 hours' - - """ - - locale_name = locale - locale = locales.get_locale(locale) - - if other is None: - utc = dt_datetime.utcnow().replace(tzinfo=dateutil_tz.tzutc()) - dt = utc.astimezone(self._datetime.tzinfo) - - elif isinstance(other, Arrow): - dt = other._datetime - - elif isinstance(other, dt_datetime): - if other.tzinfo is None: - dt = other.replace(tzinfo=self._datetime.tzinfo) - else: - dt = other.astimezone(self._datetime.tzinfo) - - else: - raise TypeError( - f"Invalid 'other' argument of type {type(other).__name__!r}. " - "Argument must be of type None, Arrow, or datetime." - ) - - if isinstance(granularity, list) and len(granularity) == 1: - granularity = granularity[0] - - _delta = int(round((self._datetime - dt).total_seconds())) - sign = -1 if _delta < 0 else 1 - delta_second = diff = abs(_delta) - - try: - if granularity == "auto": - if diff < 10: - return locale.describe("now", only_distance=only_distance) - - if diff < self._SECS_PER_MINUTE: - seconds = sign * delta_second - return locale.describe( - "seconds", seconds, only_distance=only_distance - ) - - elif diff < self._SECS_PER_MINUTE * 2: - return locale.describe("minute", sign, only_distance=only_distance) - elif diff < self._SECS_PER_HOUR: - minutes = sign * max(delta_second // self._SECS_PER_MINUTE, 2) - return locale.describe( - "minutes", minutes, only_distance=only_distance - ) - - elif diff < self._SECS_PER_HOUR * 2: - return locale.describe("hour", sign, only_distance=only_distance) - elif diff < self._SECS_PER_DAY: - hours = sign * max(delta_second // self._SECS_PER_HOUR, 2) - return locale.describe("hours", hours, only_distance=only_distance) - elif diff < self._SECS_PER_DAY * 2: - return locale.describe("day", sign, only_distance=only_distance) - elif diff < self._SECS_PER_WEEK: - days = sign * max(delta_second // self._SECS_PER_DAY, 2) - return locale.describe("days", days, only_distance=only_distance) - - elif diff < self._SECS_PER_WEEK * 2: - return locale.describe("week", sign, only_distance=only_distance) - elif diff < self._SECS_PER_MONTH: - weeks = sign * max(delta_second // self._SECS_PER_WEEK, 2) - return locale.describe("weeks", weeks, only_distance=only_distance) - - elif diff < self._SECS_PER_MONTH * 2: - return locale.describe("month", sign, only_distance=only_distance) - elif diff < self._SECS_PER_YEAR: - # TODO revisit for humanization during leap years - self_months = self._datetime.year * 12 + self._datetime.month - other_months = dt.year * 12 + dt.month - - months = sign * max(abs(other_months - self_months), 2) - - return locale.describe( - "months", months, only_distance=only_distance - ) - - elif diff < self._SECS_PER_YEAR * 2: - return locale.describe("year", sign, only_distance=only_distance) - else: - years = sign * max(delta_second // self._SECS_PER_YEAR, 2) - return locale.describe("years", years, only_distance=only_distance) - - elif isinstance(granularity, str): - granularity = cast(TimeFrameLiteral, granularity) # type: ignore[assignment] - - if granularity == "second": - delta = sign * float(delta_second) - if abs(delta) < 2: - return locale.describe("now", only_distance=only_distance) - elif granularity == "minute": - delta = sign * delta_second / self._SECS_PER_MINUTE - elif granularity == "hour": - delta = sign * delta_second / self._SECS_PER_HOUR - elif granularity == "day": - delta = sign * delta_second / self._SECS_PER_DAY - elif granularity == "week": - delta = sign * delta_second / self._SECS_PER_WEEK - elif granularity == "month": - delta = sign * delta_second / self._SECS_PER_MONTH - elif granularity == "quarter": - delta = sign * delta_second / self._SECS_PER_QUARTER - elif granularity == "year": - delta = sign * delta_second / self._SECS_PER_YEAR - else: - raise ValueError( - "Invalid level of granularity. " - "Please select between 'second', 'minute', 'hour', 'day', 'week', 'month', 'quarter' or 'year'." - ) - - if trunc(abs(delta)) != 1: - granularity += "s" # type: ignore - return locale.describe(granularity, delta, only_distance=only_distance) - - else: - - if not granularity: - raise ValueError( - "Empty granularity list provided. " - "Please select one or more from 'second', 'minute', 'hour', 'day', 'week', 'month', 'quarter', 'year'." - ) - - timeframes: List[Tuple[TimeFrameLiteral, float]] = [] - - def gather_timeframes(_delta: float, _frame: TimeFrameLiteral) -> float: - if _frame in granularity: - value = sign * _delta / self._SECS_MAP[_frame] - _delta %= self._SECS_MAP[_frame] - if trunc(abs(value)) != 1: - timeframes.append( - (cast(TimeFrameLiteral, _frame + "s"), value) - ) - else: - timeframes.append((_frame, value)) - return _delta - - delta = float(delta_second) - frames: Tuple[TimeFrameLiteral, ...] = ( - "year", - "quarter", - "month", - "week", - "day", - "hour", - "minute", - "second", - ) - for frame in frames: - delta = gather_timeframes(delta, frame) - - if len(timeframes) < len(granularity): - raise ValueError( - "Invalid level of granularity. " - "Please select between 'second', 'minute', 'hour', 'day', 'week', 'month', 'quarter' or 'year'." - ) - - return locale.describe_multi(timeframes, only_distance=only_distance) - - except KeyError as e: - raise ValueError( - f"Humanization of the {e} granularity is not currently translated in the {locale_name!r} locale. " - "Please consider making a contribution to this locale." - ) - - def dehumanize(self, input_string: str, locale: str = "en_us") -> "Arrow": - """Returns a new :class:`Arrow ` object, that represents - the time difference relative to the attrbiutes of the - :class:`Arrow ` object. - - :param timestring: a ``str`` representing a humanized relative time. - :param locale: (optional) a ``str`` specifying a locale. Defaults to 'en-us'. - - Usage:: - - >>> arw = arrow.utcnow() - >>> arw - - >>> earlier = arw.dehumanize("2 days ago") - >>> earlier - - - >>> arw = arrow.utcnow() - >>> arw - - >>> later = arw.dehumanize("in a month") - >>> later - - - """ - - # Create a locale object based off given local - locale_obj = locales.get_locale(locale) - - # Check to see if locale is supported - normalized_locale_name = locale.lower().replace("_", "-") - - if normalized_locale_name not in DEHUMANIZE_LOCALES: - raise ValueError( - f"Dehumanize does not currently support the {locale} locale, please consider making a contribution to add support for this locale." - ) - - current_time = self.fromdatetime(self._datetime) - - # Create an object containing the relative time info - time_object_info = dict.fromkeys( - ["seconds", "minutes", "hours", "days", "weeks", "months", "years"], 0 - ) - - # Create an object representing if unit has been seen - unit_visited = dict.fromkeys( - ["now", "seconds", "minutes", "hours", "days", "weeks", "months", "years"], - False, - ) - - # Create a regex pattern object for numbers - num_pattern = re.compile(r"\d+") - - # Search input string for each time unit within locale - for unit, unit_object in locale_obj.timeframes.items(): - - # Need to check the type of unit_object to create the correct dictionary - if isinstance(unit_object, Mapping): - strings_to_search = unit_object - else: - strings_to_search = {unit: str(unit_object)} - - # Search for any matches that exist for that locale's unit. - # Needs to cycle all through strings as some locales have strings that - # could overlap in a regex match, since input validation isn't being performed. - for time_delta, time_string in strings_to_search.items(): - - # Replace {0} with regex \d representing digits - search_string = str(time_string) - search_string = search_string.format(r"\d+") - - # Create search pattern and find within string - pattern = re.compile(rf"(^|\b|\d){search_string}") - match = pattern.search(input_string) - - # If there is no match continue to next iteration - if not match: - continue - - match_string = match.group() - num_match = num_pattern.search(match_string) - - # If no number matches - # Need for absolute value as some locales have signs included in their objects - if not num_match: - change_value = ( - 1 if not time_delta.isnumeric() else abs(int(time_delta)) - ) - else: - change_value = int(num_match.group()) - - # No time to update if now is the unit - if unit == "now": - unit_visited[unit] = True - continue - - # Add change value to the correct unit (incorporates the plurality that exists within timeframe i.e second v.s seconds) - time_unit_to_change = str(unit) - time_unit_to_change += ( - "s" if (str(time_unit_to_change)[-1] != "s") else "" - ) - time_object_info[time_unit_to_change] = change_value - unit_visited[time_unit_to_change] = True - - # Assert error if string does not modify any units - if not any([True for k, v in unit_visited.items() if v]): - raise ValueError( - "Input string not valid. Note: Some locales do not support the week granulairty in Arrow. " - "If you are attempting to use the week granularity on an unsupported locale, this could be the cause of this error." - ) - - # Sign logic - future_string = locale_obj.future - future_string = future_string.format(".*") - future_pattern = re.compile(rf"^{future_string}$") - future_pattern_match = future_pattern.findall(input_string) - - past_string = locale_obj.past - past_string = past_string.format(".*") - past_pattern = re.compile(rf"^{past_string}$") - past_pattern_match = past_pattern.findall(input_string) - - # If a string contains the now unit, there will be no relative units, hence the need to check if the now unit - # was visited before raising a ValueError - if past_pattern_match: - sign_val = -1 - elif future_pattern_match: - sign_val = 1 - elif unit_visited["now"]: - sign_val = 0 - else: - raise ValueError( - "Invalid input String. String does not contain any relative time information. " - "String should either represent a time in the future or a time in the past. " - "Ex: 'in 5 seconds' or '5 seconds ago'." - ) - - time_changes = {k: sign_val * v for k, v in time_object_info.items()} - - return current_time.shift(**time_changes) - - # query functions - - def is_between( - self, - start: "Arrow", - end: "Arrow", - bounds: _BOUNDS = "()", - ) -> bool: - """Returns a boolean denoting whether the :class:`Arrow ` object is between - the start and end limits. - - :param start: an :class:`Arrow ` object. - :param end: an :class:`Arrow ` object. - :param bounds: (optional) a ``str`` of either '()', '(]', '[)', or '[]' that specifies - whether to include or exclude the start and end values in the range. '(' excludes - the start, '[' includes the start, ')' excludes the end, and ']' includes the end. - If the bounds are not specified, the default bound '()' is used. - - Usage:: - - >>> start = arrow.get(datetime(2013, 5, 5, 12, 30, 10)) - >>> end = arrow.get(datetime(2013, 5, 5, 12, 30, 36)) - >>> arrow.get(datetime(2013, 5, 5, 12, 30, 27)).is_between(start, end) - True - - >>> start = arrow.get(datetime(2013, 5, 5)) - >>> end = arrow.get(datetime(2013, 5, 8)) - >>> arrow.get(datetime(2013, 5, 8)).is_between(start, end, '[]') - True - - >>> start = arrow.get(datetime(2013, 5, 5)) - >>> end = arrow.get(datetime(2013, 5, 8)) - >>> arrow.get(datetime(2013, 5, 8)).is_between(start, end, '[)') - False - - """ - - util.validate_bounds(bounds) - - if not isinstance(start, Arrow): - raise TypeError( - f"Cannot parse start date argument type of {type(start)!r}." - ) - - if not isinstance(end, Arrow): - raise TypeError(f"Cannot parse end date argument type of {type(start)!r}.") - - include_start = bounds[0] == "[" - include_end = bounds[1] == "]" - - target_ts = self.float_timestamp - start_ts = start.float_timestamp - end_ts = end.float_timestamp - - return ( - (start_ts <= target_ts <= end_ts) - and (include_start or start_ts < target_ts) - and (include_end or target_ts < end_ts) - ) - - # datetime methods - - def date(self) -> date: - """Returns a ``date`` object with the same year, month and day. - - Usage:: - - >>> arrow.utcnow().date() - datetime.date(2019, 1, 23) - - """ - - return self._datetime.date() - - def time(self) -> dt_time: - """Returns a ``time`` object with the same hour, minute, second, microsecond. - - Usage:: - - >>> arrow.utcnow().time() - datetime.time(12, 15, 34, 68352) - - """ - - return self._datetime.time() - - def timetz(self) -> dt_time: - """Returns a ``time`` object with the same hour, minute, second, microsecond and - tzinfo. - - Usage:: - - >>> arrow.utcnow().timetz() - datetime.time(12, 5, 18, 298893, tzinfo=tzutc()) - - """ - - return self._datetime.timetz() - - def astimezone(self, tz: Optional[dt_tzinfo]) -> dt_datetime: - """Returns a ``datetime`` object, converted to the specified timezone. - - :param tz: a ``tzinfo`` object. - - Usage:: - - >>> pacific=arrow.now('US/Pacific') - >>> nyc=arrow.now('America/New_York').tzinfo - >>> pacific.astimezone(nyc) - datetime.datetime(2019, 1, 20, 10, 24, 22, 328172, tzinfo=tzfile('/usr/share/zoneinfo/America/New_York')) - - """ - - return self._datetime.astimezone(tz) - - def utcoffset(self) -> Optional[timedelta]: - """Returns a ``timedelta`` object representing the whole number of minutes difference from - UTC time. - - Usage:: - - >>> arrow.now('US/Pacific').utcoffset() - datetime.timedelta(-1, 57600) - - """ - - return self._datetime.utcoffset() - - def dst(self) -> Optional[timedelta]: - """Returns the daylight savings time adjustment. - - Usage:: - - >>> arrow.utcnow().dst() - datetime.timedelta(0) - - """ - - return self._datetime.dst() - - def timetuple(self) -> struct_time: - """Returns a ``time.struct_time``, in the current timezone. - - Usage:: - - >>> arrow.utcnow().timetuple() - time.struct_time(tm_year=2019, tm_mon=1, tm_mday=20, tm_hour=15, tm_min=17, tm_sec=8, tm_wday=6, tm_yday=20, tm_isdst=0) - - """ - - return self._datetime.timetuple() - - def utctimetuple(self) -> struct_time: - """Returns a ``time.struct_time``, in UTC time. - - Usage:: - - >>> arrow.utcnow().utctimetuple() - time.struct_time(tm_year=2019, tm_mon=1, tm_mday=19, tm_hour=21, tm_min=41, tm_sec=7, tm_wday=5, tm_yday=19, tm_isdst=0) - - """ - - return self._datetime.utctimetuple() - - def toordinal(self) -> int: - """Returns the proleptic Gregorian ordinal of the date. - - Usage:: - - >>> arrow.utcnow().toordinal() - 737078 - - """ - - return self._datetime.toordinal() - - def weekday(self) -> int: - """Returns the day of the week as an integer (0-6). - - Usage:: - - >>> arrow.utcnow().weekday() - 5 - - """ - - return self._datetime.weekday() - - def isoweekday(self) -> int: - """Returns the ISO day of the week as an integer (1-7). - - Usage:: - - >>> arrow.utcnow().isoweekday() - 6 - - """ - - return self._datetime.isoweekday() - - def isocalendar(self) -> Tuple[int, int, int]: - """Returns a 3-tuple, (ISO year, ISO week number, ISO weekday). - - Usage:: - - >>> arrow.utcnow().isocalendar() - (2019, 3, 6) - - """ - - return self._datetime.isocalendar() - - def isoformat(self, sep: str = "T", timespec: str = "auto") -> str: - """Returns an ISO 8601 formatted representation of the date and time. - - Usage:: - - >>> arrow.utcnow().isoformat() - '2019-01-19T18:30:52.442118+00:00' - - """ - - return self._datetime.isoformat(sep, timespec) - - def ctime(self) -> str: - """Returns a ctime formatted representation of the date and time. - - Usage:: - - >>> arrow.utcnow().ctime() - 'Sat Jan 19 18:26:50 2019' - - """ - - return self._datetime.ctime() - - def strftime(self, format: str) -> str: - """Formats in the style of ``datetime.strftime``. - - :param format: the format string. - - Usage:: - - >>> arrow.utcnow().strftime('%d-%m-%Y %H:%M:%S') - '23-01-2019 12:28:17' - - """ - - return self._datetime.strftime(format) - - def for_json(self) -> str: - """Serializes for the ``for_json`` protocol of simplejson. - - Usage:: - - >>> arrow.utcnow().for_json() - '2019-01-19T18:25:36.760079+00:00' - - """ - - return self.isoformat() - - # math - - def __add__(self, other: Any) -> "Arrow": - - if isinstance(other, (timedelta, relativedelta)): - return self.fromdatetime(self._datetime + other, self._datetime.tzinfo) - - return NotImplemented - - def __radd__(self, other: Union[timedelta, relativedelta]) -> "Arrow": - return self.__add__(other) - - @overload - def __sub__(self, other: Union[timedelta, relativedelta]) -> "Arrow": - pass # pragma: no cover - - @overload - def __sub__(self, other: Union[dt_datetime, "Arrow"]) -> timedelta: - pass # pragma: no cover - - def __sub__(self, other: Any) -> Union[timedelta, "Arrow"]: - - if isinstance(other, (timedelta, relativedelta)): - return self.fromdatetime(self._datetime - other, self._datetime.tzinfo) - - elif isinstance(other, dt_datetime): - return self._datetime - other - - elif isinstance(other, Arrow): - return self._datetime - other._datetime - - return NotImplemented - - def __rsub__(self, other: Any) -> timedelta: - - if isinstance(other, dt_datetime): - return other - self._datetime - - return NotImplemented - - # comparisons - - def __eq__(self, other: Any) -> bool: - - if not isinstance(other, (Arrow, dt_datetime)): - return False - - return self._datetime == self._get_datetime(other) - - def __ne__(self, other: Any) -> bool: - - if not isinstance(other, (Arrow, dt_datetime)): - return True - - return not self.__eq__(other) - - def __gt__(self, other: Any) -> bool: - - if not isinstance(other, (Arrow, dt_datetime)): - return NotImplemented - - return self._datetime > self._get_datetime(other) - - def __ge__(self, other: Any) -> bool: - - if not isinstance(other, (Arrow, dt_datetime)): - return NotImplemented - - return self._datetime >= self._get_datetime(other) - - def __lt__(self, other: Any) -> bool: - - if not isinstance(other, (Arrow, dt_datetime)): - return NotImplemented - - return self._datetime < self._get_datetime(other) - - def __le__(self, other: Any) -> bool: - - if not isinstance(other, (Arrow, dt_datetime)): - return NotImplemented - - return self._datetime <= self._get_datetime(other) - - # internal methods - @staticmethod - def _get_tzinfo(tz_expr: Optional[TZ_EXPR]) -> dt_tzinfo: - """Get normalized tzinfo object from various inputs.""" - if tz_expr is None: - return dateutil_tz.tzutc() - if isinstance(tz_expr, dt_tzinfo): - return tz_expr - else: - try: - return parser.TzinfoParser.parse(tz_expr) - except parser.ParserError: - raise ValueError(f"{tz_expr!r} not recognized as a timezone.") - - @classmethod - def _get_datetime( - cls, expr: Union["Arrow", dt_datetime, int, float, str] - ) -> dt_datetime: - """Get datetime object from a specified expression.""" - if isinstance(expr, Arrow): - return expr.datetime - elif isinstance(expr, dt_datetime): - return expr - elif util.is_timestamp(expr): - timestamp = float(expr) - return cls.utcfromtimestamp(timestamp).datetime - else: - raise ValueError(f"{expr!r} not recognized as a datetime or timestamp.") - - @classmethod - def _get_frames(cls, name: _T_FRAMES) -> Tuple[str, str, int]: - """Finds relevant timeframe and steps for use in range and span methods. - - Returns a 3 element tuple in the form (frame, plural frame, step), for example ("day", "days", 1) - - """ - if name in cls._ATTRS: - return name, f"{name}s", 1 - elif name[-1] == "s" and name[:-1] in cls._ATTRS: - return name[:-1], name, 1 - elif name in ["week", "weeks"]: - return "week", "weeks", 1 - elif name in ["quarter", "quarters"]: - return "quarter", "months", 3 - else: - supported = ", ".join( - [ - "year(s)", - "month(s)", - "day(s)", - "hour(s)", - "minute(s)", - "second(s)", - "microsecond(s)", - "week(s)", - "quarter(s)", - ] - ) - raise ValueError( - f"Range or span over frame {name} not supported. Supported frames: {supported}." - ) - - @classmethod - def _get_iteration_params(cls, end: Any, limit: Optional[int]) -> Tuple[Any, int]: - """Sets default end and limit values for range method.""" - if end is None: - - if limit is None: - raise ValueError("One of 'end' or 'limit' is required.") - - return cls.max, limit - - else: - if limit is None: - return end, sys.maxsize - return end, limit - - @staticmethod - def _is_last_day_of_month(date: "Arrow") -> bool: - """Returns a boolean indicating whether the datetime is the last day of the month.""" - return date.day == calendar.monthrange(date.year, date.month)[1] - - -Arrow.min = Arrow.fromdatetime(dt_datetime.min) -Arrow.max = Arrow.fromdatetime(dt_datetime.max) diff --git a/.venv/Lib/site-packages/arrow/constants.py b/.venv/Lib/site-packages/arrow/constants.py deleted file mode 100644 index 53d163b..0000000 --- a/.venv/Lib/site-packages/arrow/constants.py +++ /dev/null @@ -1,177 +0,0 @@ -"""Constants used internally in arrow.""" - -import sys -from datetime import datetime - -if sys.version_info < (3, 8): # pragma: no cover - from typing_extensions import Final -else: - from typing import Final # pragma: no cover - -# datetime.max.timestamp() errors on Windows, so we must hardcode -# the highest possible datetime value that can output a timestamp. -# tl;dr platform-independent max timestamps are hard to form -# See: https://stackoverflow.com/q/46133223 -try: - # Get max timestamp. Works on POSIX-based systems like Linux and macOS, - # but will trigger an OverflowError, ValueError, or OSError on Windows - _MAX_TIMESTAMP = datetime.max.timestamp() -except (OverflowError, ValueError, OSError): # pragma: no cover - # Fallback for Windows and 32-bit systems if initial max timestamp call fails - # Must get max value of ctime on Windows based on architecture (x32 vs x64) - # https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/ctime-ctime32-ctime64-wctime-wctime32-wctime64 - # Note: this may occur on both 32-bit Linux systems (issue #930) along with Windows systems - is_64bits = sys.maxsize > 2**32 - _MAX_TIMESTAMP = ( - datetime(3000, 1, 1, 23, 59, 59, 999999).timestamp() - if is_64bits - else datetime(2038, 1, 1, 23, 59, 59, 999999).timestamp() - ) - -MAX_TIMESTAMP: Final[float] = _MAX_TIMESTAMP -MAX_TIMESTAMP_MS: Final[float] = MAX_TIMESTAMP * 1000 -MAX_TIMESTAMP_US: Final[float] = MAX_TIMESTAMP * 1_000_000 - -MAX_ORDINAL: Final[int] = datetime.max.toordinal() -MIN_ORDINAL: Final[int] = 1 - -DEFAULT_LOCALE: Final[str] = "en-us" - -# Supported dehumanize locales -DEHUMANIZE_LOCALES = { - "en", - "en-us", - "en-gb", - "en-au", - "en-be", - "en-jp", - "en-za", - "en-ca", - "en-ph", - "fr", - "fr-fr", - "fr-ca", - "it", - "it-it", - "es", - "es-es", - "el", - "el-gr", - "ja", - "ja-jp", - "se", - "se-fi", - "se-no", - "se-se", - "sv", - "sv-se", - "fi", - "fi-fi", - "zh", - "zh-cn", - "zh-tw", - "zh-hk", - "nl", - "nl-nl", - "be", - "be-by", - "pl", - "pl-pl", - "ru", - "ru-ru", - "af", - "bg", - "bg-bg", - "ua", - "uk", - "uk-ua", - "mk", - "mk-mk", - "de", - "de-de", - "de-ch", - "de-at", - "nb", - "nb-no", - "nn", - "nn-no", - "pt", - "pt-pt", - "pt-br", - "tl", - "tl-ph", - "vi", - "vi-vn", - "tr", - "tr-tr", - "az", - "az-az", - "da", - "da-dk", - "ml", - "hi", - "cs", - "cs-cz", - "sk", - "sk-sk", - "fa", - "fa-ir", - "mr", - "ca", - "ca-es", - "ca-ad", - "ca-fr", - "ca-it", - "eo", - "eo-xx", - "bn", - "bn-bd", - "bn-in", - "rm", - "rm-ch", - "ro", - "ro-ro", - "sl", - "sl-si", - "id", - "id-id", - "ne", - "ne-np", - "ee", - "et", - "sw", - "sw-ke", - "sw-tz", - "la", - "la-va", - "lt", - "lt-lt", - "ms", - "ms-my", - "ms-bn", - "or", - "or-in", - "lb", - "lb-lu", - "zu", - "zu-za", - "sq", - "sq-al", - "ta", - "ta-in", - "ta-lk", - "ur", - "ur-pk", - "ka", - "ka-ge", - "kk", - "kk-kz", - # "lo", - # "lo-la", - "am", - "am-et", - "hy-am", - "hy", - "uz", - "uz-uz", -} diff --git a/.venv/Lib/site-packages/arrow/factory.py b/.venv/Lib/site-packages/arrow/factory.py deleted file mode 100644 index aad4af8..0000000 --- a/.venv/Lib/site-packages/arrow/factory.py +++ /dev/null @@ -1,348 +0,0 @@ -""" -Implements the :class:`ArrowFactory ` class, -providing factory methods for common :class:`Arrow ` -construction scenarios. - -""" - - -import calendar -from datetime import date, datetime -from datetime import tzinfo as dt_tzinfo -from decimal import Decimal -from time import struct_time -from typing import Any, List, Optional, Tuple, Type, Union, overload - -from dateutil import tz as dateutil_tz - -from arrow import parser -from arrow.arrow import TZ_EXPR, Arrow -from arrow.constants import DEFAULT_LOCALE -from arrow.util import is_timestamp, iso_to_gregorian - - -class ArrowFactory: - """A factory for generating :class:`Arrow ` objects. - - :param type: (optional) the :class:`Arrow `-based class to construct from. - Defaults to :class:`Arrow `. - - """ - - type: Type[Arrow] - - def __init__(self, type: Type[Arrow] = Arrow) -> None: - self.type = type - - @overload - def get( - self, - *, - locale: str = DEFAULT_LOCALE, - tzinfo: Optional[TZ_EXPR] = None, - normalize_whitespace: bool = False, - ) -> Arrow: - ... # pragma: no cover - - @overload - def get( - self, - __obj: Union[ - Arrow, - datetime, - date, - struct_time, - dt_tzinfo, - int, - float, - str, - Tuple[int, int, int], - ], - *, - locale: str = DEFAULT_LOCALE, - tzinfo: Optional[TZ_EXPR] = None, - normalize_whitespace: bool = False, - ) -> Arrow: - ... # pragma: no cover - - @overload - def get( - self, - __arg1: Union[datetime, date], - __arg2: TZ_EXPR, - *, - locale: str = DEFAULT_LOCALE, - tzinfo: Optional[TZ_EXPR] = None, - normalize_whitespace: bool = False, - ) -> Arrow: - ... # pragma: no cover - - @overload - def get( - self, - __arg1: str, - __arg2: Union[str, List[str]], - *, - locale: str = DEFAULT_LOCALE, - tzinfo: Optional[TZ_EXPR] = None, - normalize_whitespace: bool = False, - ) -> Arrow: - ... # pragma: no cover - - def get(self, *args: Any, **kwargs: Any) -> Arrow: - """Returns an :class:`Arrow ` object based on flexible inputs. - - :param locale: (optional) a ``str`` specifying a locale for the parser. Defaults to 'en-us'. - :param tzinfo: (optional) a :ref:`timezone expression ` or tzinfo object. - Replaces the timezone unless using an input form that is explicitly UTC or specifies - the timezone in a positional argument. Defaults to UTC. - :param normalize_whitespace: (optional) a ``bool`` specifying whether or not to normalize - redundant whitespace (spaces, tabs, and newlines) in a datetime string before parsing. - Defaults to false. - - Usage:: - - >>> import arrow - - **No inputs** to get current UTC time:: - - >>> arrow.get() - - - **One** :class:`Arrow ` object, to get a copy. - - >>> arw = arrow.utcnow() - >>> arrow.get(arw) - - - **One** ``float`` or ``int``, convertible to a floating-point timestamp, to get - that timestamp in UTC:: - - >>> arrow.get(1367992474.293378) - - - >>> arrow.get(1367992474) - - - **One** ISO 8601-formatted ``str``, to parse it:: - - >>> arrow.get('2013-09-29T01:26:43.830580') - - - **One** ISO 8601-formatted ``str``, in basic format, to parse it:: - - >>> arrow.get('20160413T133656.456289') - - - **One** ``tzinfo``, to get the current time **converted** to that timezone:: - - >>> arrow.get(tz.tzlocal()) - - - **One** naive ``datetime``, to get that datetime in UTC:: - - >>> arrow.get(datetime(2013, 5, 5)) - - - **One** aware ``datetime``, to get that datetime:: - - >>> arrow.get(datetime(2013, 5, 5, tzinfo=tz.tzlocal())) - - - **One** naive ``date``, to get that date in UTC:: - - >>> arrow.get(date(2013, 5, 5)) - - - **One** time.struct time:: - - >>> arrow.get(gmtime(0)) - - - **One** iso calendar ``tuple``, to get that week date in UTC:: - - >>> arrow.get((2013, 18, 7)) - - - **Two** arguments, a naive or aware ``datetime``, and a replacement - :ref:`timezone expression `:: - - >>> arrow.get(datetime(2013, 5, 5), 'US/Pacific') - - - **Two** arguments, a naive ``date``, and a replacement - :ref:`timezone expression `:: - - >>> arrow.get(date(2013, 5, 5), 'US/Pacific') - - - **Two** arguments, both ``str``, to parse the first according to the format of the second:: - - >>> arrow.get('2013-05-05 12:30:45 America/Chicago', 'YYYY-MM-DD HH:mm:ss ZZZ') - - - **Two** arguments, first a ``str`` to parse and second a ``list`` of formats to try:: - - >>> arrow.get('2013-05-05 12:30:45', ['MM/DD/YYYY', 'YYYY-MM-DD HH:mm:ss']) - - - **Three or more** arguments, as for the direct constructor of an ``Arrow`` object:: - - >>> arrow.get(2013, 5, 5, 12, 30, 45) - - - """ - - arg_count = len(args) - locale = kwargs.pop("locale", DEFAULT_LOCALE) - tz = kwargs.get("tzinfo", None) - normalize_whitespace = kwargs.pop("normalize_whitespace", False) - - # if kwargs given, send to constructor unless only tzinfo provided - if len(kwargs) > 1: - arg_count = 3 - - # tzinfo kwarg is not provided - if len(kwargs) == 1 and tz is None: - arg_count = 3 - - # () -> now, @ tzinfo or utc - if arg_count == 0: - if isinstance(tz, str): - tz = parser.TzinfoParser.parse(tz) - return self.type.now(tzinfo=tz) - - if isinstance(tz, dt_tzinfo): - return self.type.now(tzinfo=tz) - - return self.type.utcnow() - - if arg_count == 1: - arg = args[0] - if isinstance(arg, Decimal): - arg = float(arg) - - # (None) -> raises an exception - if arg is None: - raise TypeError("Cannot parse argument of type None.") - - # try (int, float) -> from timestamp @ tzinfo - elif not isinstance(arg, str) and is_timestamp(arg): - if tz is None: - # set to UTC by default - tz = dateutil_tz.tzutc() - return self.type.fromtimestamp(arg, tzinfo=tz) - - # (Arrow) -> from the object's datetime @ tzinfo - elif isinstance(arg, Arrow): - return self.type.fromdatetime(arg.datetime, tzinfo=tz) - - # (datetime) -> from datetime @ tzinfo - elif isinstance(arg, datetime): - return self.type.fromdatetime(arg, tzinfo=tz) - - # (date) -> from date @ tzinfo - elif isinstance(arg, date): - return self.type.fromdate(arg, tzinfo=tz) - - # (tzinfo) -> now @ tzinfo - elif isinstance(arg, dt_tzinfo): - return self.type.now(tzinfo=arg) - - # (str) -> parse @ tzinfo - elif isinstance(arg, str): - dt = parser.DateTimeParser(locale).parse_iso(arg, normalize_whitespace) - return self.type.fromdatetime(dt, tzinfo=tz) - - # (struct_time) -> from struct_time - elif isinstance(arg, struct_time): - return self.type.utcfromtimestamp(calendar.timegm(arg)) - - # (iso calendar) -> convert then from date @ tzinfo - elif isinstance(arg, tuple) and len(arg) == 3: - d = iso_to_gregorian(*arg) - return self.type.fromdate(d, tzinfo=tz) - - else: - raise TypeError(f"Cannot parse single argument of type {type(arg)!r}.") - - elif arg_count == 2: - - arg_1, arg_2 = args[0], args[1] - - if isinstance(arg_1, datetime): - - # (datetime, tzinfo/str) -> fromdatetime @ tzinfo - if isinstance(arg_2, (dt_tzinfo, str)): - return self.type.fromdatetime(arg_1, tzinfo=arg_2) - else: - raise TypeError( - f"Cannot parse two arguments of types 'datetime', {type(arg_2)!r}." - ) - - elif isinstance(arg_1, date): - - # (date, tzinfo/str) -> fromdate @ tzinfo - if isinstance(arg_2, (dt_tzinfo, str)): - return self.type.fromdate(arg_1, tzinfo=arg_2) - else: - raise TypeError( - f"Cannot parse two arguments of types 'date', {type(arg_2)!r}." - ) - - # (str, format) -> parse @ tzinfo - elif isinstance(arg_1, str) and isinstance(arg_2, (str, list)): - dt = parser.DateTimeParser(locale).parse( - args[0], args[1], normalize_whitespace - ) - return self.type.fromdatetime(dt, tzinfo=tz) - - else: - raise TypeError( - f"Cannot parse two arguments of types {type(arg_1)!r} and {type(arg_2)!r}." - ) - - # 3+ args -> datetime-like via constructor - else: - return self.type(*args, **kwargs) - - def utcnow(self) -> Arrow: - """Returns an :class:`Arrow ` object, representing "now" in UTC time. - - Usage:: - - >>> import arrow - >>> arrow.utcnow() - - """ - - return self.type.utcnow() - - def now(self, tz: Optional[TZ_EXPR] = None) -> Arrow: - """Returns an :class:`Arrow ` object, representing "now" in the given - timezone. - - :param tz: (optional) A :ref:`timezone expression `. Defaults to local time. - - Usage:: - - >>> import arrow - >>> arrow.now() - - - >>> arrow.now('US/Pacific') - - - >>> arrow.now('+02:00') - - - >>> arrow.now('local') - - """ - - if tz is None: - tz = dateutil_tz.tzlocal() - elif not isinstance(tz, dt_tzinfo): - tz = parser.TzinfoParser.parse(tz) - - return self.type.now(tz) diff --git a/.venv/Lib/site-packages/arrow/formatter.py b/.venv/Lib/site-packages/arrow/formatter.py deleted file mode 100644 index 728bea1..0000000 --- a/.venv/Lib/site-packages/arrow/formatter.py +++ /dev/null @@ -1,152 +0,0 @@ -"""Provides the :class:`Arrow ` class, an improved formatter for datetimes.""" - -import re -import sys -from datetime import datetime, timedelta -from typing import Optional, Pattern, cast - -from dateutil import tz as dateutil_tz - -from arrow import locales -from arrow.constants import DEFAULT_LOCALE - -if sys.version_info < (3, 8): # pragma: no cover - from typing_extensions import Final -else: - from typing import Final # pragma: no cover - - -FORMAT_ATOM: Final[str] = "YYYY-MM-DD HH:mm:ssZZ" -FORMAT_COOKIE: Final[str] = "dddd, DD-MMM-YYYY HH:mm:ss ZZZ" -FORMAT_RFC822: Final[str] = "ddd, DD MMM YY HH:mm:ss Z" -FORMAT_RFC850: Final[str] = "dddd, DD-MMM-YY HH:mm:ss ZZZ" -FORMAT_RFC1036: Final[str] = "ddd, DD MMM YY HH:mm:ss Z" -FORMAT_RFC1123: Final[str] = "ddd, DD MMM YYYY HH:mm:ss Z" -FORMAT_RFC2822: Final[str] = "ddd, DD MMM YYYY HH:mm:ss Z" -FORMAT_RFC3339: Final[str] = "YYYY-MM-DD HH:mm:ssZZ" -FORMAT_RSS: Final[str] = "ddd, DD MMM YYYY HH:mm:ss Z" -FORMAT_W3C: Final[str] = "YYYY-MM-DD HH:mm:ssZZ" - - -class DateTimeFormatter: - - # This pattern matches characters enclosed in square brackets are matched as - # an atomic group. For more info on atomic groups and how to they are - # emulated in Python's re library, see https://stackoverflow.com/a/13577411/2701578 - - _FORMAT_RE: Final[Pattern[str]] = re.compile( - r"(\[(?:(?=(?P[^]]))(?P=literal))*\]|YYY?Y?|MM?M?M?|Do|DD?D?D?|d?dd?d?|HH?|hh?|mm?|ss?|SS?S?S?S?S?|ZZ?Z?|a|A|X|x|W)" - ) - - locale: locales.Locale - - def __init__(self, locale: str = DEFAULT_LOCALE) -> None: - - self.locale = locales.get_locale(locale) - - def format(cls, dt: datetime, fmt: str) -> str: - - # FIXME: _format_token() is nullable - return cls._FORMAT_RE.sub( - lambda m: cast(str, cls._format_token(dt, m.group(0))), fmt - ) - - def _format_token(self, dt: datetime, token: Optional[str]) -> Optional[str]: - - if token and token.startswith("[") and token.endswith("]"): - return token[1:-1] - - if token == "YYYY": - return self.locale.year_full(dt.year) - if token == "YY": - return self.locale.year_abbreviation(dt.year) - - if token == "MMMM": - return self.locale.month_name(dt.month) - if token == "MMM": - return self.locale.month_abbreviation(dt.month) - if token == "MM": - return f"{dt.month:02d}" - if token == "M": - return f"{dt.month}" - - if token == "DDDD": - return f"{dt.timetuple().tm_yday:03d}" - if token == "DDD": - return f"{dt.timetuple().tm_yday}" - if token == "DD": - return f"{dt.day:02d}" - if token == "D": - return f"{dt.day}" - - if token == "Do": - return self.locale.ordinal_number(dt.day) - - if token == "dddd": - return self.locale.day_name(dt.isoweekday()) - if token == "ddd": - return self.locale.day_abbreviation(dt.isoweekday()) - if token == "d": - return f"{dt.isoweekday()}" - - if token == "HH": - return f"{dt.hour:02d}" - if token == "H": - return f"{dt.hour}" - if token == "hh": - return f"{dt.hour if 0 < dt.hour < 13 else abs(dt.hour - 12):02d}" - if token == "h": - return f"{dt.hour if 0 < dt.hour < 13 else abs(dt.hour - 12)}" - - if token == "mm": - return f"{dt.minute:02d}" - if token == "m": - return f"{dt.minute}" - - if token == "ss": - return f"{dt.second:02d}" - if token == "s": - return f"{dt.second}" - - if token == "SSSSSS": - return f"{dt.microsecond:06d}" - if token == "SSSSS": - return f"{dt.microsecond // 10:05d}" - if token == "SSSS": - return f"{dt.microsecond // 100:04d}" - if token == "SSS": - return f"{dt.microsecond // 1000:03d}" - if token == "SS": - return f"{dt.microsecond // 10000:02d}" - if token == "S": - return f"{dt.microsecond // 100000}" - - if token == "X": - return f"{dt.timestamp()}" - - if token == "x": - return f"{dt.timestamp() * 1_000_000:.0f}" - - if token == "ZZZ": - return dt.tzname() - - if token in ["ZZ", "Z"]: - separator = ":" if token == "ZZ" else "" - tz = dateutil_tz.tzutc() if dt.tzinfo is None else dt.tzinfo - # `dt` must be aware object. Otherwise, this line will raise AttributeError - # https://github.com/arrow-py/arrow/pull/883#discussion_r529866834 - # datetime awareness: https://docs.python.org/3/library/datetime.html#aware-and-naive-objects - total_minutes = int(cast(timedelta, tz.utcoffset(dt)).total_seconds() / 60) - - sign = "+" if total_minutes >= 0 else "-" - total_minutes = abs(total_minutes) - hour, minute = divmod(total_minutes, 60) - - return f"{sign}{hour:02d}{separator}{minute:02d}" - - if token in ("a", "A"): - return self.locale.meridian(dt.hour, token) - - if token == "W": - year, week, day = dt.isocalendar() - return f"{year}-W{week:02d}-{day}" diff --git a/.venv/Lib/site-packages/arrow/locales.py b/.venv/Lib/site-packages/arrow/locales.py deleted file mode 100644 index 3627497..0000000 --- a/.venv/Lib/site-packages/arrow/locales.py +++ /dev/null @@ -1,6475 +0,0 @@ -"""Provides internationalization for arrow in over 60 languages and dialects.""" - -import sys -from math import trunc -from typing import ( - Any, - ClassVar, - Dict, - List, - Mapping, - Optional, - Sequence, - Tuple, - Type, - Union, - cast, -) - -if sys.version_info < (3, 8): # pragma: no cover - from typing_extensions import Literal -else: - from typing import Literal # pragma: no cover - -TimeFrameLiteral = Literal[ - "now", - "second", - "seconds", - "minute", - "minutes", - "hour", - "hours", - "day", - "days", - "week", - "weeks", - "month", - "months", - "quarter", - "quarters", - "year", - "years", -] - -_TimeFrameElements = Union[ - str, Sequence[str], Mapping[str, str], Mapping[str, Sequence[str]] -] - -_locale_map: Dict[str, Type["Locale"]] = {} - - -def get_locale(name: str) -> "Locale": - """Returns an appropriate :class:`Locale ` - corresponding to an input locale name. - - :param name: the name of the locale. - - """ - - normalized_locale_name = name.lower().replace("_", "-") - locale_cls = _locale_map.get(normalized_locale_name) - - if locale_cls is None: - raise ValueError(f"Unsupported locale {normalized_locale_name!r}.") - - return locale_cls() - - -def get_locale_by_class_name(name: str) -> "Locale": - """Returns an appropriate :class:`Locale ` - corresponding to an locale class name. - - :param name: the name of the locale class. - - """ - locale_cls: Optional[Type[Locale]] = globals().get(name) - - if locale_cls is None: - raise ValueError(f"Unsupported locale {name!r}.") - - return locale_cls() - - -class Locale: - """Represents locale-specific data and functionality.""" - - names: ClassVar[List[str]] = [] - - timeframes: ClassVar[Mapping[TimeFrameLiteral, _TimeFrameElements]] = { - "now": "", - "second": "", - "seconds": "", - "minute": "", - "minutes": "", - "hour": "", - "hours": "", - "day": "", - "days": "", - "week": "", - "weeks": "", - "month": "", - "months": "", - "quarter": "", - "quarters": "", - "year": "", - "years": "", - } - - meridians: ClassVar[Dict[str, str]] = {"am": "", "pm": "", "AM": "", "PM": ""} - - past: ClassVar[str] - future: ClassVar[str] - and_word: ClassVar[Optional[str]] = None - - month_names: ClassVar[List[str]] = [] - month_abbreviations: ClassVar[List[str]] = [] - - day_names: ClassVar[List[str]] = [] - day_abbreviations: ClassVar[List[str]] = [] - - ordinal_day_re: ClassVar[str] = r"(\d+)" - - _month_name_to_ordinal: Optional[Dict[str, int]] - - def __init_subclass__(cls, **kwargs: Any) -> None: - for locale_name in cls.names: - if locale_name in _locale_map: - raise LookupError(f"Duplicated locale name: {locale_name}") - - _locale_map[locale_name.lower().replace("_", "-")] = cls - - def __init__(self) -> None: - - self._month_name_to_ordinal = None - - def describe( - self, - timeframe: TimeFrameLiteral, - delta: Union[float, int] = 0, - only_distance: bool = False, - ) -> str: - """Describes a delta within a timeframe in plain language. - - :param timeframe: a string representing a timeframe. - :param delta: a quantity representing a delta in a timeframe. - :param only_distance: return only distance eg: "11 seconds" without "in" or "ago" keywords - """ - - humanized = self._format_timeframe(timeframe, trunc(delta)) - if not only_distance: - humanized = self._format_relative(humanized, timeframe, delta) - - return humanized - - def describe_multi( - self, - timeframes: Sequence[Tuple[TimeFrameLiteral, Union[int, float]]], - only_distance: bool = False, - ) -> str: - """Describes a delta within multiple timeframes in plain language. - - :param timeframes: a list of string, quantity pairs each representing a timeframe and delta. - :param only_distance: return only distance eg: "2 hours and 11 seconds" without "in" or "ago" keywords - """ - - parts = [ - self._format_timeframe(timeframe, trunc(delta)) - for timeframe, delta in timeframes - ] - if self.and_word: - parts.insert(-1, self.and_word) - humanized = " ".join(parts) - - if not only_distance: - # Needed to determine the correct relative string to use - timeframe_value = 0 - - for _unit_name, unit_value in timeframes: - if trunc(unit_value) != 0: - timeframe_value = trunc(unit_value) - break - - # Note it doesn't matter the timeframe unit we use on the call, only the value - humanized = self._format_relative(humanized, "seconds", timeframe_value) - - return humanized - - def day_name(self, day: int) -> str: - """Returns the day name for a specified day of the week. - - :param day: the ``int`` day of the week (1-7). - - """ - - return self.day_names[day] - - def day_abbreviation(self, day: int) -> str: - """Returns the day abbreviation for a specified day of the week. - - :param day: the ``int`` day of the week (1-7). - - """ - - return self.day_abbreviations[day] - - def month_name(self, month: int) -> str: - """Returns the month name for a specified month of the year. - - :param month: the ``int`` month of the year (1-12). - - """ - - return self.month_names[month] - - def month_abbreviation(self, month: int) -> str: - """Returns the month abbreviation for a specified month of the year. - - :param month: the ``int`` month of the year (1-12). - - """ - - return self.month_abbreviations[month] - - def month_number(self, name: str) -> Optional[int]: - """Returns the month number for a month specified by name or abbreviation. - - :param name: the month name or abbreviation. - - """ - - if self._month_name_to_ordinal is None: - self._month_name_to_ordinal = self._name_to_ordinal(self.month_names) - self._month_name_to_ordinal.update( - self._name_to_ordinal(self.month_abbreviations) - ) - - return self._month_name_to_ordinal.get(name) - - def year_full(self, year: int) -> str: - """Returns the year for specific locale if available - - :param year: the ``int`` year (4-digit) - """ - return f"{year:04d}" - - def year_abbreviation(self, year: int) -> str: - """Returns the year for specific locale if available - - :param year: the ``int`` year (4-digit) - """ - return f"{year:04d}"[2:] - - def meridian(self, hour: int, token: Any) -> Optional[str]: - """Returns the meridian indicator for a specified hour and format token. - - :param hour: the ``int`` hour of the day. - :param token: the format token. - """ - - if token == "a": - return self.meridians["am"] if hour < 12 else self.meridians["pm"] - if token == "A": - return self.meridians["AM"] if hour < 12 else self.meridians["PM"] - return None - - def ordinal_number(self, n: int) -> str: - """Returns the ordinal format of a given integer - - :param n: an integer - """ - return self._ordinal_number(n) - - def _ordinal_number(self, n: int) -> str: - return f"{n}" - - def _name_to_ordinal(self, lst: Sequence[str]) -> Dict[str, int]: - return {elem.lower(): i for i, elem in enumerate(lst[1:], 1)} - - def _format_timeframe(self, timeframe: TimeFrameLiteral, delta: int) -> str: - # TODO: remove cast - return cast(str, self.timeframes[timeframe]).format(trunc(abs(delta))) - - def _format_relative( - self, - humanized: str, - timeframe: TimeFrameLiteral, - delta: Union[float, int], - ) -> str: - - if timeframe == "now": - return humanized - - direction = self.past if delta < 0 else self.future - - return direction.format(humanized) - - -class EnglishLocale(Locale): - names = [ - "en", - "en-us", - "en-gb", - "en-au", - "en-be", - "en-jp", - "en-za", - "en-ca", - "en-ph", - ] - - past = "{0} ago" - future = "in {0}" - and_word = "and" - - timeframes = { - "now": "just now", - "second": "a second", - "seconds": "{0} seconds", - "minute": "a minute", - "minutes": "{0} minutes", - "hour": "an hour", - "hours": "{0} hours", - "day": "a day", - "days": "{0} days", - "week": "a week", - "weeks": "{0} weeks", - "month": "a month", - "months": "{0} months", - "quarter": "a quarter", - "quarters": "{0} quarters", - "year": "a year", - "years": "{0} years", - } - - meridians = {"am": "am", "pm": "pm", "AM": "AM", "PM": "PM"} - - month_names = [ - "", - "January", - "February", - "March", - "April", - "May", - "June", - "July", - "August", - "September", - "October", - "November", - "December", - ] - month_abbreviations = [ - "", - "Jan", - "Feb", - "Mar", - "Apr", - "May", - "Jun", - "Jul", - "Aug", - "Sep", - "Oct", - "Nov", - "Dec", - ] - - day_names = [ - "", - "Monday", - "Tuesday", - "Wednesday", - "Thursday", - "Friday", - "Saturday", - "Sunday", - ] - day_abbreviations = ["", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] - - ordinal_day_re = r"((?P[2-3]?1(?=st)|[2-3]?2(?=nd)|[2-3]?3(?=rd)|[1-3]?[04-9](?=th)|1[1-3](?=th))(st|nd|rd|th))" - - def _ordinal_number(self, n: int) -> str: - if n % 100 not in (11, 12, 13): - remainder = abs(n) % 10 - if remainder == 1: - return f"{n}st" - elif remainder == 2: - return f"{n}nd" - elif remainder == 3: - return f"{n}rd" - return f"{n}th" - - def describe( - self, - timeframe: TimeFrameLiteral, - delta: Union[int, float] = 0, - only_distance: bool = False, - ) -> str: - """Describes a delta within a timeframe in plain language. - - :param timeframe: a string representing a timeframe. - :param delta: a quantity representing a delta in a timeframe. - :param only_distance: return only distance eg: "11 seconds" without "in" or "ago" keywords - """ - - humanized = super().describe(timeframe, delta, only_distance) - if only_distance and timeframe == "now": - humanized = "instantly" - - return humanized - - -class ItalianLocale(Locale): - names = ["it", "it-it"] - past = "{0} fa" - future = "tra {0}" - and_word = "e" - - timeframes = { - "now": "adesso", - "second": "un secondo", - "seconds": "{0} qualche secondo", - "minute": "un minuto", - "minutes": "{0} minuti", - "hour": "un'ora", - "hours": "{0} ore", - "day": "un giorno", - "days": "{0} giorni", - "week": "una settimana,", - "weeks": "{0} settimane", - "month": "un mese", - "months": "{0} mesi", - "year": "un anno", - "years": "{0} anni", - } - - month_names = [ - "", - "gennaio", - "febbraio", - "marzo", - "aprile", - "maggio", - "giugno", - "luglio", - "agosto", - "settembre", - "ottobre", - "novembre", - "dicembre", - ] - month_abbreviations = [ - "", - "gen", - "feb", - "mar", - "apr", - "mag", - "giu", - "lug", - "ago", - "set", - "ott", - "nov", - "dic", - ] - - day_names = [ - "", - "lunedì", - "martedì", - "mercoledì", - "giovedì", - "venerdì", - "sabato", - "domenica", - ] - day_abbreviations = ["", "lun", "mar", "mer", "gio", "ven", "sab", "dom"] - - ordinal_day_re = r"((?P[1-3]?[0-9](?=[ºª]))[ºª])" - - def _ordinal_number(self, n: int) -> str: - return f"{n}º" - - -class SpanishLocale(Locale): - names = ["es", "es-es"] - past = "hace {0}" - future = "en {0}" - and_word = "y" - - timeframes = { - "now": "ahora", - "second": "un segundo", - "seconds": "{0} segundos", - "minute": "un minuto", - "minutes": "{0} minutos", - "hour": "una hora", - "hours": "{0} horas", - "day": "un día", - "days": "{0} días", - "week": "una semana", - "weeks": "{0} semanas", - "month": "un mes", - "months": "{0} meses", - "year": "un año", - "years": "{0} años", - } - - meridians = {"am": "am", "pm": "pm", "AM": "AM", "PM": "PM"} - - month_names = [ - "", - "enero", - "febrero", - "marzo", - "abril", - "mayo", - "junio", - "julio", - "agosto", - "septiembre", - "octubre", - "noviembre", - "diciembre", - ] - month_abbreviations = [ - "", - "ene", - "feb", - "mar", - "abr", - "may", - "jun", - "jul", - "ago", - "sep", - "oct", - "nov", - "dic", - ] - - day_names = [ - "", - "lunes", - "martes", - "miércoles", - "jueves", - "viernes", - "sábado", - "domingo", - ] - day_abbreviations = ["", "lun", "mar", "mie", "jue", "vie", "sab", "dom"] - - ordinal_day_re = r"((?P[1-3]?[0-9](?=[ºª]))[ºª])" - - def _ordinal_number(self, n: int) -> str: - return f"{n}º" - - -class FrenchBaseLocale(Locale): - past = "il y a {0}" - future = "dans {0}" - and_word = "et" - - timeframes = { - "now": "maintenant", - "second": "une seconde", - "seconds": "{0} secondes", - "minute": "une minute", - "minutes": "{0} minutes", - "hour": "une heure", - "hours": "{0} heures", - "day": "un jour", - "days": "{0} jours", - "week": "une semaine", - "weeks": "{0} semaines", - "month": "un mois", - "months": "{0} mois", - "year": "un an", - "years": "{0} ans", - } - - month_names = [ - "", - "janvier", - "février", - "mars", - "avril", - "mai", - "juin", - "juillet", - "août", - "septembre", - "octobre", - "novembre", - "décembre", - ] - - day_names = [ - "", - "lundi", - "mardi", - "mercredi", - "jeudi", - "vendredi", - "samedi", - "dimanche", - ] - day_abbreviations = ["", "lun", "mar", "mer", "jeu", "ven", "sam", "dim"] - - ordinal_day_re = ( - r"((?P\b1(?=er\b)|[1-3]?[02-9](?=e\b)|[1-3]1(?=e\b))(er|e)\b)" - ) - - def _ordinal_number(self, n: int) -> str: - if abs(n) == 1: - return f"{n}er" - return f"{n}e" - - -class FrenchLocale(FrenchBaseLocale, Locale): - names = ["fr", "fr-fr"] - - month_abbreviations = [ - "", - "janv", - "févr", - "mars", - "avr", - "mai", - "juin", - "juil", - "août", - "sept", - "oct", - "nov", - "déc", - ] - - -class FrenchCanadianLocale(FrenchBaseLocale, Locale): - names = ["fr-ca"] - - month_abbreviations = [ - "", - "janv", - "févr", - "mars", - "avr", - "mai", - "juin", - "juill", - "août", - "sept", - "oct", - "nov", - "déc", - ] - - -class GreekLocale(Locale): - names = ["el", "el-gr"] - - past = "{0} πριν" - future = "σε {0}" - and_word = "και" - - timeframes = { - "now": "τώρα", - "second": "ένα δεύτερο", - "seconds": "{0} δευτερόλεπτα", - "minute": "ένα λεπτό", - "minutes": "{0} λεπτά", - "hour": "μία ώρα", - "hours": "{0} ώρες", - "day": "μία μέρα", - "days": "{0} μέρες", - "week": "μία εβδομάδα", - "weeks": "{0} εβδομάδες", - "month": "ένα μήνα", - "months": "{0} μήνες", - "year": "ένα χρόνο", - "years": "{0} χρόνια", - } - - month_names = [ - "", - "Ιανουαρίου", - "Φεβρουαρίου", - "Μαρτίου", - "Απριλίου", - "Μαΐου", - "Ιουνίου", - "Ιουλίου", - "Αυγούστου", - "Σεπτεμβρίου", - "Οκτωβρίου", - "Νοεμβρίου", - "Δεκεμβρίου", - ] - month_abbreviations = [ - "", - "Ιαν", - "Φεβ", - "Μαρ", - "Απρ", - "Μαϊ", - "Ιον", - "Ιολ", - "Αυγ", - "Σεπ", - "Οκτ", - "Νοε", - "Δεκ", - ] - - day_names = [ - "", - "Δευτέρα", - "Τρίτη", - "Τετάρτη", - "Πέμπτη", - "Παρασκευή", - "Σάββατο", - "Κυριακή", - ] - day_abbreviations = ["", "Δευ", "Τρι", "Τετ", "Πεμ", "Παρ", "Σαβ", "Κυρ"] - - -class JapaneseLocale(Locale): - names = ["ja", "ja-jp"] - - past = "{0}前" - future = "{0}後" - and_word = "" - - timeframes = { - "now": "現在", - "second": "1秒", - "seconds": "{0}秒", - "minute": "1分", - "minutes": "{0}分", - "hour": "1時間", - "hours": "{0}時間", - "day": "1日", - "days": "{0}日", - "week": "1週間", - "weeks": "{0}週間", - "month": "1ヶ月", - "months": "{0}ヶ月", - "year": "1年", - "years": "{0}年", - } - - month_names = [ - "", - "1月", - "2月", - "3月", - "4月", - "5月", - "6月", - "7月", - "8月", - "9月", - "10月", - "11月", - "12月", - ] - month_abbreviations = [ - "", - " 1", - " 2", - " 3", - " 4", - " 5", - " 6", - " 7", - " 8", - " 9", - "10", - "11", - "12", - ] - - day_names = ["", "月曜日", "火曜日", "水曜日", "木曜日", "金曜日", "土曜日", "日曜日"] - day_abbreviations = ["", "月", "火", "水", "木", "金", "土", "日"] - - -class SwedishLocale(Locale): - names = ["sv", "sv-se"] - - past = "för {0} sen" - future = "om {0}" - and_word = "och" - - timeframes = { - "now": "just nu", - "second": "en sekund", - "seconds": "{0} sekunder", - "minute": "en minut", - "minutes": "{0} minuter", - "hour": "en timme", - "hours": "{0} timmar", - "day": "en dag", - "days": "{0} dagar", - "week": "en vecka", - "weeks": "{0} veckor", - "month": "en månad", - "months": "{0} månader", - "year": "ett år", - "years": "{0} år", - } - - month_names = [ - "", - "januari", - "februari", - "mars", - "april", - "maj", - "juni", - "juli", - "augusti", - "september", - "oktober", - "november", - "december", - ] - month_abbreviations = [ - "", - "jan", - "feb", - "mar", - "apr", - "maj", - "jun", - "jul", - "aug", - "sep", - "okt", - "nov", - "dec", - ] - - day_names = [ - "", - "måndag", - "tisdag", - "onsdag", - "torsdag", - "fredag", - "lördag", - "söndag", - ] - day_abbreviations = ["", "mån", "tis", "ons", "tor", "fre", "lör", "sön"] - - -class FinnishLocale(Locale): - names = ["fi", "fi-fi"] - - # The finnish grammar is very complex, and its hard to convert - # 1-to-1 to something like English. - - past = "{0} sitten" - future = "{0} kuluttua" - - timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = { - "now": "juuri nyt", - "second": "sekunti", - "seconds": {"past": "{0} muutama sekunti", "future": "{0} muutaman sekunnin"}, - "minute": {"past": "minuutti", "future": "minuutin"}, - "minutes": {"past": "{0} minuuttia", "future": "{0} minuutin"}, - "hour": {"past": "tunti", "future": "tunnin"}, - "hours": {"past": "{0} tuntia", "future": "{0} tunnin"}, - "day": "päivä", - "days": {"past": "{0} päivää", "future": "{0} päivän"}, - "month": {"past": "kuukausi", "future": "kuukauden"}, - "months": {"past": "{0} kuukautta", "future": "{0} kuukauden"}, - "year": {"past": "vuosi", "future": "vuoden"}, - "years": {"past": "{0} vuotta", "future": "{0} vuoden"}, - } - - # Months and days are lowercase in Finnish - month_names = [ - "", - "tammikuu", - "helmikuu", - "maaliskuu", - "huhtikuu", - "toukokuu", - "kesäkuu", - "heinäkuu", - "elokuu", - "syyskuu", - "lokakuu", - "marraskuu", - "joulukuu", - ] - - month_abbreviations = [ - "", - "tammi", - "helmi", - "maalis", - "huhti", - "touko", - "kesä", - "heinä", - "elo", - "syys", - "loka", - "marras", - "joulu", - ] - - day_names = [ - "", - "maanantai", - "tiistai", - "keskiviikko", - "torstai", - "perjantai", - "lauantai", - "sunnuntai", - ] - - day_abbreviations = ["", "ma", "ti", "ke", "to", "pe", "la", "su"] - - def _format_timeframe(self, timeframe: TimeFrameLiteral, delta: int) -> str: - form = self.timeframes[timeframe] - - if isinstance(form, Mapping): - if delta < 0: - form = form["past"] - else: - form = form["future"] - - return form.format(abs(delta)) - - def _ordinal_number(self, n: int) -> str: - return f"{n}." - - -class ChineseCNLocale(Locale): - names = ["zh", "zh-cn"] - - past = "{0}前" - future = "{0}后" - - timeframes = { - "now": "刚才", - "second": "1秒", - "seconds": "{0}秒", - "minute": "1分钟", - "minutes": "{0}分钟", - "hour": "1小时", - "hours": "{0}小时", - "day": "1天", - "days": "{0}天", - "week": "1周", - "weeks": "{0}周", - "month": "1个月", - "months": "{0}个月", - "year": "1年", - "years": "{0}年", - } - - month_names = [ - "", - "一月", - "二月", - "三月", - "四月", - "五月", - "六月", - "七月", - "八月", - "九月", - "十月", - "十一月", - "十二月", - ] - month_abbreviations = [ - "", - " 1", - " 2", - " 3", - " 4", - " 5", - " 6", - " 7", - " 8", - " 9", - "10", - "11", - "12", - ] - - day_names = ["", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"] - day_abbreviations = ["", "一", "二", "三", "四", "五", "六", "日"] - - -class ChineseTWLocale(Locale): - names = ["zh-tw"] - - past = "{0}前" - future = "{0}後" - and_word = "和" - - timeframes = { - "now": "剛才", - "second": "1秒", - "seconds": "{0}秒", - "minute": "1分鐘", - "minutes": "{0}分鐘", - "hour": "1小時", - "hours": "{0}小時", - "day": "1天", - "days": "{0}天", - "week": "1週", - "weeks": "{0}週", - "month": "1個月", - "months": "{0}個月", - "year": "1年", - "years": "{0}年", - } - - month_names = [ - "", - "1月", - "2月", - "3月", - "4月", - "5月", - "6月", - "7月", - "8月", - "9月", - "10月", - "11月", - "12月", - ] - month_abbreviations = [ - "", - " 1", - " 2", - " 3", - " 4", - " 5", - " 6", - " 7", - " 8", - " 9", - "10", - "11", - "12", - ] - - day_names = ["", "週一", "週二", "週三", "週四", "週五", "週六", "週日"] - day_abbreviations = ["", "一", "二", "三", "四", "五", "六", "日"] - - -class HongKongLocale(Locale): - names = ["zh-hk"] - - past = "{0}前" - future = "{0}後" - - timeframes = { - "now": "剛才", - "second": "1秒", - "seconds": "{0}秒", - "minute": "1分鐘", - "minutes": "{0}分鐘", - "hour": "1小時", - "hours": "{0}小時", - "day": "1天", - "days": "{0}天", - "week": "1星期", - "weeks": "{0}星期", - "month": "1個月", - "months": "{0}個月", - "year": "1年", - "years": "{0}年", - } - - month_names = [ - "", - "1月", - "2月", - "3月", - "4月", - "5月", - "6月", - "7月", - "8月", - "9月", - "10月", - "11月", - "12月", - ] - month_abbreviations = [ - "", - " 1", - " 2", - " 3", - " 4", - " 5", - " 6", - " 7", - " 8", - " 9", - "10", - "11", - "12", - ] - - day_names = ["", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"] - day_abbreviations = ["", "一", "二", "三", "四", "五", "六", "日"] - - -class KoreanLocale(Locale): - names = ["ko", "ko-kr"] - - past = "{0} 전" - future = "{0} 후" - - timeframes = { - "now": "지금", - "second": "1초", - "seconds": "{0}초", - "minute": "1분", - "minutes": "{0}분", - "hour": "한시간", - "hours": "{0}시간", - "day": "하루", - "days": "{0}일", - "week": "1주", - "weeks": "{0}주", - "month": "한달", - "months": "{0}개월", - "year": "1년", - "years": "{0}년", - } - - special_dayframes = { - -3: "그끄제", - -2: "그제", - -1: "어제", - 1: "내일", - 2: "모레", - 3: "글피", - 4: "그글피", - } - - special_yearframes = {-2: "제작년", -1: "작년", 1: "내년", 2: "내후년"} - - month_names = [ - "", - "1월", - "2월", - "3월", - "4월", - "5월", - "6월", - "7월", - "8월", - "9월", - "10월", - "11월", - "12월", - ] - month_abbreviations = [ - "", - " 1", - " 2", - " 3", - " 4", - " 5", - " 6", - " 7", - " 8", - " 9", - "10", - "11", - "12", - ] - - day_names = ["", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일", "일요일"] - day_abbreviations = ["", "월", "화", "수", "목", "금", "토", "일"] - - def _ordinal_number(self, n: int) -> str: - ordinals = ["0", "첫", "두", "세", "네", "다섯", "여섯", "일곱", "여덟", "아홉", "열"] - if n < len(ordinals): - return f"{ordinals[n]}번째" - return f"{n}번째" - - def _format_relative( - self, - humanized: str, - timeframe: TimeFrameLiteral, - delta: Union[float, int], - ) -> str: - if timeframe in ("day", "days"): - special = self.special_dayframes.get(int(delta)) - if special: - return special - elif timeframe in ("year", "years"): - special = self.special_yearframes.get(int(delta)) - if special: - return special - - return super()._format_relative(humanized, timeframe, delta) - - -# derived locale types & implementations. -class DutchLocale(Locale): - names = ["nl", "nl-nl"] - - past = "{0} geleden" - future = "over {0}" - - timeframes = { - "now": "nu", - "second": "een seconde", - "seconds": "{0} seconden", - "minute": "een minuut", - "minutes": "{0} minuten", - "hour": "een uur", - "hours": "{0} uur", - "day": "een dag", - "days": "{0} dagen", - "week": "een week", - "weeks": "{0} weken", - "month": "een maand", - "months": "{0} maanden", - "year": "een jaar", - "years": "{0} jaar", - } - - # In Dutch names of months and days are not starting with a capital letter - # like in the English language. - month_names = [ - "", - "januari", - "februari", - "maart", - "april", - "mei", - "juni", - "juli", - "augustus", - "september", - "oktober", - "november", - "december", - ] - month_abbreviations = [ - "", - "jan", - "feb", - "mrt", - "apr", - "mei", - "jun", - "jul", - "aug", - "sep", - "okt", - "nov", - "dec", - ] - - day_names = [ - "", - "maandag", - "dinsdag", - "woensdag", - "donderdag", - "vrijdag", - "zaterdag", - "zondag", - ] - day_abbreviations = ["", "ma", "di", "wo", "do", "vr", "za", "zo"] - - -class SlavicBaseLocale(Locale): - timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] - - def _format_timeframe(self, timeframe: TimeFrameLiteral, delta: int) -> str: - form = self.timeframes[timeframe] - delta = abs(delta) - - if isinstance(form, Mapping): - if delta % 10 == 1 and delta % 100 != 11: - form = form["singular"] - elif 2 <= delta % 10 <= 4 and (delta % 100 < 10 or delta % 100 >= 20): - form = form["dual"] - else: - form = form["plural"] - - return form.format(delta) - - -class BelarusianLocale(SlavicBaseLocale): - names = ["be", "be-by"] - - past = "{0} таму" - future = "праз {0}" - - timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = { - "now": "зараз", - "second": "секунду", - "seconds": "{0} некалькі секунд", - "minute": "хвіліну", - "minutes": { - "singular": "{0} хвіліну", - "dual": "{0} хвіліны", - "plural": "{0} хвілін", - }, - "hour": "гадзіну", - "hours": { - "singular": "{0} гадзіну", - "dual": "{0} гадзіны", - "plural": "{0} гадзін", - }, - "day": "дзень", - "days": {"singular": "{0} дзень", "dual": "{0} дні", "plural": "{0} дзён"}, - "month": "месяц", - "months": { - "singular": "{0} месяц", - "dual": "{0} месяцы", - "plural": "{0} месяцаў", - }, - "year": "год", - "years": {"singular": "{0} год", "dual": "{0} гады", "plural": "{0} гадоў"}, - } - - month_names = [ - "", - "студзеня", - "лютага", - "сакавіка", - "красавіка", - "траўня", - "чэрвеня", - "ліпеня", - "жніўня", - "верасня", - "кастрычніка", - "лістапада", - "снежня", - ] - month_abbreviations = [ - "", - "студ", - "лют", - "сак", - "крас", - "трав", - "чэрв", - "ліп", - "жнів", - "вер", - "каст", - "ліст", - "снеж", - ] - - day_names = [ - "", - "панядзелак", - "аўторак", - "серада", - "чацвер", - "пятніца", - "субота", - "нядзеля", - ] - day_abbreviations = ["", "пн", "ат", "ср", "чц", "пт", "сб", "нд"] - - -class PolishLocale(SlavicBaseLocale): - names = ["pl", "pl-pl"] - - past = "{0} temu" - future = "za {0}" - - # The nouns should be in genitive case (Polish: "dopełniacz") - # in order to correctly form `past` & `future` expressions. - timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = { - "now": "teraz", - "second": "sekundę", - "seconds": { - "singular": "{0} sekund", - "dual": "{0} sekundy", - "plural": "{0} sekund", - }, - "minute": "minutę", - "minutes": { - "singular": "{0} minut", - "dual": "{0} minuty", - "plural": "{0} minut", - }, - "hour": "godzinę", - "hours": { - "singular": "{0} godzin", - "dual": "{0} godziny", - "plural": "{0} godzin", - }, - "day": "dzień", - "days": "{0} dni", - "week": "tydzień", - "weeks": { - "singular": "{0} tygodni", - "dual": "{0} tygodnie", - "plural": "{0} tygodni", - }, - "month": "miesiąc", - "months": { - "singular": "{0} miesięcy", - "dual": "{0} miesiące", - "plural": "{0} miesięcy", - }, - "year": "rok", - "years": {"singular": "{0} lat", "dual": "{0} lata", "plural": "{0} lat"}, - } - - month_names = [ - "", - "styczeń", - "luty", - "marzec", - "kwiecień", - "maj", - "czerwiec", - "lipiec", - "sierpień", - "wrzesień", - "październik", - "listopad", - "grudzień", - ] - month_abbreviations = [ - "", - "sty", - "lut", - "mar", - "kwi", - "maj", - "cze", - "lip", - "sie", - "wrz", - "paź", - "lis", - "gru", - ] - - day_names = [ - "", - "poniedziałek", - "wtorek", - "środa", - "czwartek", - "piątek", - "sobota", - "niedziela", - ] - day_abbreviations = ["", "Pn", "Wt", "Śr", "Czw", "Pt", "So", "Nd"] - - -class RussianLocale(SlavicBaseLocale): - names = ["ru", "ru-ru"] - - past = "{0} назад" - future = "через {0}" - - timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = { - "now": "сейчас", - "second": "секунда", - "seconds": { - "singular": "{0} секунду", - "dual": "{0} секунды", - "plural": "{0} секунд", - }, - "minute": "минуту", - "minutes": { - "singular": "{0} минуту", - "dual": "{0} минуты", - "plural": "{0} минут", - }, - "hour": "час", - "hours": {"singular": "{0} час", "dual": "{0} часа", "plural": "{0} часов"}, - "day": "день", - "days": {"singular": "{0} день", "dual": "{0} дня", "plural": "{0} дней"}, - "week": "неделю", - "weeks": { - "singular": "{0} неделю", - "dual": "{0} недели", - "plural": "{0} недель", - }, - "month": "месяц", - "months": { - "singular": "{0} месяц", - "dual": "{0} месяца", - "plural": "{0} месяцев", - }, - "quarter": "квартал", - "quarters": { - "singular": "{0} квартал", - "dual": "{0} квартала", - "plural": "{0} кварталов", - }, - "year": "год", - "years": {"singular": "{0} год", "dual": "{0} года", "plural": "{0} лет"}, - } - - month_names = [ - "", - "января", - "февраля", - "марта", - "апреля", - "мая", - "июня", - "июля", - "августа", - "сентября", - "октября", - "ноября", - "декабря", - ] - month_abbreviations = [ - "", - "янв", - "фев", - "мар", - "апр", - "май", - "июн", - "июл", - "авг", - "сен", - "окт", - "ноя", - "дек", - ] - - day_names = [ - "", - "понедельник", - "вторник", - "среда", - "четверг", - "пятница", - "суббота", - "воскресенье", - ] - day_abbreviations = ["", "пн", "вт", "ср", "чт", "пт", "сб", "вс"] - - -class AfrikaansLocale(Locale): - names = ["af", "af-nl"] - - past = "{0} gelede" - future = "in {0}" - - timeframes = { - "now": "nou", - "second": "n sekonde", - "seconds": "{0} sekondes", - "minute": "minuut", - "minutes": "{0} minute", - "hour": "uur", - "hours": "{0} ure", - "day": "een dag", - "days": "{0} dae", - "month": "een maand", - "months": "{0} maande", - "year": "een jaar", - "years": "{0} jaar", - } - - month_names = [ - "", - "Januarie", - "Februarie", - "Maart", - "April", - "Mei", - "Junie", - "Julie", - "Augustus", - "September", - "Oktober", - "November", - "Desember", - ] - month_abbreviations = [ - "", - "Jan", - "Feb", - "Mrt", - "Apr", - "Mei", - "Jun", - "Jul", - "Aug", - "Sep", - "Okt", - "Nov", - "Des", - ] - - day_names = [ - "", - "Maandag", - "Dinsdag", - "Woensdag", - "Donderdag", - "Vrydag", - "Saterdag", - "Sondag", - ] - day_abbreviations = ["", "Ma", "Di", "Wo", "Do", "Vr", "Za", "So"] - - -class BulgarianLocale(SlavicBaseLocale): - names = ["bg", "bg-bg"] - - past = "{0} назад" - future = "напред {0}" - - timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = { - "now": "сега", - "second": "секунда", - "seconds": "{0} няколко секунди", - "minute": "минута", - "minutes": { - "singular": "{0} минута", - "dual": "{0} минути", - "plural": "{0} минути", - }, - "hour": "час", - "hours": {"singular": "{0} час", "dual": "{0} часа", "plural": "{0} часа"}, - "day": "ден", - "days": {"singular": "{0} ден", "dual": "{0} дни", "plural": "{0} дни"}, - "month": "месец", - "months": { - "singular": "{0} месец", - "dual": "{0} месеца", - "plural": "{0} месеца", - }, - "year": "година", - "years": { - "singular": "{0} година", - "dual": "{0} години", - "plural": "{0} години", - }, - } - - month_names = [ - "", - "януари", - "февруари", - "март", - "април", - "май", - "юни", - "юли", - "август", - "септември", - "октомври", - "ноември", - "декември", - ] - month_abbreviations = [ - "", - "ян", - "февр", - "март", - "апр", - "май", - "юни", - "юли", - "авг", - "септ", - "окт", - "ноем", - "дек", - ] - - day_names = [ - "", - "понеделник", - "вторник", - "сряда", - "четвъртък", - "петък", - "събота", - "неделя", - ] - day_abbreviations = ["", "пон", "вт", "ср", "четв", "пет", "съб", "нед"] - - -class UkrainianLocale(SlavicBaseLocale): - names = ["ua", "uk", "uk-ua"] - - past = "{0} тому" - future = "за {0}" - - timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = { - "now": "зараз", - "second": "секунда", - "seconds": "{0} кілька секунд", - "minute": "хвилину", - "minutes": { - "singular": "{0} хвилину", - "dual": "{0} хвилини", - "plural": "{0} хвилин", - }, - "hour": "годину", - "hours": { - "singular": "{0} годину", - "dual": "{0} години", - "plural": "{0} годин", - }, - "day": "день", - "days": {"singular": "{0} день", "dual": "{0} дні", "plural": "{0} днів"}, - "month": "місяць", - "months": { - "singular": "{0} місяць", - "dual": "{0} місяці", - "plural": "{0} місяців", - }, - "year": "рік", - "years": {"singular": "{0} рік", "dual": "{0} роки", "plural": "{0} років"}, - } - - month_names = [ - "", - "січня", - "лютого", - "березня", - "квітня", - "травня", - "червня", - "липня", - "серпня", - "вересня", - "жовтня", - "листопада", - "грудня", - ] - month_abbreviations = [ - "", - "січ", - "лют", - "бер", - "квіт", - "трав", - "черв", - "лип", - "серп", - "вер", - "жовт", - "лист", - "груд", - ] - - day_names = [ - "", - "понеділок", - "вівторок", - "середа", - "четвер", - "п’ятниця", - "субота", - "неділя", - ] - day_abbreviations = ["", "пн", "вт", "ср", "чт", "пт", "сб", "нд"] - - -class MacedonianLocale(SlavicBaseLocale): - names = ["mk", "mk-mk"] - - past = "пред {0}" - future = "за {0}" - - timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = { - "now": "сега", - "second": "една секунда", - "seconds": { - "singular": "{0} секунда", - "dual": "{0} секунди", - "plural": "{0} секунди", - }, - "minute": "една минута", - "minutes": { - "singular": "{0} минута", - "dual": "{0} минути", - "plural": "{0} минути", - }, - "hour": "еден саат", - "hours": {"singular": "{0} саат", "dual": "{0} саати", "plural": "{0} саати"}, - "day": "еден ден", - "days": {"singular": "{0} ден", "dual": "{0} дена", "plural": "{0} дена"}, - "week": "една недела", - "weeks": { - "singular": "{0} недела", - "dual": "{0} недели", - "plural": "{0} недели", - }, - "month": "еден месец", - "months": { - "singular": "{0} месец", - "dual": "{0} месеци", - "plural": "{0} месеци", - }, - "year": "една година", - "years": { - "singular": "{0} година", - "dual": "{0} години", - "plural": "{0} години", - }, - } - - meridians = {"am": "дп", "pm": "пп", "AM": "претпладне", "PM": "попладне"} - - month_names = [ - "", - "Јануари", - "Февруари", - "Март", - "Април", - "Мај", - "Јуни", - "Јули", - "Август", - "Септември", - "Октомври", - "Ноември", - "Декември", - ] - month_abbreviations = [ - "", - "Јан", - "Фев", - "Мар", - "Апр", - "Мај", - "Јун", - "Јул", - "Авг", - "Септ", - "Окт", - "Ноем", - "Декем", - ] - - day_names = [ - "", - "Понеделник", - "Вторник", - "Среда", - "Четврток", - "Петок", - "Сабота", - "Недела", - ] - day_abbreviations = [ - "", - "Пон", - "Вт", - "Сре", - "Чет", - "Пет", - "Саб", - "Нед", - ] - - -class GermanBaseLocale(Locale): - past = "vor {0}" - future = "in {0}" - and_word = "und" - - timeframes = { - "now": "gerade eben", - "second": "einer Sekunde", - "seconds": "{0} Sekunden", - "minute": "einer Minute", - "minutes": "{0} Minuten", - "hour": "einer Stunde", - "hours": "{0} Stunden", - "day": "einem Tag", - "days": "{0} Tagen", - "week": "einer Woche", - "weeks": "{0} Wochen", - "month": "einem Monat", - "months": "{0} Monaten", - "year": "einem Jahr", - "years": "{0} Jahren", - } - - timeframes_only_distance = timeframes.copy() - timeframes_only_distance["second"] = "eine Sekunde" - timeframes_only_distance["minute"] = "eine Minute" - timeframes_only_distance["hour"] = "eine Stunde" - timeframes_only_distance["day"] = "ein Tag" - timeframes_only_distance["days"] = "{0} Tage" - timeframes_only_distance["week"] = "eine Woche" - timeframes_only_distance["month"] = "ein Monat" - timeframes_only_distance["months"] = "{0} Monate" - timeframes_only_distance["year"] = "ein Jahr" - timeframes_only_distance["years"] = "{0} Jahre" - - month_names = [ - "", - "Januar", - "Februar", - "März", - "April", - "Mai", - "Juni", - "Juli", - "August", - "September", - "Oktober", - "November", - "Dezember", - ] - - month_abbreviations = [ - "", - "Jan", - "Feb", - "Mär", - "Apr", - "Mai", - "Jun", - "Jul", - "Aug", - "Sep", - "Okt", - "Nov", - "Dez", - ] - - day_names = [ - "", - "Montag", - "Dienstag", - "Mittwoch", - "Donnerstag", - "Freitag", - "Samstag", - "Sonntag", - ] - - day_abbreviations = ["", "Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"] - - def _ordinal_number(self, n: int) -> str: - return f"{n}." - - def describe( - self, - timeframe: TimeFrameLiteral, - delta: Union[int, float] = 0, - only_distance: bool = False, - ) -> str: - """Describes a delta within a timeframe in plain language. - - :param timeframe: a string representing a timeframe. - :param delta: a quantity representing a delta in a timeframe. - :param only_distance: return only distance eg: "11 seconds" without "in" or "ago" keywords - """ - - if not only_distance: - return super().describe(timeframe, delta, only_distance) - - # German uses a different case without 'in' or 'ago' - humanized = self.timeframes_only_distance[timeframe].format(trunc(abs(delta))) - - return humanized - - -class GermanLocale(GermanBaseLocale, Locale): - names = ["de", "de-de"] - - -class SwissLocale(GermanBaseLocale, Locale): - names = ["de-ch"] - - -class AustrianLocale(GermanBaseLocale, Locale): - names = ["de-at"] - - month_names = [ - "", - "Jänner", - "Februar", - "März", - "April", - "Mai", - "Juni", - "Juli", - "August", - "September", - "Oktober", - "November", - "Dezember", - ] - - -class NorwegianLocale(Locale): - names = ["nb", "nb-no"] - - past = "for {0} siden" - future = "om {0}" - - timeframes = { - "now": "nå nettopp", - "second": "ett sekund", - "seconds": "{0} sekunder", - "minute": "ett minutt", - "minutes": "{0} minutter", - "hour": "en time", - "hours": "{0} timer", - "day": "en dag", - "days": "{0} dager", - "week": "en uke", - "weeks": "{0} uker", - "month": "en måned", - "months": "{0} måneder", - "year": "ett år", - "years": "{0} år", - } - - month_names = [ - "", - "januar", - "februar", - "mars", - "april", - "mai", - "juni", - "juli", - "august", - "september", - "oktober", - "november", - "desember", - ] - month_abbreviations = [ - "", - "jan", - "feb", - "mar", - "apr", - "mai", - "jun", - "jul", - "aug", - "sep", - "okt", - "nov", - "des", - ] - - day_names = [ - "", - "mandag", - "tirsdag", - "onsdag", - "torsdag", - "fredag", - "lørdag", - "søndag", - ] - day_abbreviations = ["", "ma", "ti", "on", "to", "fr", "lø", "sø"] - - def _ordinal_number(self, n: int) -> str: - return f"{n}." - - -class NewNorwegianLocale(Locale): - names = ["nn", "nn-no"] - - past = "for {0} sidan" - future = "om {0}" - - timeframes = { - "now": "no nettopp", - "second": "eitt sekund", - "seconds": "{0} sekund", - "minute": "eitt minutt", - "minutes": "{0} minutt", - "hour": "ein time", - "hours": "{0} timar", - "day": "ein dag", - "days": "{0} dagar", - "week": "ei veke", - "weeks": "{0} veker", - "month": "ein månad", - "months": "{0} månader", - "year": "eitt år", - "years": "{0} år", - } - - month_names = [ - "", - "januar", - "februar", - "mars", - "april", - "mai", - "juni", - "juli", - "august", - "september", - "oktober", - "november", - "desember", - ] - month_abbreviations = [ - "", - "jan", - "feb", - "mar", - "apr", - "mai", - "jun", - "jul", - "aug", - "sep", - "okt", - "nov", - "des", - ] - - day_names = [ - "", - "måndag", - "tysdag", - "onsdag", - "torsdag", - "fredag", - "laurdag", - "sundag", - ] - day_abbreviations = ["", "må", "ty", "on", "to", "fr", "la", "su"] - - def _ordinal_number(self, n: int) -> str: - return f"{n}." - - -class PortugueseLocale(Locale): - names = ["pt", "pt-pt"] - - past = "há {0}" - future = "em {0}" - and_word = "e" - - timeframes = { - "now": "agora", - "second": "um segundo", - "seconds": "{0} segundos", - "minute": "um minuto", - "minutes": "{0} minutos", - "hour": "uma hora", - "hours": "{0} horas", - "day": "um dia", - "days": "{0} dias", - "week": "uma semana", - "weeks": "{0} semanas", - "month": "um mês", - "months": "{0} meses", - "year": "um ano", - "years": "{0} anos", - } - - month_names = [ - "", - "Janeiro", - "Fevereiro", - "Março", - "Abril", - "Maio", - "Junho", - "Julho", - "Agosto", - "Setembro", - "Outubro", - "Novembro", - "Dezembro", - ] - month_abbreviations = [ - "", - "Jan", - "Fev", - "Mar", - "Abr", - "Mai", - "Jun", - "Jul", - "Ago", - "Set", - "Out", - "Nov", - "Dez", - ] - - day_names = [ - "", - "Segunda-feira", - "Terça-feira", - "Quarta-feira", - "Quinta-feira", - "Sexta-feira", - "Sábado", - "Domingo", - ] - day_abbreviations = ["", "Seg", "Ter", "Qua", "Qui", "Sex", "Sab", "Dom"] - - -class BrazilianPortugueseLocale(PortugueseLocale): - names = ["pt-br"] - - past = "faz {0}" - - -class TagalogLocale(Locale): - names = ["tl", "tl-ph"] - - past = "nakaraang {0}" - future = "{0} mula ngayon" - - timeframes = { - "now": "ngayon lang", - "second": "isang segundo", - "seconds": "{0} segundo", - "minute": "isang minuto", - "minutes": "{0} minuto", - "hour": "isang oras", - "hours": "{0} oras", - "day": "isang araw", - "days": "{0} araw", - "week": "isang linggo", - "weeks": "{0} linggo", - "month": "isang buwan", - "months": "{0} buwan", - "year": "isang taon", - "years": "{0} taon", - } - - month_names = [ - "", - "Enero", - "Pebrero", - "Marso", - "Abril", - "Mayo", - "Hunyo", - "Hulyo", - "Agosto", - "Setyembre", - "Oktubre", - "Nobyembre", - "Disyembre", - ] - month_abbreviations = [ - "", - "Ene", - "Peb", - "Mar", - "Abr", - "May", - "Hun", - "Hul", - "Ago", - "Set", - "Okt", - "Nob", - "Dis", - ] - - day_names = [ - "", - "Lunes", - "Martes", - "Miyerkules", - "Huwebes", - "Biyernes", - "Sabado", - "Linggo", - ] - day_abbreviations = ["", "Lun", "Mar", "Miy", "Huw", "Biy", "Sab", "Lin"] - - meridians = {"am": "nu", "pm": "nh", "AM": "ng umaga", "PM": "ng hapon"} - - def _ordinal_number(self, n: int) -> str: - return f"ika-{n}" - - -class VietnameseLocale(Locale): - names = ["vi", "vi-vn"] - - past = "{0} trước" - future = "{0} nữa" - - timeframes = { - "now": "hiện tại", - "second": "một giây", - "seconds": "{0} giây", - "minute": "một phút", - "minutes": "{0} phút", - "hour": "một giờ", - "hours": "{0} giờ", - "day": "một ngày", - "days": "{0} ngày", - "week": "một tuần", - "weeks": "{0} tuần", - "month": "một tháng", - "months": "{0} tháng", - "year": "một năm", - "years": "{0} năm", - } - - month_names = [ - "", - "Tháng Một", - "Tháng Hai", - "Tháng Ba", - "Tháng Tư", - "Tháng Năm", - "Tháng Sáu", - "Tháng Bảy", - "Tháng Tám", - "Tháng Chín", - "Tháng Mười", - "Tháng Mười Một", - "Tháng Mười Hai", - ] - month_abbreviations = [ - "", - "Tháng 1", - "Tháng 2", - "Tháng 3", - "Tháng 4", - "Tháng 5", - "Tháng 6", - "Tháng 7", - "Tháng 8", - "Tháng 9", - "Tháng 10", - "Tháng 11", - "Tháng 12", - ] - - day_names = [ - "", - "Thứ Hai", - "Thứ Ba", - "Thứ Tư", - "Thứ Năm", - "Thứ Sáu", - "Thứ Bảy", - "Chủ Nhật", - ] - day_abbreviations = ["", "Thứ 2", "Thứ 3", "Thứ 4", "Thứ 5", "Thứ 6", "Thứ 7", "CN"] - - -class TurkishLocale(Locale): - names = ["tr", "tr-tr"] - - past = "{0} önce" - future = "{0} sonra" - and_word = "ve" - - timeframes = { - "now": "şimdi", - "second": "bir saniye", - "seconds": "{0} saniye", - "minute": "bir dakika", - "minutes": "{0} dakika", - "hour": "bir saat", - "hours": "{0} saat", - "day": "bir gün", - "days": "{0} gün", - "week": "bir hafta", - "weeks": "{0} hafta", - "month": "bir ay", - "months": "{0} ay", - "year": "bir yıl", - "years": "{0} yıl", - } - - meridians = {"am": "öö", "pm": "ös", "AM": "ÖÖ", "PM": "ÖS"} - - month_names = [ - "", - "Ocak", - "Şubat", - "Mart", - "Nisan", - "Mayıs", - "Haziran", - "Temmuz", - "Ağustos", - "Eylül", - "Ekim", - "Kasım", - "Aralık", - ] - month_abbreviations = [ - "", - "Oca", - "Şub", - "Mar", - "Nis", - "May", - "Haz", - "Tem", - "Ağu", - "Eyl", - "Eki", - "Kas", - "Ara", - ] - - day_names = [ - "", - "Pazartesi", - "Salı", - "Çarşamba", - "Perşembe", - "Cuma", - "Cumartesi", - "Pazar", - ] - day_abbreviations = ["", "Pzt", "Sal", "Çar", "Per", "Cum", "Cmt", "Paz"] - - -class AzerbaijaniLocale(Locale): - names = ["az", "az-az"] - - past = "{0} əvvəl" - future = "{0} sonra" - - timeframes = { - "now": "indi", - "second": "bir saniyə", - "seconds": "{0} saniyə", - "minute": "bir dəqiqə", - "minutes": "{0} dəqiqə", - "hour": "bir saat", - "hours": "{0} saat", - "day": "bir gün", - "days": "{0} gün", - "week": "bir həftə", - "weeks": "{0} həftə", - "month": "bir ay", - "months": "{0} ay", - "year": "bir il", - "years": "{0} il", - } - - month_names = [ - "", - "Yanvar", - "Fevral", - "Mart", - "Aprel", - "May", - "İyun", - "İyul", - "Avqust", - "Sentyabr", - "Oktyabr", - "Noyabr", - "Dekabr", - ] - month_abbreviations = [ - "", - "Yan", - "Fev", - "Mar", - "Apr", - "May", - "İyn", - "İyl", - "Avq", - "Sen", - "Okt", - "Noy", - "Dek", - ] - - day_names = [ - "", - "Bazar ertəsi", - "Çərşənbə axşamı", - "Çərşənbə", - "Cümə axşamı", - "Cümə", - "Şənbə", - "Bazar", - ] - day_abbreviations = ["", "Ber", "Çax", "Çər", "Cax", "Cüm", "Şnb", "Bzr"] - - -class ArabicLocale(Locale): - names = [ - "ar", - "ar-ae", - "ar-bh", - "ar-dj", - "ar-eg", - "ar-eh", - "ar-er", - "ar-km", - "ar-kw", - "ar-ly", - "ar-om", - "ar-qa", - "ar-sa", - "ar-sd", - "ar-so", - "ar-ss", - "ar-td", - "ar-ye", - ] - - past = "منذ {0}" - future = "خلال {0}" - - timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = { - "now": "الآن", - "second": "ثانية", - "seconds": {"2": "ثانيتين", "ten": "{0} ثوان", "higher": "{0} ثانية"}, - "minute": "دقيقة", - "minutes": {"2": "دقيقتين", "ten": "{0} دقائق", "higher": "{0} دقيقة"}, - "hour": "ساعة", - "hours": {"2": "ساعتين", "ten": "{0} ساعات", "higher": "{0} ساعة"}, - "day": "يوم", - "days": {"2": "يومين", "ten": "{0} أيام", "higher": "{0} يوم"}, - "month": "شهر", - "months": {"2": "شهرين", "ten": "{0} أشهر", "higher": "{0} شهر"}, - "year": "سنة", - "years": {"2": "سنتين", "ten": "{0} سنوات", "higher": "{0} سنة"}, - } - - month_names = [ - "", - "يناير", - "فبراير", - "مارس", - "أبريل", - "مايو", - "يونيو", - "يوليو", - "أغسطس", - "سبتمبر", - "أكتوبر", - "نوفمبر", - "ديسمبر", - ] - month_abbreviations = [ - "", - "يناير", - "فبراير", - "مارس", - "أبريل", - "مايو", - "يونيو", - "يوليو", - "أغسطس", - "سبتمبر", - "أكتوبر", - "نوفمبر", - "ديسمبر", - ] - - day_names = [ - "", - "الإثنين", - "الثلاثاء", - "الأربعاء", - "الخميس", - "الجمعة", - "السبت", - "الأحد", - ] - day_abbreviations = ["", "إثنين", "ثلاثاء", "أربعاء", "خميس", "جمعة", "سبت", "أحد"] - - def _format_timeframe(self, timeframe: TimeFrameLiteral, delta: int) -> str: - form = self.timeframes[timeframe] - delta = abs(delta) - if isinstance(form, Mapping): - if delta == 2: - form = form["2"] - elif 2 < delta <= 10: - form = form["ten"] - else: - form = form["higher"] - - return form.format(delta) - - -class LevantArabicLocale(ArabicLocale): - names = ["ar-iq", "ar-jo", "ar-lb", "ar-ps", "ar-sy"] - month_names = [ - "", - "كانون الثاني", - "شباط", - "آذار", - "نيسان", - "أيار", - "حزيران", - "تموز", - "آب", - "أيلول", - "تشرين الأول", - "تشرين الثاني", - "كانون الأول", - ] - month_abbreviations = [ - "", - "كانون الثاني", - "شباط", - "آذار", - "نيسان", - "أيار", - "حزيران", - "تموز", - "آب", - "أيلول", - "تشرين الأول", - "تشرين الثاني", - "كانون الأول", - ] - - -class AlgeriaTunisiaArabicLocale(ArabicLocale): - names = ["ar-tn", "ar-dz"] - month_names = [ - "", - "جانفي", - "فيفري", - "مارس", - "أفريل", - "ماي", - "جوان", - "جويلية", - "أوت", - "سبتمبر", - "أكتوبر", - "نوفمبر", - "ديسمبر", - ] - month_abbreviations = [ - "", - "جانفي", - "فيفري", - "مارس", - "أفريل", - "ماي", - "جوان", - "جويلية", - "أوت", - "سبتمبر", - "أكتوبر", - "نوفمبر", - "ديسمبر", - ] - - -class MauritaniaArabicLocale(ArabicLocale): - names = ["ar-mr"] - month_names = [ - "", - "يناير", - "فبراير", - "مارس", - "إبريل", - "مايو", - "يونيو", - "يوليو", - "أغشت", - "شتمبر", - "أكتوبر", - "نوفمبر", - "دجمبر", - ] - month_abbreviations = [ - "", - "يناير", - "فبراير", - "مارس", - "إبريل", - "مايو", - "يونيو", - "يوليو", - "أغشت", - "شتمبر", - "أكتوبر", - "نوفمبر", - "دجمبر", - ] - - -class MoroccoArabicLocale(ArabicLocale): - names = ["ar-ma"] - month_names = [ - "", - "يناير", - "فبراير", - "مارس", - "أبريل", - "ماي", - "يونيو", - "يوليوز", - "غشت", - "شتنبر", - "أكتوبر", - "نونبر", - "دجنبر", - ] - month_abbreviations = [ - "", - "يناير", - "فبراير", - "مارس", - "أبريل", - "ماي", - "يونيو", - "يوليوز", - "غشت", - "شتنبر", - "أكتوبر", - "نونبر", - "دجنبر", - ] - - -class IcelandicLocale(Locale): - def _format_timeframe(self, timeframe: TimeFrameLiteral, delta: int) -> str: - form = self.timeframes[timeframe] - - if isinstance(form, Mapping): - if delta < 0: - form = form["past"] - elif delta > 0: - form = form["future"] - else: - raise ValueError( - "Icelandic Locale does not support units with a delta of zero. " - "Please consider making a contribution to fix this issue." - ) - # FIXME: handle when delta is 0 - - return form.format(abs(delta)) - - names = ["is", "is-is"] - - past = "fyrir {0} síðan" - future = "eftir {0}" - - timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = { - "now": "rétt í þessu", - "second": {"past": "sekúndu", "future": "sekúndu"}, - "seconds": {"past": "{0} nokkrum sekúndum", "future": "nokkrar sekúndur"}, - "minute": {"past": "einni mínútu", "future": "eina mínútu"}, - "minutes": {"past": "{0} mínútum", "future": "{0} mínútur"}, - "hour": {"past": "einum tíma", "future": "einn tíma"}, - "hours": {"past": "{0} tímum", "future": "{0} tíma"}, - "day": {"past": "einum degi", "future": "einn dag"}, - "days": {"past": "{0} dögum", "future": "{0} daga"}, - "month": {"past": "einum mánuði", "future": "einn mánuð"}, - "months": {"past": "{0} mánuðum", "future": "{0} mánuði"}, - "year": {"past": "einu ári", "future": "eitt ár"}, - "years": {"past": "{0} árum", "future": "{0} ár"}, - } - - meridians = {"am": "f.h.", "pm": "e.h.", "AM": "f.h.", "PM": "e.h."} - - month_names = [ - "", - "janúar", - "febrúar", - "mars", - "apríl", - "maí", - "júní", - "júlí", - "ágúst", - "september", - "október", - "nóvember", - "desember", - ] - month_abbreviations = [ - "", - "jan", - "feb", - "mar", - "apr", - "maí", - "jún", - "júl", - "ágú", - "sep", - "okt", - "nóv", - "des", - ] - - day_names = [ - "", - "mánudagur", - "þriðjudagur", - "miðvikudagur", - "fimmtudagur", - "föstudagur", - "laugardagur", - "sunnudagur", - ] - day_abbreviations = ["", "mán", "þri", "mið", "fim", "fös", "lau", "sun"] - - -class DanishLocale(Locale): - names = ["da", "da-dk"] - - past = "for {0} siden" - future = "om {0}" - and_word = "og" - - timeframes = { - "now": "lige nu", - "second": "et sekund", - "seconds": "{0} sekunder", - "minute": "et minut", - "minutes": "{0} minutter", - "hour": "en time", - "hours": "{0} timer", - "day": "en dag", - "days": "{0} dage", - "week": "en uge", - "weeks": "{0} uger", - "month": "en måned", - "months": "{0} måneder", - "year": "et år", - "years": "{0} år", - } - - month_names = [ - "", - "januar", - "februar", - "marts", - "april", - "maj", - "juni", - "juli", - "august", - "september", - "oktober", - "november", - "december", - ] - month_abbreviations = [ - "", - "jan", - "feb", - "mar", - "apr", - "maj", - "jun", - "jul", - "aug", - "sep", - "okt", - "nov", - "dec", - ] - - day_names = [ - "", - "mandag", - "tirsdag", - "onsdag", - "torsdag", - "fredag", - "lørdag", - "søndag", - ] - day_abbreviations = ["", "man", "tir", "ons", "tor", "fre", "lør", "søn"] - - def _ordinal_number(self, n: int) -> str: - return f"{n}." - - -class MalayalamLocale(Locale): - names = ["ml"] - - past = "{0} മുമ്പ്" - future = "{0} ശേഷം" - - timeframes = { - "now": "ഇപ്പോൾ", - "second": "ഒരു നിമിഷം", - "seconds": "{0} സെക്കന്റ്‌", - "minute": "ഒരു മിനിറ്റ്", - "minutes": "{0} മിനിറ്റ്", - "hour": "ഒരു മണിക്കൂർ", - "hours": "{0} മണിക്കൂർ", - "day": "ഒരു ദിവസം ", - "days": "{0} ദിവസം ", - "month": "ഒരു മാസം ", - "months": "{0} മാസം ", - "year": "ഒരു വർഷം ", - "years": "{0} വർഷം ", - } - - meridians = { - "am": "രാവിലെ", - "pm": "ഉച്ചക്ക് ശേഷം", - "AM": "രാവിലെ", - "PM": "ഉച്ചക്ക് ശേഷം", - } - - month_names = [ - "", - "ജനുവരി", - "ഫെബ്രുവരി", - "മാർച്ച്‌", - "ഏപ്രിൽ ", - "മെയ്‌ ", - "ജൂണ്‍", - "ജൂലൈ", - "ഓഗസ്റ്റ്‌", - "സെപ്റ്റംബർ", - "ഒക്ടോബർ", - "നവംബർ", - "ഡിസംബർ", - ] - month_abbreviations = [ - "", - "ജനു", - "ഫെബ് ", - "മാർ", - "ഏപ്രിൽ", - "മേയ്", - "ജൂണ്‍", - "ജൂലൈ", - "ഓഗസ്റ", - "സെപ്റ്റ", - "ഒക്ടോ", - "നവം", - "ഡിസം", - ] - - day_names = ["", "തിങ്കള്‍", "ചൊവ്വ", "ബുധന്‍", "വ്യാഴം", "വെള്ളി", "ശനി", "ഞായര്‍"] - day_abbreviations = [ - "", - "തിങ്കള്‍", - "ചൊവ്വ", - "ബുധന്‍", - "വ്യാഴം", - "വെള്ളി", - "ശനി", - "ഞായര്‍", - ] - - -class HindiLocale(Locale): - names = ["hi", "hi-in"] - - past = "{0} पहले" - future = "{0} बाद" - - timeframes = { - "now": "अभी", - "second": "एक पल", - "seconds": "{0} सेकंड्", - "minute": "एक मिनट ", - "minutes": "{0} मिनट ", - "hour": "एक घंटा", - "hours": "{0} घंटे", - "day": "एक दिन", - "days": "{0} दिन", - "month": "एक माह ", - "months": "{0} महीने ", - "year": "एक वर्ष ", - "years": "{0} साल ", - } - - meridians = {"am": "सुबह", "pm": "शाम", "AM": "सुबह", "PM": "शाम"} - - month_names = [ - "", - "जनवरी", - "फरवरी", - "मार्च", - "अप्रैल ", - "मई", - "जून", - "जुलाई", - "अगस्त", - "सितंबर", - "अक्टूबर", - "नवंबर", - "दिसंबर", - ] - month_abbreviations = [ - "", - "जन", - "फ़र", - "मार्च", - "अप्रै", - "मई", - "जून", - "जुलाई", - "आग", - "सित", - "अकत", - "नवे", - "दिस", - ] - - day_names = [ - "", - "सोमवार", - "मंगलवार", - "बुधवार", - "गुरुवार", - "शुक्रवार", - "शनिवार", - "रविवार", - ] - day_abbreviations = ["", "सोम", "मंगल", "बुध", "गुरुवार", "शुक्र", "शनि", "रवि"] - - -class CzechLocale(Locale): - names = ["cs", "cs-cz"] - - timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = { - "now": "Teď", - "second": {"past": "vteřina", "future": "vteřina"}, - "seconds": { - "zero": "vteřina", - "past": "{0} sekundami", - "future-singular": "{0} sekundy", - "future-paucal": "{0} sekund", - }, - "minute": {"past": "minutou", "future": "minutu"}, - "minutes": { - "zero": "{0} minut", - "past": "{0} minutami", - "future-singular": "{0} minuty", - "future-paucal": "{0} minut", - }, - "hour": {"past": "hodinou", "future": "hodinu"}, - "hours": { - "zero": "{0} hodin", - "past": "{0} hodinami", - "future-singular": "{0} hodiny", - "future-paucal": "{0} hodin", - }, - "day": {"past": "dnem", "future": "den"}, - "days": { - "zero": "{0} dnů", - "past": "{0} dny", - "future-singular": "{0} dny", - "future-paucal": "{0} dnů", - }, - "week": {"past": "týdnem", "future": "týden"}, - "weeks": { - "zero": "{0} týdnů", - "past": "{0} týdny", - "future-singular": "{0} týdny", - "future-paucal": "{0} týdnů", - }, - "month": {"past": "měsícem", "future": "měsíc"}, - "months": { - "zero": "{0} měsíců", - "past": "{0} měsíci", - "future-singular": "{0} měsíce", - "future-paucal": "{0} měsíců", - }, - "year": {"past": "rokem", "future": "rok"}, - "years": { - "zero": "{0} let", - "past": "{0} lety", - "future-singular": "{0} roky", - "future-paucal": "{0} let", - }, - } - - past = "Před {0}" - future = "Za {0}" - - month_names = [ - "", - "leden", - "únor", - "březen", - "duben", - "květen", - "červen", - "červenec", - "srpen", - "září", - "říjen", - "listopad", - "prosinec", - ] - month_abbreviations = [ - "", - "led", - "úno", - "bře", - "dub", - "kvě", - "čvn", - "čvc", - "srp", - "zář", - "říj", - "lis", - "pro", - ] - - day_names = [ - "", - "pondělí", - "úterý", - "středa", - "čtvrtek", - "pátek", - "sobota", - "neděle", - ] - day_abbreviations = ["", "po", "út", "st", "čt", "pá", "so", "ne"] - - def _format_timeframe(self, timeframe: TimeFrameLiteral, delta: int) -> str: - """Czech aware time frame format function, takes into account - the differences between past and future forms.""" - abs_delta = abs(delta) - form = self.timeframes[timeframe] - - if isinstance(form, str): - return form.format(abs_delta) - - if delta == 0: - key = "zero" # And *never* use 0 in the singular! - elif delta < 0: - key = "past" - else: - # Needed since both regular future and future-singular and future-paucal cases - if "future-singular" not in form: - key = "future" - elif 2 <= abs_delta % 10 <= 4 and ( - abs_delta % 100 < 10 or abs_delta % 100 >= 20 - ): - key = "future-singular" - else: - key = "future-paucal" - - form: str = form[key] - return form.format(abs_delta) - - -class SlovakLocale(Locale): - names = ["sk", "sk-sk"] - - timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = { - "now": "Teraz", - "second": {"past": "sekundou", "future": "sekundu"}, - "seconds": { - "zero": "{0} sekúnd", - "past": "{0} sekundami", - "future-singular": "{0} sekundy", - "future-paucal": "{0} sekúnd", - }, - "minute": {"past": "minútou", "future": "minútu"}, - "minutes": { - "zero": "{0} minút", - "past": "{0} minútami", - "future-singular": "{0} minúty", - "future-paucal": "{0} minút", - }, - "hour": {"past": "hodinou", "future": "hodinu"}, - "hours": { - "zero": "{0} hodín", - "past": "{0} hodinami", - "future-singular": "{0} hodiny", - "future-paucal": "{0} hodín", - }, - "day": {"past": "dňom", "future": "deň"}, - "days": { - "zero": "{0} dní", - "past": "{0} dňami", - "future-singular": "{0} dni", - "future-paucal": "{0} dní", - }, - "week": {"past": "týždňom", "future": "týždeň"}, - "weeks": { - "zero": "{0} týždňov", - "past": "{0} týždňami", - "future-singular": "{0} týždne", - "future-paucal": "{0} týždňov", - }, - "month": {"past": "mesiacom", "future": "mesiac"}, - "months": { - "zero": "{0} mesiacov", - "past": "{0} mesiacmi", - "future-singular": "{0} mesiace", - "future-paucal": "{0} mesiacov", - }, - "year": {"past": "rokom", "future": "rok"}, - "years": { - "zero": "{0} rokov", - "past": "{0} rokmi", - "future-singular": "{0} roky", - "future-paucal": "{0} rokov", - }, - } - - past = "Pred {0}" - future = "O {0}" - and_word = "a" - - month_names = [ - "", - "január", - "február", - "marec", - "apríl", - "máj", - "jún", - "júl", - "august", - "september", - "október", - "november", - "december", - ] - month_abbreviations = [ - "", - "jan", - "feb", - "mar", - "apr", - "máj", - "jún", - "júl", - "aug", - "sep", - "okt", - "nov", - "dec", - ] - - day_names = [ - "", - "pondelok", - "utorok", - "streda", - "štvrtok", - "piatok", - "sobota", - "nedeľa", - ] - day_abbreviations = ["", "po", "ut", "st", "št", "pi", "so", "ne"] - - def _format_timeframe(self, timeframe: TimeFrameLiteral, delta: int) -> str: - """Slovak aware time frame format function, takes into account - the differences between past and future forms.""" - abs_delta = abs(delta) - form = self.timeframes[timeframe] - - if isinstance(form, str): - return form.format(abs_delta) - - if delta == 0: - key = "zero" # And *never* use 0 in the singular! - elif delta < 0: - key = "past" - else: - if "future-singular" not in form: - key = "future" - elif 2 <= abs_delta % 10 <= 4 and ( - abs_delta % 100 < 10 or abs_delta % 100 >= 20 - ): - key = "future-singular" - else: - key = "future-paucal" - - form: str = form[key] - return form.format(abs_delta) - - -class FarsiLocale(Locale): - names = ["fa", "fa-ir"] - - past = "{0} قبل" - future = "در {0}" - - timeframes = { - "now": "اکنون", - "second": "یک لحظه", - "seconds": "{0} ثانیه", - "minute": "یک دقیقه", - "minutes": "{0} دقیقه", - "hour": "یک ساعت", - "hours": "{0} ساعت", - "day": "یک روز", - "days": "{0} روز", - "month": "یک ماه", - "months": "{0} ماه", - "year": "یک سال", - "years": "{0} سال", - } - - meridians = { - "am": "قبل از ظهر", - "pm": "بعد از ظهر", - "AM": "قبل از ظهر", - "PM": "بعد از ظهر", - } - - month_names = [ - "", - "January", - "February", - "March", - "April", - "May", - "June", - "July", - "August", - "September", - "October", - "November", - "December", - ] - month_abbreviations = [ - "", - "Jan", - "Feb", - "Mar", - "Apr", - "May", - "Jun", - "Jul", - "Aug", - "Sep", - "Oct", - "Nov", - "Dec", - ] - - day_names = [ - "", - "دو شنبه", - "سه شنبه", - "چهارشنبه", - "پنجشنبه", - "جمعه", - "شنبه", - "یکشنبه", - ] - day_abbreviations = ["", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] - - -class HebrewLocale(Locale): - names = ["he", "he-il"] - - past = "לפני {0}" - future = "בעוד {0}" - and_word = "ו" - - timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = { - "now": "הרגע", - "second": "שנייה", - "seconds": "{0} שניות", - "minute": "דקה", - "minutes": "{0} דקות", - "hour": "שעה", - "hours": {"2": "שעתיים", "ten": "{0} שעות", "higher": "{0} שעות"}, - "day": "יום", - "days": {"2": "יומיים", "ten": "{0} ימים", "higher": "{0} יום"}, - "week": "שבוע", - "weeks": {"2": "שבועיים", "ten": "{0} שבועות", "higher": "{0} שבועות"}, - "month": "חודש", - "months": {"2": "חודשיים", "ten": "{0} חודשים", "higher": "{0} חודשים"}, - "year": "שנה", - "years": {"2": "שנתיים", "ten": "{0} שנים", "higher": "{0} שנה"}, - } - - meridians = { - "am": 'לפנ"צ', - "pm": 'אחר"צ', - "AM": "לפני הצהריים", - "PM": "אחרי הצהריים", - } - - month_names = [ - "", - "ינואר", - "פברואר", - "מרץ", - "אפריל", - "מאי", - "יוני", - "יולי", - "אוגוסט", - "ספטמבר", - "אוקטובר", - "נובמבר", - "דצמבר", - ] - month_abbreviations = [ - "", - "ינו׳", - "פבר׳", - "מרץ", - "אפר׳", - "מאי", - "יוני", - "יולי", - "אוג׳", - "ספט׳", - "אוק׳", - "נוב׳", - "דצמ׳", - ] - - day_names = ["", "שני", "שלישי", "רביעי", "חמישי", "שישי", "שבת", "ראשון"] - day_abbreviations = ["", "ב׳", "ג׳", "ד׳", "ה׳", "ו׳", "ש׳", "א׳"] - - def _format_timeframe(self, timeframe: TimeFrameLiteral, delta: int) -> str: - form = self.timeframes[timeframe] - delta = abs(delta) - if isinstance(form, Mapping): - if delta == 2: - form = form["2"] - elif delta == 0 or 2 < delta <= 10: - form = form["ten"] - else: - form = form["higher"] - - return form.format(delta) - - def describe_multi( - self, - timeframes: Sequence[Tuple[TimeFrameLiteral, Union[int, float]]], - only_distance: bool = False, - ) -> str: - """Describes a delta within multiple timeframes in plain language. - In Hebrew, the and word behaves a bit differently. - - :param timeframes: a list of string, quantity pairs each representing a timeframe and delta. - :param only_distance: return only distance eg: "2 hours and 11 seconds" without "in" or "ago" keywords - """ - - humanized = "" - for index, (timeframe, delta) in enumerate(timeframes): - last_humanized = self._format_timeframe(timeframe, trunc(delta)) - if index == 0: - humanized = last_humanized - elif index == len(timeframes) - 1: # Must have at least 2 items - humanized += " " + self.and_word - if last_humanized[0].isdecimal(): - humanized += "־" - humanized += last_humanized - else: # Don't add for the last one - humanized += ", " + last_humanized - - if not only_distance: - humanized = self._format_relative(humanized, timeframe, trunc(delta)) - - return humanized - - -class MarathiLocale(Locale): - names = ["mr"] - - past = "{0} आधी" - future = "{0} नंतर" - - timeframes = { - "now": "सद्य", - "second": "एक सेकंद", - "seconds": "{0} सेकंद", - "minute": "एक मिनिट ", - "minutes": "{0} मिनिट ", - "hour": "एक तास", - "hours": "{0} तास", - "day": "एक दिवस", - "days": "{0} दिवस", - "month": "एक महिना ", - "months": "{0} महिने ", - "year": "एक वर्ष ", - "years": "{0} वर्ष ", - } - - meridians = {"am": "सकाळ", "pm": "संध्याकाळ", "AM": "सकाळ", "PM": "संध्याकाळ"} - - month_names = [ - "", - "जानेवारी", - "फेब्रुवारी", - "मार्च", - "एप्रिल", - "मे", - "जून", - "जुलै", - "अॉगस्ट", - "सप्टेंबर", - "अॉक्टोबर", - "नोव्हेंबर", - "डिसेंबर", - ] - month_abbreviations = [ - "", - "जान", - "फेब्रु", - "मार्च", - "एप्रि", - "मे", - "जून", - "जुलै", - "अॉग", - "सप्टें", - "अॉक्टो", - "नोव्हें", - "डिसें", - ] - - day_names = [ - "", - "सोमवार", - "मंगळवार", - "बुधवार", - "गुरुवार", - "शुक्रवार", - "शनिवार", - "रविवार", - ] - day_abbreviations = ["", "सोम", "मंगळ", "बुध", "गुरु", "शुक्र", "शनि", "रवि"] - - -class CatalanLocale(Locale): - names = ["ca", "ca-es", "ca-ad", "ca-fr", "ca-it"] - past = "Fa {0}" - future = "En {0}" - and_word = "i" - - timeframes = { - "now": "Ara mateix", - "second": "un segon", - "seconds": "{0} segons", - "minute": "un minut", - "minutes": "{0} minuts", - "hour": "una hora", - "hours": "{0} hores", - "day": "un dia", - "days": "{0} dies", - "month": "un mes", - "months": "{0} mesos", - "year": "un any", - "years": "{0} anys", - } - - month_names = [ - "", - "gener", - "febrer", - "març", - "abril", - "maig", - "juny", - "juliol", - "agost", - "setembre", - "octubre", - "novembre", - "desembre", - ] - month_abbreviations = [ - "", - "gen.", - "febr.", - "març", - "abr.", - "maig", - "juny", - "jul.", - "ag.", - "set.", - "oct.", - "nov.", - "des.", - ] - day_names = [ - "", - "dilluns", - "dimarts", - "dimecres", - "dijous", - "divendres", - "dissabte", - "diumenge", - ] - day_abbreviations = [ - "", - "dl.", - "dt.", - "dc.", - "dj.", - "dv.", - "ds.", - "dg.", - ] - - -class BasqueLocale(Locale): - names = ["eu", "eu-eu"] - past = "duela {0}" - future = "{0}" # I don't know what's the right phrase in Basque for the future. - - timeframes = { - "now": "Orain", - "second": "segundo bat", - "seconds": "{0} segundu", - "minute": "minutu bat", - "minutes": "{0} minutu", - "hour": "ordu bat", - "hours": "{0} ordu", - "day": "egun bat", - "days": "{0} egun", - "month": "hilabete bat", - "months": "{0} hilabet", - "year": "urte bat", - "years": "{0} urte", - } - - month_names = [ - "", - "urtarrilak", - "otsailak", - "martxoak", - "apirilak", - "maiatzak", - "ekainak", - "uztailak", - "abuztuak", - "irailak", - "urriak", - "azaroak", - "abenduak", - ] - month_abbreviations = [ - "", - "urt", - "ots", - "mar", - "api", - "mai", - "eka", - "uzt", - "abu", - "ira", - "urr", - "aza", - "abe", - ] - day_names = [ - "", - "astelehena", - "asteartea", - "asteazkena", - "osteguna", - "ostirala", - "larunbata", - "igandea", - ] - day_abbreviations = ["", "al", "ar", "az", "og", "ol", "lr", "ig"] - - -class HungarianLocale(Locale): - names = ["hu", "hu-hu"] - - past = "{0} ezelőtt" - future = "{0} múlva" - - timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = { - "now": "éppen most", - "second": {"past": "egy második", "future": "egy második"}, - "seconds": {"past": "{0} másodpercekkel", "future": "{0} pár másodperc"}, - "minute": {"past": "egy perccel", "future": "egy perc"}, - "minutes": {"past": "{0} perccel", "future": "{0} perc"}, - "hour": {"past": "egy órával", "future": "egy óra"}, - "hours": {"past": "{0} órával", "future": "{0} óra"}, - "day": {"past": "egy nappal", "future": "egy nap"}, - "days": {"past": "{0} nappal", "future": "{0} nap"}, - "month": {"past": "egy hónappal", "future": "egy hónap"}, - "months": {"past": "{0} hónappal", "future": "{0} hónap"}, - "year": {"past": "egy évvel", "future": "egy év"}, - "years": {"past": "{0} évvel", "future": "{0} év"}, - } - - month_names = [ - "", - "január", - "február", - "március", - "április", - "május", - "június", - "július", - "augusztus", - "szeptember", - "október", - "november", - "december", - ] - month_abbreviations = [ - "", - "jan", - "febr", - "márc", - "ápr", - "máj", - "jún", - "júl", - "aug", - "szept", - "okt", - "nov", - "dec", - ] - - day_names = [ - "", - "hétfő", - "kedd", - "szerda", - "csütörtök", - "péntek", - "szombat", - "vasárnap", - ] - day_abbreviations = ["", "hét", "kedd", "szer", "csüt", "pént", "szom", "vas"] - - meridians = {"am": "de", "pm": "du", "AM": "DE", "PM": "DU"} - - def _format_timeframe(self, timeframe: TimeFrameLiteral, delta: int) -> str: - form = self.timeframes[timeframe] - - if isinstance(form, Mapping): - if delta > 0: - form = form["future"] - else: - form = form["past"] - - return form.format(abs(delta)) - - -class EsperantoLocale(Locale): - names = ["eo", "eo-xx"] - past = "antaŭ {0}" - future = "post {0}" - - timeframes = { - "now": "nun", - "second": "sekundo", - "seconds": "{0} kelkaj sekundoj", - "minute": "unu minuto", - "minutes": "{0} minutoj", - "hour": "un horo", - "hours": "{0} horoj", - "day": "unu tago", - "days": "{0} tagoj", - "month": "unu monato", - "months": "{0} monatoj", - "year": "unu jaro", - "years": "{0} jaroj", - } - - month_names = [ - "", - "januaro", - "februaro", - "marto", - "aprilo", - "majo", - "junio", - "julio", - "aŭgusto", - "septembro", - "oktobro", - "novembro", - "decembro", - ] - month_abbreviations = [ - "", - "jan", - "feb", - "mar", - "apr", - "maj", - "jun", - "jul", - "aŭg", - "sep", - "okt", - "nov", - "dec", - ] - - day_names = [ - "", - "lundo", - "mardo", - "merkredo", - "ĵaŭdo", - "vendredo", - "sabato", - "dimanĉo", - ] - day_abbreviations = ["", "lun", "mar", "mer", "ĵaŭ", "ven", "sab", "dim"] - - meridians = {"am": "atm", "pm": "ptm", "AM": "ATM", "PM": "PTM"} - - ordinal_day_re = r"((?P[1-3]?[0-9](?=a))a)" - - def _ordinal_number(self, n: int) -> str: - return f"{n}a" - - -class ThaiLocale(Locale): - names = ["th", "th-th"] - - past = "{0} ที่ผ่านมา" - future = "ในอีก {0}" - - timeframes = { - "now": "ขณะนี้", - "second": "วินาที", - "seconds": "{0} ไม่กี่วินาที", - "minute": "1 นาที", - "minutes": "{0} นาที", - "hour": "1 ชั่วโมง", - "hours": "{0} ชั่วโมง", - "day": "1 วัน", - "days": "{0} วัน", - "month": "1 เดือน", - "months": "{0} เดือน", - "year": "1 ปี", - "years": "{0} ปี", - } - - month_names = [ - "", - "มกราคม", - "กุมภาพันธ์", - "มีนาคม", - "เมษายน", - "พฤษภาคม", - "มิถุนายน", - "กรกฎาคม", - "สิงหาคม", - "กันยายน", - "ตุลาคม", - "พฤศจิกายน", - "ธันวาคม", - ] - month_abbreviations = [ - "", - "ม.ค.", - "ก.พ.", - "มี.ค.", - "เม.ย.", - "พ.ค.", - "มิ.ย.", - "ก.ค.", - "ส.ค.", - "ก.ย.", - "ต.ค.", - "พ.ย.", - "ธ.ค.", - ] - - day_names = ["", "จันทร์", "อังคาร", "พุธ", "พฤหัสบดี", "ศุกร์", "เสาร์", "อาทิตย์"] - day_abbreviations = ["", "จ", "อ", "พ", "พฤ", "ศ", "ส", "อา"] - - meridians = {"am": "am", "pm": "pm", "AM": "AM", "PM": "PM"} - - BE_OFFSET = 543 - - def year_full(self, year: int) -> str: - """Thai always use Buddhist Era (BE) which is CE + 543""" - year += self.BE_OFFSET - return f"{year:04d}" - - def year_abbreviation(self, year: int) -> str: - """Thai always use Buddhist Era (BE) which is CE + 543""" - year += self.BE_OFFSET - return f"{year:04d}"[2:] - - def _format_relative( - self, - humanized: str, - timeframe: TimeFrameLiteral, - delta: Union[float, int], - ) -> str: - """Thai normally doesn't have any space between words""" - if timeframe == "now": - return humanized - - direction = self.past if delta < 0 else self.future - relative_string = direction.format(humanized) - - if timeframe == "seconds": - relative_string = relative_string.replace(" ", "") - - return relative_string - - -class LaotianLocale(Locale): - - names = ["lo", "lo-la"] - - past = "{0} ກ່ອນຫນ້ານີ້" - future = "ໃນ {0}" - - timeframes = { - "now": "ດຽວນີ້", - "second": "ວິນາທີ", - "seconds": "{0} ວິນາທີ", - "minute": "ນາທີ", - "minutes": "{0} ນາທີ", - "hour": "ຊົ່ວໂມງ", - "hours": "{0} ຊົ່ວໂມງ", - "day": "ມື້", - "days": "{0} ມື້", - "week": "ອາທິດ", - "weeks": "{0} ອາທິດ", - "month": "ເດືອນ", - "months": "{0} ເດືອນ", - "year": "ປີ", - "years": "{0} ປີ", - } - - month_names = [ - "", - "ມັງກອນ", # mangkon - "ກຸມພາ", # kumpha - "ມີນາ", # mina - "ເມສາ", # mesa - "ພຶດສະພາ", # phudsapha - "ມິຖຸນາ", # mithuna - "ກໍລະກົດ", # kolakod - "ສິງຫາ", # singha - "ກັນຍາ", # knaia - "ຕຸລາ", # tula - "ພະຈິກ", # phachik - "ທັນວາ", # thanuaa - ] - month_abbreviations = [ - "", - "ມັງກອນ", - "ກຸມພາ", - "ມີນາ", - "ເມສາ", - "ພຶດສະພາ", - "ມິຖຸນາ", - "ກໍລະກົດ", - "ສິງຫາ", - "ກັນຍາ", - "ຕຸລາ", - "ພະຈິກ", - "ທັນວາ", - ] - - day_names = [ - "", - "ວັນຈັນ", # vanchan - "ວັນອັງຄານ", # vnoangkhan - "ວັນພຸດ", # vanphud - "ວັນພະຫັດ", # vanphahad - "ວັນ​ສຸກ", # vansuk - "ວັນເສົາ", # vansao - "ວັນອາທິດ", # vnoathid - ] - day_abbreviations = [ - "", - "ວັນຈັນ", - "ວັນອັງຄານ", - "ວັນພຸດ", - "ວັນພະຫັດ", - "ວັນ​ສຸກ", - "ວັນເສົາ", - "ວັນອາທິດ", - ] - - BE_OFFSET = 543 - - def year_full(self, year: int) -> str: - """Lao always use Buddhist Era (BE) which is CE + 543""" - year += self.BE_OFFSET - return f"{year:04d}" - - def year_abbreviation(self, year: int) -> str: - """Lao always use Buddhist Era (BE) which is CE + 543""" - year += self.BE_OFFSET - return f"{year:04d}"[2:] - - def _format_relative( - self, - humanized: str, - timeframe: TimeFrameLiteral, - delta: Union[float, int], - ) -> str: - """Lao normally doesn't have any space between words""" - if timeframe == "now": - return humanized - - direction = self.past if delta < 0 else self.future - relative_string = direction.format(humanized) - - if timeframe == "seconds": - relative_string = relative_string.replace(" ", "") - - return relative_string - - -class BengaliLocale(Locale): - names = ["bn", "bn-bd", "bn-in"] - - past = "{0} আগে" - future = "{0} পরে" - - timeframes = { - "now": "এখন", - "second": "একটি দ্বিতীয়", - "seconds": "{0} সেকেন্ড", - "minute": "এক মিনিট", - "minutes": "{0} মিনিট", - "hour": "এক ঘণ্টা", - "hours": "{0} ঘণ্টা", - "day": "এক দিন", - "days": "{0} দিন", - "month": "এক মাস", - "months": "{0} মাস ", - "year": "এক বছর", - "years": "{0} বছর", - } - - meridians = {"am": "সকাল", "pm": "বিকাল", "AM": "সকাল", "PM": "বিকাল"} - - month_names = [ - "", - "জানুয়ারি", - "ফেব্রুয়ারি", - "মার্চ", - "এপ্রিল", - "মে", - "জুন", - "জুলাই", - "আগস্ট", - "সেপ্টেম্বর", - "অক্টোবর", - "নভেম্বর", - "ডিসেম্বর", - ] - month_abbreviations = [ - "", - "জানু", - "ফেব", - "মার্চ", - "এপ্রি", - "মে", - "জুন", - "জুল", - "অগা", - "সেপ্ট", - "অক্টো", - "নভে", - "ডিসে", - ] - - day_names = [ - "", - "সোমবার", - "মঙ্গলবার", - "বুধবার", - "বৃহস্পতিবার", - "শুক্রবার", - "শনিবার", - "রবিবার", - ] - day_abbreviations = ["", "সোম", "মঙ্গল", "বুধ", "বৃহঃ", "শুক্র", "শনি", "রবি"] - - def _ordinal_number(self, n: int) -> str: - if n > 10 or n == 0: - return f"{n}তম" - if n in [1, 5, 7, 8, 9, 10]: - return f"{n}ম" - if n in [2, 3]: - return f"{n}য়" - if n == 4: - return f"{n}র্থ" - if n == 6: - return f"{n}ষ্ঠ" - - -class RomanshLocale(Locale): - names = ["rm", "rm-ch"] - - past = "avant {0}" - future = "en {0}" - - timeframes = { - "now": "en quest mument", - "second": "in secunda", - "seconds": "{0} secundas", - "minute": "ina minuta", - "minutes": "{0} minutas", - "hour": "in'ura", - "hours": "{0} ura", - "day": "in di", - "days": "{0} dis", - "month": "in mais", - "months": "{0} mais", - "year": "in onn", - "years": "{0} onns", - } - - month_names = [ - "", - "schaner", - "favrer", - "mars", - "avrigl", - "matg", - "zercladur", - "fanadur", - "avust", - "settember", - "october", - "november", - "december", - ] - - month_abbreviations = [ - "", - "schan", - "fav", - "mars", - "avr", - "matg", - "zer", - "fan", - "avu", - "set", - "oct", - "nov", - "dec", - ] - - day_names = [ - "", - "glindesdi", - "mardi", - "mesemna", - "gievgia", - "venderdi", - "sonda", - "dumengia", - ] - - day_abbreviations = ["", "gli", "ma", "me", "gie", "ve", "so", "du"] - - -class RomanianLocale(Locale): - names = ["ro", "ro-ro"] - - past = "{0} în urmă" - future = "peste {0}" - and_word = "și" - - timeframes = { - "now": "acum", - "second": "o secunda", - "seconds": "{0} câteva secunde", - "minute": "un minut", - "minutes": "{0} minute", - "hour": "o oră", - "hours": "{0} ore", - "day": "o zi", - "days": "{0} zile", - "month": "o lună", - "months": "{0} luni", - "year": "un an", - "years": "{0} ani", - } - - month_names = [ - "", - "ianuarie", - "februarie", - "martie", - "aprilie", - "mai", - "iunie", - "iulie", - "august", - "septembrie", - "octombrie", - "noiembrie", - "decembrie", - ] - month_abbreviations = [ - "", - "ian", - "febr", - "mart", - "apr", - "mai", - "iun", - "iul", - "aug", - "sept", - "oct", - "nov", - "dec", - ] - - day_names = [ - "", - "luni", - "marți", - "miercuri", - "joi", - "vineri", - "sâmbătă", - "duminică", - ] - day_abbreviations = ["", "Lun", "Mar", "Mie", "Joi", "Vin", "Sâm", "Dum"] - - -class SlovenianLocale(Locale): - names = ["sl", "sl-si"] - - past = "pred {0}" - future = "čez {0}" - and_word = "in" - - timeframes = { - "now": "zdaj", - "second": "sekundo", - "seconds": "{0} sekund", - "minute": "minuta", - "minutes": "{0} minutami", - "hour": "uro", - "hours": "{0} ur", - "day": "dan", - "days": "{0} dni", - "month": "mesec", - "months": "{0} mesecev", - "year": "leto", - "years": "{0} let", - } - - meridians = {"am": "", "pm": "", "AM": "", "PM": ""} - - month_names = [ - "", - "Januar", - "Februar", - "Marec", - "April", - "Maj", - "Junij", - "Julij", - "Avgust", - "September", - "Oktober", - "November", - "December", - ] - - month_abbreviations = [ - "", - "Jan", - "Feb", - "Mar", - "Apr", - "Maj", - "Jun", - "Jul", - "Avg", - "Sep", - "Okt", - "Nov", - "Dec", - ] - - day_names = [ - "", - "Ponedeljek", - "Torek", - "Sreda", - "Četrtek", - "Petek", - "Sobota", - "Nedelja", - ] - - day_abbreviations = ["", "Pon", "Tor", "Sre", "Čet", "Pet", "Sob", "Ned"] - - -class IndonesianLocale(Locale): - names = ["id", "id-id"] - - past = "{0} yang lalu" - future = "dalam {0}" - and_word = "dan" - - timeframes = { - "now": "baru saja", - "second": "1 sebentar", - "seconds": "{0} detik", - "minute": "1 menit", - "minutes": "{0} menit", - "hour": "1 jam", - "hours": "{0} jam", - "day": "1 hari", - "days": "{0} hari", - "week": "1 minggu", - "weeks": "{0} minggu", - "month": "1 bulan", - "months": "{0} bulan", - "quarter": "1 kuartal", - "quarters": "{0} kuartal", - "year": "1 tahun", - "years": "{0} tahun", - } - - meridians = {"am": "", "pm": "", "AM": "", "PM": ""} - - month_names = [ - "", - "Januari", - "Februari", - "Maret", - "April", - "Mei", - "Juni", - "Juli", - "Agustus", - "September", - "Oktober", - "November", - "Desember", - ] - - month_abbreviations = [ - "", - "Jan", - "Feb", - "Mar", - "Apr", - "Mei", - "Jun", - "Jul", - "Ags", - "Sept", - "Okt", - "Nov", - "Des", - ] - - day_names = ["", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu", "Minggu"] - - day_abbreviations = [ - "", - "Senin", - "Selasa", - "Rabu", - "Kamis", - "Jumat", - "Sabtu", - "Minggu", - ] - - -class NepaliLocale(Locale): - names = ["ne", "ne-np"] - - past = "{0} पहिले" - future = "{0} पछी" - - timeframes = { - "now": "अहिले", - "second": "एक सेकेन्ड", - "seconds": "{0} सेकण्ड", - "minute": "मिनेट", - "minutes": "{0} मिनेट", - "hour": "एक घण्टा", - "hours": "{0} घण्टा", - "day": "एक दिन", - "days": "{0} दिन", - "month": "एक महिना", - "months": "{0} महिना", - "year": "एक बर्ष", - "years": "{0} बर्ष", - } - - meridians = {"am": "पूर्वाह्न", "pm": "अपरान्ह", "AM": "पूर्वाह्न", "PM": "अपरान्ह"} - - month_names = [ - "", - "जनवरी", - "फेब्रुअरी", - "मार्च", - "एप्रील", - "मे", - "जुन", - "जुलाई", - "अगष्ट", - "सेप्टेम्बर", - "अक्टोबर", - "नोवेम्बर", - "डिसेम्बर", - ] - month_abbreviations = [ - "", - "जन", - "फेब", - "मार्च", - "एप्रील", - "मे", - "जुन", - "जुलाई", - "अग", - "सेप", - "अक्ट", - "नोव", - "डिस", - ] - - day_names = [ - "", - "सोमवार", - "मंगलवार", - "बुधवार", - "बिहिवार", - "शुक्रवार", - "शनिवार", - "आइतवार", - ] - - day_abbreviations = ["", "सोम", "मंगल", "बुध", "बिहि", "शुक्र", "शनि", "आइत"] - - -class EstonianLocale(Locale): - names = ["ee", "et"] - - past = "{0} tagasi" - future = "{0} pärast" - and_word = "ja" - - timeframes: ClassVar[Mapping[TimeFrameLiteral, Mapping[str, str]]] = { - "now": {"past": "just nüüd", "future": "just nüüd"}, - "second": {"past": "üks sekund", "future": "ühe sekundi"}, - "seconds": {"past": "{0} sekundit", "future": "{0} sekundi"}, - "minute": {"past": "üks minut", "future": "ühe minuti"}, - "minutes": {"past": "{0} minutit", "future": "{0} minuti"}, - "hour": {"past": "tund aega", "future": "tunni aja"}, - "hours": {"past": "{0} tundi", "future": "{0} tunni"}, - "day": {"past": "üks päev", "future": "ühe päeva"}, - "days": {"past": "{0} päeva", "future": "{0} päeva"}, - "month": {"past": "üks kuu", "future": "ühe kuu"}, - "months": {"past": "{0} kuud", "future": "{0} kuu"}, - "year": {"past": "üks aasta", "future": "ühe aasta"}, - "years": {"past": "{0} aastat", "future": "{0} aasta"}, - } - - month_names = [ - "", - "Jaanuar", - "Veebruar", - "Märts", - "Aprill", - "Mai", - "Juuni", - "Juuli", - "August", - "September", - "Oktoober", - "November", - "Detsember", - ] - month_abbreviations = [ - "", - "Jan", - "Veb", - "Mär", - "Apr", - "Mai", - "Jun", - "Jul", - "Aug", - "Sep", - "Okt", - "Nov", - "Dets", - ] - - day_names = [ - "", - "Esmaspäev", - "Teisipäev", - "Kolmapäev", - "Neljapäev", - "Reede", - "Laupäev", - "Pühapäev", - ] - day_abbreviations = ["", "Esm", "Teis", "Kolm", "Nelj", "Re", "Lau", "Püh"] - - def _format_timeframe(self, timeframe: TimeFrameLiteral, delta: int) -> str: - form = self.timeframes[timeframe] - if delta > 0: - _form = form["future"] - else: - _form = form["past"] - return _form.format(abs(delta)) - - -class LatvianLocale(Locale): - names = ["lv", "lv-lv"] - - past = "pirms {0}" - future = "pēc {0}" - and_word = "un" - - timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = { - "now": "tagad", - "second": "sekundes", - "seconds": "{0} sekundēm", - "minute": "minūtes", - "minutes": "{0} minūtēm", - "hour": "stundas", - "hours": "{0} stundām", - "day": "dienas", - "days": "{0} dienām", - "week": "nedēļas", - "weeks": "{0} nedēļām", - "month": "mēneša", - "months": "{0} mēnešiem", - "year": "gada", - "years": "{0} gadiem", - } - - month_names = [ - "", - "janvāris", - "februāris", - "marts", - "aprīlis", - "maijs", - "jūnijs", - "jūlijs", - "augusts", - "septembris", - "oktobris", - "novembris", - "decembris", - ] - - month_abbreviations = [ - "", - "jan", - "feb", - "marts", - "apr", - "maijs", - "jūnijs", - "jūlijs", - "aug", - "sept", - "okt", - "nov", - "dec", - ] - - day_names = [ - "", - "pirmdiena", - "otrdiena", - "trešdiena", - "ceturtdiena", - "piektdiena", - "sestdiena", - "svētdiena", - ] - - day_abbreviations = [ - "", - "pi", - "ot", - "tr", - "ce", - "pi", - "se", - "sv", - ] - - -class SwahiliLocale(Locale): - names = [ - "sw", - "sw-ke", - "sw-tz", - ] - - past = "{0} iliyopita" - future = "muda wa {0}" - and_word = "na" - - timeframes = { - "now": "sasa hivi", - "second": "sekunde", - "seconds": "sekunde {0}", - "minute": "dakika moja", - "minutes": "dakika {0}", - "hour": "saa moja", - "hours": "saa {0}", - "day": "siku moja", - "days": "siku {0}", - "week": "wiki moja", - "weeks": "wiki {0}", - "month": "mwezi moja", - "months": "miezi {0}", - "year": "mwaka moja", - "years": "miaka {0}", - } - - meridians = {"am": "asu", "pm": "mch", "AM": "ASU", "PM": "MCH"} - - month_names = [ - "", - "Januari", - "Februari", - "Machi", - "Aprili", - "Mei", - "Juni", - "Julai", - "Agosti", - "Septemba", - "Oktoba", - "Novemba", - "Desemba", - ] - month_abbreviations = [ - "", - "Jan", - "Feb", - "Mac", - "Apr", - "Mei", - "Jun", - "Jul", - "Ago", - "Sep", - "Okt", - "Nov", - "Des", - ] - - day_names = [ - "", - "Jumatatu", - "Jumanne", - "Jumatano", - "Alhamisi", - "Ijumaa", - "Jumamosi", - "Jumapili", - ] - day_abbreviations = [ - "", - "Jumatatu", - "Jumanne", - "Jumatano", - "Alhamisi", - "Ijumaa", - "Jumamosi", - "Jumapili", - ] - - -class CroatianLocale(Locale): - names = ["hr", "hr-hr"] - - past = "prije {0}" - future = "za {0}" - and_word = "i" - - timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = { - "now": "upravo sad", - "second": "sekundu", - "seconds": {"double": "{0} sekunde", "higher": "{0} sekundi"}, - "minute": "minutu", - "minutes": {"double": "{0} minute", "higher": "{0} minuta"}, - "hour": "sat", - "hours": {"double": "{0} sata", "higher": "{0} sati"}, - "day": "jedan dan", - "days": {"double": "{0} dana", "higher": "{0} dana"}, - "week": "tjedan", - "weeks": {"double": "{0} tjedna", "higher": "{0} tjedana"}, - "month": "mjesec", - "months": {"double": "{0} mjeseca", "higher": "{0} mjeseci"}, - "year": "godinu", - "years": {"double": "{0} godine", "higher": "{0} godina"}, - } - - month_names = [ - "", - "siječanj", - "veljača", - "ožujak", - "travanj", - "svibanj", - "lipanj", - "srpanj", - "kolovoz", - "rujan", - "listopad", - "studeni", - "prosinac", - ] - - month_abbreviations = [ - "", - "siječ", - "velj", - "ožuj", - "trav", - "svib", - "lip", - "srp", - "kol", - "ruj", - "list", - "stud", - "pros", - ] - - day_names = [ - "", - "ponedjeljak", - "utorak", - "srijeda", - "četvrtak", - "petak", - "subota", - "nedjelja", - ] - - day_abbreviations = [ - "", - "po", - "ut", - "sr", - "če", - "pe", - "su", - "ne", - ] - - def _format_timeframe(self, timeframe: TimeFrameLiteral, delta: int) -> str: - form = self.timeframes[timeframe] - delta = abs(delta) - if isinstance(form, Mapping): - if 1 < delta <= 4: - form = form["double"] - else: - form = form["higher"] - - return form.format(delta) - - -class LatinLocale(Locale): - names = ["la", "la-va"] - - past = "ante {0}" - future = "in {0}" - and_word = "et" - - timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = { - "now": "nunc", - "second": "secundum", - "seconds": "{0} secundis", - "minute": "minutam", - "minutes": "{0} minutis", - "hour": "horam", - "hours": "{0} horas", - "day": "diem", - "days": "{0} dies", - "week": "hebdomadem", - "weeks": "{0} hebdomades", - "month": "mensem", - "months": "{0} mensis", - "year": "annum", - "years": "{0} annos", - } - - month_names = [ - "", - "Ianuarius", - "Februarius", - "Martius", - "Aprilis", - "Maius", - "Iunius", - "Iulius", - "Augustus", - "September", - "October", - "November", - "December", - ] - - month_abbreviations = [ - "", - "Ian", - "Febr", - "Mart", - "Apr", - "Mai", - "Iun", - "Iul", - "Aug", - "Sept", - "Oct", - "Nov", - "Dec", - ] - - day_names = [ - "", - "dies Lunae", - "dies Martis", - "dies Mercurii", - "dies Iovis", - "dies Veneris", - "dies Saturni", - "dies Solis", - ] - - day_abbreviations = [ - "", - "dies Lunae", - "dies Martis", - "dies Mercurii", - "dies Iovis", - "dies Veneris", - "dies Saturni", - "dies Solis", - ] - - -class LithuanianLocale(Locale): - names = ["lt", "lt-lt"] - - past = "prieš {0}" - future = "po {0}" - and_word = "ir" - - timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = { - "now": "dabar", - "second": "sekundės", - "seconds": "{0} sekundžių", - "minute": "minutės", - "minutes": "{0} minučių", - "hour": "valandos", - "hours": "{0} valandų", - "day": "dieną", - "days": "{0} dienų", - "week": "savaitės", - "weeks": "{0} savaičių", - "month": "mėnesio", - "months": "{0} mėnesių", - "year": "metų", - "years": "{0} metų", - } - - month_names = [ - "", - "sausis", - "vasaris", - "kovas", - "balandis", - "gegužė", - "birželis", - "liepa", - "rugpjūtis", - "rugsėjis", - "spalis", - "lapkritis", - "gruodis", - ] - - month_abbreviations = [ - "", - "saus", - "vas", - "kovas", - "bal", - "geg", - "birž", - "liepa", - "rugp", - "rugs", - "spalis", - "lapkr", - "gr", - ] - - day_names = [ - "", - "pirmadienis", - "antradienis", - "trečiadienis", - "ketvirtadienis", - "penktadienis", - "šeštadienis", - "sekmadienis", - ] - - day_abbreviations = [ - "", - "pi", - "an", - "tr", - "ke", - "pe", - "še", - "se", - ] - - -class MalayLocale(Locale): - names = ["ms", "ms-my", "ms-bn"] - - past = "{0} yang lalu" - future = "dalam {0}" - and_word = "dan" - - timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = { - "now": "sekarang", - "second": "saat", - "seconds": "{0} saat", - "minute": "minit", - "minutes": "{0} minit", - "hour": "jam", - "hours": "{0} jam", - "day": "hari", - "days": "{0} hari", - "week": "minggu", - "weeks": "{0} minggu", - "month": "bulan", - "months": "{0} bulan", - "year": "tahun", - "years": "{0} tahun", - } - - month_names = [ - "", - "Januari", - "Februari", - "Mac", - "April", - "Mei", - "Jun", - "Julai", - "Ogos", - "September", - "Oktober", - "November", - "Disember", - ] - - month_abbreviations = [ - "", - "Jan.", - "Feb.", - "Mac", - "Apr.", - "Mei", - "Jun", - "Julai", - "Og.", - "Sept.", - "Okt.", - "Nov.", - "Dis.", - ] - - day_names = [ - "", - "Isnin", - "Selasa", - "Rabu", - "Khamis", - "Jumaat", - "Sabtu", - "Ahad", - ] - - day_abbreviations = [ - "", - "Isnin", - "Selasa", - "Rabu", - "Khamis", - "Jumaat", - "Sabtu", - "Ahad", - ] - - -class MalteseLocale(Locale): - names = ["mt", "mt-mt"] - - past = "{0} ilu" - future = "fi {0}" - and_word = "u" - - timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = { - "now": "issa", - "second": "sekonda", - "seconds": "{0} sekondi", - "minute": "minuta", - "minutes": "{0} minuti", - "hour": "siegħa", - "hours": {"dual": "{0} sagħtejn", "plural": "{0} sigħat"}, - "day": "jum", - "days": {"dual": "{0} jumejn", "plural": "{0} ijiem"}, - "week": "ġimgħa", - "weeks": {"dual": "{0} ġimagħtejn", "plural": "{0} ġimgħat"}, - "month": "xahar", - "months": {"dual": "{0} xahrejn", "plural": "{0} xhur"}, - "year": "sena", - "years": {"dual": "{0} sentejn", "plural": "{0} snin"}, - } - - month_names = [ - "", - "Jannar", - "Frar", - "Marzu", - "April", - "Mejju", - "Ġunju", - "Lulju", - "Awwissu", - "Settembru", - "Ottubru", - "Novembru", - "Diċembru", - ] - - month_abbreviations = [ - "", - "Jan", - "Fr", - "Mar", - "Apr", - "Mejju", - "Ġun", - "Lul", - "Aw", - "Sett", - "Ott", - "Nov", - "Diċ", - ] - - day_names = [ - "", - "It-Tnejn", - "It-Tlieta", - "L-Erbgħa", - "Il-Ħamis", - "Il-Ġimgħa", - "Is-Sibt", - "Il-Ħadd", - ] - - day_abbreviations = [ - "", - "T", - "TL", - "E", - "Ħ", - "Ġ", - "S", - "Ħ", - ] - - def _format_timeframe(self, timeframe: TimeFrameLiteral, delta: int) -> str: - form = self.timeframes[timeframe] - delta = abs(delta) - if isinstance(form, Mapping): - if delta == 2: - form = form["dual"] - else: - form = form["plural"] - - return form.format(delta) - - -class SamiLocale(Locale): - names = ["se", "se-fi", "se-no", "se-se"] - - past = "{0} dassái" - future = "{0} " # NOTE: couldn't find preposition for Sami here, none needed? - - timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = { - "now": "dál", - "second": "sekunda", - "seconds": "{0} sekundda", - "minute": "minuhta", - "minutes": "{0} minuhta", - "hour": "diimmu", - "hours": "{0} diimmu", - "day": "beaivvi", - "days": "{0} beaivvi", - "week": "vahku", - "weeks": "{0} vahku", - "month": "mánu", - "months": "{0} mánu", - "year": "jagi", - "years": "{0} jagi", - } - - month_names = [ - "", - "Ođđajagimánnu", - "Guovvamánnu", - "Njukčamánnu", - "Cuoŋománnu", - "Miessemánnu", - "Geassemánnu", - "Suoidnemánnu", - "Borgemánnu", - "Čakčamánnu", - "Golggotmánnu", - "Skábmamánnu", - "Juovlamánnu", - ] - - month_abbreviations = [ - "", - "Ođđajagimánnu", - "Guovvamánnu", - "Njukčamánnu", - "Cuoŋománnu", - "Miessemánnu", - "Geassemánnu", - "Suoidnemánnu", - "Borgemánnu", - "Čakčamánnu", - "Golggotmánnu", - "Skábmamánnu", - "Juovlamánnu", - ] - - day_names = [ - "", - "Mánnodat", - "Disdat", - "Gaskavahkku", - "Duorastat", - "Bearjadat", - "Lávvordat", - "Sotnabeaivi", - ] - - day_abbreviations = [ - "", - "Mánnodat", - "Disdat", - "Gaskavahkku", - "Duorastat", - "Bearjadat", - "Lávvordat", - "Sotnabeaivi", - ] - - -class OdiaLocale(Locale): - names = ["or", "or-in"] - - past = "{0} ପୂର୍ବେ" - future = "{0} ପରେ" - - timeframes = { - "now": "ବର୍ତ୍ତମାନ", - "second": "ଏକ ସେକେଣ୍ଡ", - "seconds": "{0} ସେକେଣ୍ଡ", - "minute": "ଏକ ମିନଟ", - "minutes": "{0} ମିନଟ", - "hour": "ଏକ ଘଣ୍ଟା", - "hours": "{0} ଘଣ୍ଟା", - "day": "ଏକ ଦିନ", - "days": "{0} ଦିନ", - "month": "ଏକ ମାସ", - "months": "{0} ମାସ ", - "year": "ଏକ ବର୍ଷ", - "years": "{0} ବର୍ଷ", - } - - meridians = {"am": "ପୂର୍ବାହ୍ନ", "pm": "ଅପରାହ୍ନ", "AM": "ପୂର୍ବାହ୍ନ", "PM": "ଅପରାହ୍ନ"} - - month_names = [ - "", - "ଜାନୁଆରୀ", - "ଫେବୃଆରୀ", - "ମାର୍ଚ୍ଚ୍", - "ଅପ୍ରେଲ", - "ମଇ", - "ଜୁନ୍", - "ଜୁଲାଇ", - "ଅଗଷ୍ଟ", - "ସେପ୍ଟେମ୍ବର", - "ଅକ୍ଟୋବର୍", - "ନଭେମ୍ବର୍", - "ଡିସେମ୍ବର୍", - ] - month_abbreviations = [ - "", - "ଜାନୁ", - "ଫେବୃ", - "ମାର୍ଚ୍ଚ୍", - "ଅପ୍ରେ", - "ମଇ", - "ଜୁନ୍", - "ଜୁଲା", - "ଅଗ", - "ସେପ୍ଟେ", - "ଅକ୍ଟୋ", - "ନଭେ", - "ଡିସେ", - ] - - day_names = [ - "", - "ସୋମବାର", - "ମଙ୍ଗଳବାର", - "ବୁଧବାର", - "ଗୁରୁବାର", - "ଶୁକ୍ରବାର", - "ଶନିବାର", - "ରବିବାର", - ] - day_abbreviations = [ - "", - "ସୋମ", - "ମଙ୍ଗଳ", - "ବୁଧ", - "ଗୁରୁ", - "ଶୁକ୍ର", - "ଶନି", - "ରବି", - ] - - def _ordinal_number(self, n: int) -> str: - if n > 10 or n == 0: - return f"{n}ତମ" - if n in [1, 5, 7, 8, 9, 10]: - return f"{n}ମ" - if n in [2, 3]: - return f"{n}ୟ" - if n == 4: - return f"{n}ର୍ଥ" - if n == 6: - return f"{n}ଷ୍ଠ" - return "" - - -class SerbianLocale(Locale): - names = ["sr", "sr-rs", "sr-sp"] - - past = "pre {0}" - future = "za {0}" - and_word = "i" - - timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = { - "now": "sada", - "second": "sekundu", - "seconds": {"double": "{0} sekunde", "higher": "{0} sekundi"}, - "minute": "minutu", - "minutes": {"double": "{0} minute", "higher": "{0} minuta"}, - "hour": "sat", - "hours": {"double": "{0} sata", "higher": "{0} sati"}, - "day": "dan", - "days": {"double": "{0} dana", "higher": "{0} dana"}, - "week": "nedelju", - "weeks": {"double": "{0} nedelje", "higher": "{0} nedelja"}, - "month": "mesec", - "months": {"double": "{0} meseca", "higher": "{0} meseci"}, - "year": "godinu", - "years": {"double": "{0} godine", "higher": "{0} godina"}, - } - - month_names = [ - "", - "januar", # јануар - "februar", # фебруар - "mart", # март - "april", # април - "maj", # мај - "jun", # јун - "jul", # јул - "avgust", # август - "septembar", # септембар - "oktobar", # октобар - "novembar", # новембар - "decembar", # децембар - ] - - month_abbreviations = [ - "", - "jan", - "feb", - "mar", - "apr", - "maj", - "jun", - "jul", - "avg", - "sep", - "okt", - "nov", - "dec", - ] - - day_names = [ - "", - "ponedeljak", # понедељак - "utorak", # уторак - "sreda", # среда - "četvrtak", # четвртак - "petak", # петак - "subota", # субота - "nedelja", # недеља - ] - - day_abbreviations = [ - "", - "po", # по - "ut", # ут - "sr", # ср - "če", # че - "pe", # пе - "su", # су - "ne", # не - ] - - def _format_timeframe(self, timeframe: TimeFrameLiteral, delta: int) -> str: - form = self.timeframes[timeframe] - delta = abs(delta) - if isinstance(form, Mapping): - if 1 < delta <= 4: - form = form["double"] - else: - form = form["higher"] - - return form.format(delta) - - -class LuxembourgishLocale(Locale): - names = ["lb", "lb-lu"] - - past = "virun {0}" - future = "an {0}" - and_word = "an" - - timeframes = { - "now": "just elo", - "second": "enger Sekonn", - "seconds": "{0} Sekonnen", - "minute": "enger Minutt", - "minutes": "{0} Minutten", - "hour": "enger Stonn", - "hours": "{0} Stonnen", - "day": "engem Dag", - "days": "{0} Deeg", - "week": "enger Woch", - "weeks": "{0} Wochen", - "month": "engem Mount", - "months": "{0} Méint", - "year": "engem Joer", - "years": "{0} Jahren", - } - - timeframes_only_distance = timeframes.copy() - timeframes_only_distance["second"] = "eng Sekonn" - timeframes_only_distance["minute"] = "eng Minutt" - timeframes_only_distance["hour"] = "eng Stonn" - timeframes_only_distance["day"] = "een Dag" - timeframes_only_distance["days"] = "{0} Deeg" - timeframes_only_distance["week"] = "eng Woch" - timeframes_only_distance["month"] = "ee Mount" - timeframes_only_distance["months"] = "{0} Méint" - timeframes_only_distance["year"] = "ee Joer" - timeframes_only_distance["years"] = "{0} Joer" - - month_names = [ - "", - "Januar", - "Februar", - "Mäerz", - "Abrëll", - "Mee", - "Juni", - "Juli", - "August", - "September", - "Oktouber", - "November", - "Dezember", - ] - - month_abbreviations = [ - "", - "Jan", - "Feb", - "Mäe", - "Abr", - "Mee", - "Jun", - "Jul", - "Aug", - "Sep", - "Okt", - "Nov", - "Dez", - ] - - day_names = [ - "", - "Méindeg", - "Dënschdeg", - "Mëttwoch", - "Donneschdeg", - "Freideg", - "Samschdeg", - "Sonndeg", - ] - - day_abbreviations = ["", "Méi", "Dën", "Mët", "Don", "Fre", "Sam", "Son"] - - def _ordinal_number(self, n: int) -> str: - return f"{n}." - - def describe( - self, - timeframe: TimeFrameLiteral, - delta: Union[int, float] = 0, - only_distance: bool = False, - ) -> str: - if not only_distance: - return super().describe(timeframe, delta, only_distance) - - # Luxembourgish uses a different case without 'in' or 'ago' - humanized = self.timeframes_only_distance[timeframe].format(trunc(abs(delta))) - - return humanized - - -class ZuluLocale(Locale): - names = ["zu", "zu-za"] - - past = "{0} edlule" - future = "{0} " - and_word = "futhi" - - timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[Mapping[str, str], str]]] = { - "now": "manje", - "second": {"past": "umzuzwana", "future": "ngomzuzwana"}, - "seconds": {"past": "{0} imizuzwana", "future": "{0} ngemizuzwana"}, - "minute": {"past": "umzuzu", "future": "ngomzuzu"}, - "minutes": {"past": "{0} imizuzu", "future": "{0} ngemizuzu"}, - "hour": {"past": "ihora", "future": "ngehora"}, - "hours": {"past": "{0} amahora", "future": "{0} emahoreni"}, - "day": {"past": "usuku", "future": "ngosuku"}, - "days": {"past": "{0} izinsuku", "future": "{0} ezinsukwini"}, - "week": {"past": "isonto", "future": "ngesonto"}, - "weeks": {"past": "{0} amasonto", "future": "{0} emasontweni"}, - "month": {"past": "inyanga", "future": "ngenyanga"}, - "months": {"past": "{0} izinyanga", "future": "{0} ezinyangeni"}, - "year": {"past": "unyaka", "future": "ngonyak"}, - "years": {"past": "{0} iminyaka", "future": "{0} eminyakeni"}, - } - - def _format_timeframe(self, timeframe: TimeFrameLiteral, delta: int) -> str: - """Zulu aware time frame format function, takes into account - the differences between past and future forms.""" - abs_delta = abs(delta) - form = self.timeframes[timeframe] - - if isinstance(form, str): - return form.format(abs_delta) - - if delta > 0: - key = "future" - else: - key = "past" - form = form[key] - - return form.format(abs_delta) - - month_names = [ - "", - "uMasingane", - "uNhlolanja", - "uNdasa", - "UMbasa", - "UNhlaba", - "UNhlangulana", - "uNtulikazi", - "UNcwaba", - "uMandulo", - "uMfumfu", - "uLwezi", - "uZibandlela", - ] - - month_abbreviations = [ - "", - "uMasingane", - "uNhlolanja", - "uNdasa", - "UMbasa", - "UNhlaba", - "UNhlangulana", - "uNtulikazi", - "UNcwaba", - "uMandulo", - "uMfumfu", - "uLwezi", - "uZibandlela", - ] - - day_names = [ - "", - "uMsombuluko", - "uLwesibili", - "uLwesithathu", - "uLwesine", - "uLwesihlanu", - "uMgqibelo", - "iSonto", - ] - - day_abbreviations = [ - "", - "uMsombuluko", - "uLwesibili", - "uLwesithathu", - "uLwesine", - "uLwesihlanu", - "uMgqibelo", - "iSonto", - ] - - -class TamilLocale(Locale): - names = ["ta", "ta-in", "ta-lk"] - - past = "{0} நேரத்திற்கு முன்பு" - future = "இல் {0}" - - timeframes = { - "now": "இப்போது", - "second": "ஒரு இரண்டாவது", - "seconds": "{0} விநாடிகள்", - "minute": "ஒரு நிமிடம்", - "minutes": "{0} நிமிடங்கள்", - "hour": "ஒரு மணி", - "hours": "{0} மணிநேரம்", - "day": "ஒரு நாள்", - "days": "{0} நாட்கள்", - "week": "ஒரு வாரம்", - "weeks": "{0} வாரங்கள்", - "month": "ஒரு மாதம்", - "months": "{0} மாதங்கள்", - "year": "ஒரு ஆண்டு", - "years": "{0} ஆண்டுகள்", - } - - month_names = [ - "", - "சித்திரை", - "வைகாசி", - "ஆனி", - "ஆடி", - "ஆவணி", - "புரட்டாசி", - "ஐப்பசி", - "கார்த்திகை", - "மார்கழி", - "தை", - "மாசி", - "பங்குனி", - ] - - month_abbreviations = [ - "", - "ஜன", - "பிப்", - "மார்", - "ஏப்", - "மே", - "ஜூன்", - "ஜூலை", - "ஆக", - "செப்", - "அக்", - "நவ", - "டிச", - ] - - day_names = [ - "", - "திங்கட்கிழமை", - "செவ்வாய்க்கிழமை", - "புதன்கிழமை", - "வியாழக்கிழமை", - "வெள்ளிக்கிழமை", - "சனிக்கிழமை", - "ஞாயிற்றுக்கிழமை", - ] - - day_abbreviations = [ - "", - "திங்கட்", - "செவ்வாய்", - "புதன்", - "வியாழன்", - "வெள்ளி", - "சனி", - "ஞாயிறு", - ] - - def _ordinal_number(self, n: int) -> str: - if n == 1: - return f"{n}வது" - elif n >= 0: - return f"{n}ஆம்" - else: - return "" - - -class AlbanianLocale(Locale): - names = ["sq", "sq-al"] - - past = "{0} më parë" - future = "në {0}" - and_word = "dhe" - - timeframes = { - "now": "tani", - "second": "sekondë", - "seconds": "{0} sekonda", - "minute": "minutë", - "minutes": "{0} minuta", - "hour": "orë", - "hours": "{0} orë", - "day": "ditë", - "days": "{0} ditë", - "week": "javë", - "weeks": "{0} javë", - "month": "muaj", - "months": "{0} muaj", - "year": "vit", - "years": "{0} vjet", - } - - month_names = [ - "", - "janar", - "shkurt", - "mars", - "prill", - "maj", - "qershor", - "korrik", - "gusht", - "shtator", - "tetor", - "nëntor", - "dhjetor", - ] - - month_abbreviations = [ - "", - "jan", - "shk", - "mar", - "pri", - "maj", - "qer", - "korr", - "gush", - "sht", - "tet", - "nën", - "dhj", - ] - - day_names = [ - "", - "e hënë", - "e martë", - "e mërkurë", - "e enjte", - "e premte", - "e shtunë", - "e diel", - ] - - day_abbreviations = [ - "", - "hën", - "mar", - "mër", - "enj", - "pre", - "sht", - "die", - ] - - -class GeorgianLocale(Locale): - names = ["ka", "ka-ge"] - - past = "{0} წინ" # ts’in - future = "{0} შემდეგ" # shemdeg - and_word = "და" # da - - timeframes = { - "now": "ახლა", # akhla - # When a cardinal qualifies a noun, it stands in the singular - "second": "წამის", # ts’amis - "seconds": "{0} წამის", - "minute": "წუთის", # ts’utis - "minutes": "{0} წუთის", - "hour": "საათის", # saatis - "hours": "{0} საათის", - "day": "დღის", # dghis - "days": "{0} დღის", - "week": "კვირის", # k’viris - "weeks": "{0} კვირის", - "month": "თვის", # tvis - "months": "{0} თვის", - "year": "წლის", # ts’lis - "years": "{0} წლის", - } - - month_names = [ - # modern month names - "", - "იანვარი", # Ianvari - "თებერვალი", # Tebervali - "მარტი", # Mart'i - "აპრილი", # Ap'rili - "მაისი", # Maisi - "ივნისი", # Ivnisi - "ივლისი", # Ivlisi - "აგვისტო", # Agvist'o - "სექტემბერი", # Sekt'emberi - "ოქტომბერი", # Okt'omberi - "ნოემბერი", # Noemberi - "დეკემბერი", # Dek'emberi - ] - - month_abbreviations = [ - # no abbr. found yet - "", - "იანვარი", # Ianvari - "თებერვალი", # Tebervali - "მარტი", # Mart'i - "აპრილი", # Ap'rili - "მაისი", # Maisi - "ივნისი", # Ivnisi - "ივლისი", # Ivlisi - "აგვისტო", # Agvist'o - "სექტემბერი", # Sekt'emberi - "ოქტომბერი", # Okt'omberi - "ნოემბერი", # Noemberi - "დეკემბერი", # Dek'emberi - ] - - day_names = [ - "", - "ორშაბათი", # orshabati - "სამშაბათი", # samshabati - "ოთხშაბათი", # otkhshabati - "ხუთშაბათი", # khutshabati - "პარასკევი", # p’arask’evi - "შაბათი", # shabati - # "k’vira" also serves as week; to avoid confusion "k’vira-dge" can be used for Sunday - "კვირა", # k’vira - ] - - day_abbreviations = [ - "", - "ორშაბათი", # orshabati - "სამშაბათი", # samshabati - "ოთხშაბათი", # otkhshabati - "ხუთშაბათი", # khutshabati - "პარასკევი", # p’arask’evi - "შაბათი", # shabati - "კვირა", # k’vira - ] - - -class SinhalaLocale(Locale): - names = ["si", "si-lk"] - - past = "{0}ට පෙර" - future = "{0}" - and_word = "සහ" - - timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[Mapping[str, str], str]]] = { - "now": "දැන්", - "second": { - "past": "තත්පරයක", - "future": "තත්පරයකින්", - }, # ක් is the article - "seconds": { - "past": "තත්පර {0} ක", - "future": "තත්පර {0} කින්", - }, - "minute": { - "past": "විනාඩියක", - "future": "විනාඩියකින්", - }, - "minutes": { - "past": "විනාඩි {0} ක", - "future": "මිනිත්තු {0} කින්", - }, - "hour": {"past": "පැයක", "future": "පැයකින්"}, - "hours": { - "past": "පැය {0} ක", - "future": "පැය {0} කින්", - }, - "day": {"past": "දිනක", "future": "දිනකට"}, - "days": { - "past": "දින {0} ක", - "future": "දින {0} කින්", - }, - "week": {"past": "සතියක", "future": "සතියකින්"}, - "weeks": { - "past": "සති {0} ක", - "future": "සති {0} කින්", - }, - "month": {"past": "මාසයක", "future": "එය මාසය තුළ"}, - "months": { - "past": "මාස {0} ක", - "future": "මාස {0} කින්", - }, - "year": {"past": "වසරක", "future": "වසරක් තුළ"}, - "years": { - "past": "අවුරුදු {0} ක", - "future": "අවුරුදු {0} තුළ", - }, - } - # Sinhala: the general format to describe timeframe is different from past and future, - # so we do not copy the original timeframes dictionary - timeframes_only_distance = {} - timeframes_only_distance["second"] = "තත්පරයක්" - timeframes_only_distance["seconds"] = "තත්පර {0}" - timeframes_only_distance["minute"] = "මිනිත්තුවක්" - timeframes_only_distance["minutes"] = "විනාඩි {0}" - timeframes_only_distance["hour"] = "පැයක්" - timeframes_only_distance["hours"] = "පැය {0}" - timeframes_only_distance["day"] = "දවසක්" - timeframes_only_distance["days"] = "දවස් {0}" - timeframes_only_distance["week"] = "සතියක්" - timeframes_only_distance["weeks"] = "සති {0}" - timeframes_only_distance["month"] = "මාසයක්" - timeframes_only_distance["months"] = "මාස {0}" - timeframes_only_distance["year"] = "අවුරුද්දක්" - timeframes_only_distance["years"] = "අවුරුදු {0}" - - def _format_timeframe(self, timeframe: TimeFrameLiteral, delta: int) -> str: - """ - Sinhala awares time frame format function, takes into account - the differences between general, past, and future forms (three different suffixes). - """ - abs_delta = abs(delta) - form = self.timeframes[timeframe] - - if isinstance(form, str): - return form.format(abs_delta) - - if delta > 0: - key = "future" - else: - key = "past" - form = form[key] - - return form.format(abs_delta) - - def describe( - self, - timeframe: TimeFrameLiteral, - delta: Union[float, int] = 1, # key is always future when only_distance=False - only_distance: bool = False, - ) -> str: - """Describes a delta within a timeframe in plain language. - - :param timeframe: a string representing a timeframe. - :param delta: a quantity representing a delta in a timeframe. - :param only_distance: return only distance eg: "11 seconds" without "in" or "ago" keywords - """ - - if not only_distance: - return super().describe(timeframe, delta, only_distance) - # Sinhala uses a different case without 'in' or 'ago' - humanized = self.timeframes_only_distance[timeframe].format(trunc(abs(delta))) - - return humanized - - month_names = [ - "", - "ජනවාරි", - "පෙබරවාරි", - "මාර්තු", - "අප්‍රේල්", - "මැයි", - "ජූනි", - "ජූලි", - "අගෝස්තු", - "සැප්තැම්බර්", - "ඔක්තෝබර්", - "නොවැම්බර්", - "දෙසැම්බර්", - ] - - month_abbreviations = [ - "", - "ජන", - "පෙබ", - "මාර්", - "අප්‍රේ", - "මැයි", - "ජුනි", - "ජූලි", - "අගෝ", - "සැප්", - "ඔක්", - "නොවැ", - "දෙසැ", - ] - - day_names = [ - "", - "සදුදා", - "අඟහරැවදා", - "බදාදා", - "බ්‍රහස්‍පතින්‍දා", - "සිකුරාදා", - "සෙනසුරාදා", - "ඉරිදා", - ] - - day_abbreviations = [ - "", - "සදුද", - "බදා", - "බදා", - "සිකු", - "සෙන", - "අ", - "ඉරිදා", - ] - - -class UrduLocale(Locale): - names = ["ur", "ur-pk"] - - past = "پہلے {0}" - future = "میں {0}" - and_word = "اور" - - timeframes = { - "now": "ابھی", - "second": "ایک سیکنڈ", - "seconds": "{0} سیکنڈ", - "minute": "ایک منٹ", - "minutes": "{0} منٹ", - "hour": "ایک گھنٹے", - "hours": "{0} گھنٹے", - "day": "ایک دن", - "days": "{0} دن", - "week": "ایک ہفتے", - "weeks": "{0} ہفتے", - "month": "ایک مہینہ", - "months": "{0} ماہ", - "year": "ایک سال", - "years": "{0} سال", - } - - month_names = [ - "", - "جنوری", - "فروری", - "مارچ", - "اپریل", - "مئی", - "جون", - "جولائی", - "اگست", - "ستمبر", - "اکتوبر", - "نومبر", - "دسمبر", - ] - - month_abbreviations = [ - "", - "جنوری", - "فروری", - "مارچ", - "اپریل", - "مئی", - "جون", - "جولائی", - "اگست", - "ستمبر", - "اکتوبر", - "نومبر", - "دسمبر", - ] - - day_names = [ - "", - "سوموار", - "منگل", - "بدھ", - "جمعرات", - "جمعہ", - "ہفتہ", - "اتوار", - ] - - day_abbreviations = [ - "", - "سوموار", - "منگل", - "بدھ", - "جمعرات", - "جمعہ", - "ہفتہ", - "اتوار", - ] - - -class KazakhLocale(Locale): - names = ["kk", "kk-kz"] - - past = "{0} бұрын" - future = "{0} кейін" - timeframes = { - "now": "қазір", - "second": "бір секунд", - "seconds": "{0} секунд", - "minute": "бір минут", - "minutes": "{0} минут", - "hour": "бір сағат", - "hours": "{0} сағат", - "day": "бір күн", - "days": "{0} күн", - "week": "бір апта", - "weeks": "{0} апта", - "month": "бір ай", - "months": "{0} ай", - "year": "бір жыл", - "years": "{0} жыл", - } - - month_names = [ - "", - "Қаңтар", - "Ақпан", - "Наурыз", - "Сәуір", - "Мамыр", - "Маусым", - "Шілде", - "Тамыз", - "Қыркүйек", - "Қазан", - "Қараша", - "Желтоқсан", - ] - month_abbreviations = [ - "", - "Қан", - "Ақп", - "Нау", - "Сәу", - "Мам", - "Мау", - "Шіл", - "Там", - "Қыр", - "Қаз", - "Қар", - "Жел", - ] - - day_names = [ - "", - "Дүйсембі", - "Сейсенбі", - "Сәрсенбі", - "Бейсенбі", - "Жұма", - "Сенбі", - "Жексенбі", - ] - day_abbreviations = ["", "Дс", "Сс", "Ср", "Бс", "Жм", "Сб", "Жс"] - - -class AmharicLocale(Locale): - names = ["am", "am-et"] - - past = "{0} በፊት" - future = "{0} ውስጥ" - and_word = "እና" - - timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[Mapping[str, str], str]]] = { - "now": "አሁን", - "second": { - "past": "ከአንድ ሰከንድ", - "future": "በአንድ ሰከንድ", - }, - "seconds": { - "past": "ከ {0} ሰከንድ", - "future": "በ {0} ሰከንድ", - }, - "minute": { - "past": "ከአንድ ደቂቃ", - "future": "በአንድ ደቂቃ", - }, - "minutes": { - "past": "ከ {0} ደቂቃዎች", - "future": "በ {0} ደቂቃዎች", - }, - "hour": { - "past": "ከአንድ ሰዓት", - "future": "በአንድ ሰዓት", - }, - "hours": { - "past": "ከ {0} ሰዓታት", - "future": "በ {0} ሰከንድ", - }, - "day": { - "past": "ከአንድ ቀን", - "future": "በአንድ ቀን", - }, - "days": { - "past": "ከ {0} ቀናት", - "future": "በ {0} ቀናት", - }, - "week": { - "past": "ከአንድ ሳምንት", - "future": "በአንድ ሳምንት", - }, - "weeks": { - "past": "ከ {0} ሳምንታት", - "future": "በ {0} ሳምንታት", - }, - "month": { - "past": "ከአንድ ወር", - "future": "በአንድ ወር", - }, - "months": { - "past": "ከ {0} ወር", - "future": "በ {0} ወራት", - }, - "year": { - "past": "ከአንድ አመት", - "future": "በአንድ አመት", - }, - "years": { - "past": "ከ {0} ዓመታት", - "future": "በ {0} ዓመታት", - }, - } - # Amharic: the general format to describe timeframe is different from past and future, - # so we do not copy the original timeframes dictionary - timeframes_only_distance = { - "second": "አንድ ሰከንድ", - "seconds": "{0} ሰከንድ", - "minute": "አንድ ደቂቃ", - "minutes": "{0} ደቂቃዎች", - "hour": "አንድ ሰዓት", - "hours": "{0} ሰዓት", - "day": "አንድ ቀን", - "days": "{0} ቀናት", - "week": "አንድ ሳምንት", - "weeks": "{0} ሳምንት", - "month": "አንድ ወር", - "months": "{0} ወራት", - "year": "አንድ አመት", - "years": "{0} ዓመታት", - } - - month_names = [ - "", - "ጃንዩወሪ", - "ፌብሩወሪ", - "ማርች", - "ኤፕሪል", - "ሜይ", - "ጁን", - "ጁላይ", - "ኦገስት", - "ሴፕቴምበር", - "ኦክቶበር", - "ኖቬምበር", - "ዲሴምበር", - ] - - month_abbreviations = [ - "", - "ጃንዩ", - "ፌብሩ", - "ማርች", - "ኤፕሪ", - "ሜይ", - "ጁን", - "ጁላይ", - "ኦገስ", - "ሴፕቴ", - "ኦክቶ", - "ኖቬም", - "ዲሴም", - ] - - day_names = [ - "", - "ሰኞ", - "ማክሰኞ", - "ረቡዕ", - "ሐሙስ", - "ዓርብ", - "ቅዳሜ", - "እሑድ", - ] - day_abbreviations = ["", "እ", "ሰ", "ማ", "ረ", "ሐ", "ዓ", "ቅ"] - - def _ordinal_number(self, n: int) -> str: - return f"{n}ኛ" - - def _format_timeframe(self, timeframe: TimeFrameLiteral, delta: int) -> str: - """ - Amharic awares time frame format function, takes into account - the differences between general, past, and future forms (three different suffixes). - """ - abs_delta = abs(delta) - form = self.timeframes[timeframe] - - if isinstance(form, str): - return form.format(abs_delta) - - if delta > 0: - key = "future" - else: - key = "past" - form = form[key] - - return form.format(abs_delta) - - def describe( - self, - timeframe: TimeFrameLiteral, - delta: Union[float, int] = 1, # key is always future when only_distance=False - only_distance: bool = False, - ) -> str: - """Describes a delta within a timeframe in plain language. - - :param timeframe: a string representing a timeframe. - :param delta: a quantity representing a delta in a timeframe. - :param only_distance: return only distance eg: "11 seconds" without "in" or "ago" keywords - """ - - if not only_distance: - return super().describe(timeframe, delta, only_distance) - humanized = self.timeframes_only_distance[timeframe].format(trunc(abs(delta))) - - return humanized - - -class ArmenianLocale(Locale): - names = ["hy", "hy-am"] - past = "{0} առաջ" - future = "{0}ից" - and_word = "Եվ" # Yev - - timeframes = { - "now": "հիմա", - "second": "վայրկյան", - "seconds": "{0} վայրկյան", - "minute": "րոպե", - "minutes": "{0} րոպե", - "hour": "ժամ", - "hours": "{0} ժամ", - "day": "օր", - "days": "{0} օր", - "month": "ամիս", - "months": "{0} ամիս", - "year": "տարին", - "years": "{0} տարին", - "week": "շաբաթ", - "weeks": "{0} շաբաթ", - } - - meridians = { - "am": "Ամ", - "pm": "պ.մ.", - "AM": "Ամ", - "PM": "պ.մ.", - } - - month_names = [ - "", - "հունվար", - "փետրվար", - "մարտ", - "ապրիլ", - "մայիս", - "հունիս", - "հուլիս", - "օգոստոս", - "սեպտեմբեր", - "հոկտեմբեր", - "նոյեմբեր", - "դեկտեմբեր", - ] - - month_abbreviations = [ - "", - "հունվար", - "փետրվար", - "մարտ", - "ապրիլ", - "մայիս", - "հունիս", - "հուլիս", - "օգոստոս", - "սեպտեմբեր", - "հոկտեմբեր", - "նոյեմբեր", - "դեկտեմբեր", - ] - - day_names = [ - "", - "երկուշաբթի", - "երեքշաբթի", - "չորեքշաբթի", - "հինգշաբթի", - "ուրբաթ", - "շաբաթ", - "կիրակի", - ] - - day_abbreviations = [ - "", - "երկ.", - "երեք.", - "չորեք.", - "հինգ.", - "ուրբ.", - "շաբ.", - "կիր.", - ] - - -class UzbekLocale(Locale): - names = ["uz", "uz-uz"] - past = "{0}dan avval" - future = "{0}dan keyin" - timeframes = { - "now": "hozir", - "second": "bir soniya", - "seconds": "{0} soniya", - "minute": "bir daqiqa", - "minutes": "{0} daqiqa", - "hour": "bir soat", - "hours": "{0} soat", - "day": "bir kun", - "days": "{0} kun", - "week": "bir hafta", - "weeks": "{0} hafta", - "month": "bir oy", - "months": "{0} oy", - "year": "bir yil", - "years": "{0} yil", - } - - month_names = [ - "", - "Yanvar", - "Fevral", - "Mart", - "Aprel", - "May", - "Iyun", - "Iyul", - "Avgust", - "Sentyabr", - "Oktyabr", - "Noyabr", - "Dekabr", - ] - - month_abbreviations = [ - "", - "Yan", - "Fev", - "Mar", - "Apr", - "May", - "Iyn", - "Iyl", - "Avg", - "Sen", - "Okt", - "Noy", - "Dek", - ] - - day_names = [ - "", - "Dushanba", - "Seshanba", - "Chorshanba", - "Payshanba", - "Juma", - "Shanba", - "Yakshanba", - ] - - day_abbreviations = ["", "Dush", "Sesh", "Chor", "Pay", "Jum", "Shan", "Yak"] diff --git a/.venv/Lib/site-packages/arrow/parser.py b/.venv/Lib/site-packages/arrow/parser.py deleted file mode 100644 index e95d78b..0000000 --- a/.venv/Lib/site-packages/arrow/parser.py +++ /dev/null @@ -1,779 +0,0 @@ -"""Provides the :class:`Arrow ` class, a better way to parse datetime strings.""" - -import re -import sys -from datetime import datetime, timedelta -from datetime import tzinfo as dt_tzinfo -from functools import lru_cache -from typing import ( - Any, - ClassVar, - Dict, - Iterable, - List, - Match, - Optional, - Pattern, - SupportsFloat, - SupportsInt, - Tuple, - Union, - cast, - overload, -) - -from dateutil import tz - -from arrow import locales -from arrow.constants import DEFAULT_LOCALE -from arrow.util import next_weekday, normalize_timestamp - -if sys.version_info < (3, 8): # pragma: no cover - from typing_extensions import Literal, TypedDict -else: - from typing import Literal, TypedDict # pragma: no cover - - -class ParserError(ValueError): - pass - - -# Allows for ParserErrors to be propagated from _build_datetime() -# when day_of_year errors occur. -# Before this, the ParserErrors were caught by the try/except in -# _parse_multiformat() and the appropriate error message was not -# transmitted to the user. -class ParserMatchError(ParserError): - pass - - -_WEEKDATE_ELEMENT = Union[str, bytes, SupportsInt, bytearray] - -_FORMAT_TYPE = Literal[ - "YYYY", - "YY", - "MM", - "M", - "DDDD", - "DDD", - "DD", - "D", - "HH", - "H", - "hh", - "h", - "mm", - "m", - "ss", - "s", - "X", - "x", - "ZZZ", - "ZZ", - "Z", - "S", - "W", - "MMMM", - "MMM", - "Do", - "dddd", - "ddd", - "d", - "a", - "A", -] - - -class _Parts(TypedDict, total=False): - year: int - month: int - day_of_year: int - day: int - hour: int - minute: int - second: int - microsecond: int - timestamp: float - expanded_timestamp: int - tzinfo: dt_tzinfo - am_pm: Literal["am", "pm"] - day_of_week: int - weekdate: Tuple[_WEEKDATE_ELEMENT, _WEEKDATE_ELEMENT, Optional[_WEEKDATE_ELEMENT]] - - -class DateTimeParser: - _FORMAT_RE: ClassVar[Pattern[str]] = re.compile( - r"(YYY?Y?|MM?M?M?|Do|DD?D?D?|d?d?d?d|HH?|hh?|mm?|ss?|S+|ZZ?Z?|a|A|x|X|W)" - ) - _ESCAPE_RE: ClassVar[Pattern[str]] = re.compile(r"\[[^\[\]]*\]") - - _ONE_OR_TWO_DIGIT_RE: ClassVar[Pattern[str]] = re.compile(r"\d{1,2}") - _ONE_OR_TWO_OR_THREE_DIGIT_RE: ClassVar[Pattern[str]] = re.compile(r"\d{1,3}") - _ONE_OR_MORE_DIGIT_RE: ClassVar[Pattern[str]] = re.compile(r"\d+") - _TWO_DIGIT_RE: ClassVar[Pattern[str]] = re.compile(r"\d{2}") - _THREE_DIGIT_RE: ClassVar[Pattern[str]] = re.compile(r"\d{3}") - _FOUR_DIGIT_RE: ClassVar[Pattern[str]] = re.compile(r"\d{4}") - _TZ_Z_RE: ClassVar[Pattern[str]] = re.compile(r"([\+\-])(\d{2})(?:(\d{2}))?|Z") - _TZ_ZZ_RE: ClassVar[Pattern[str]] = re.compile(r"([\+\-])(\d{2})(?:\:(\d{2}))?|Z") - _TZ_NAME_RE: ClassVar[Pattern[str]] = re.compile(r"\w[\w+\-/]+") - # NOTE: timestamps cannot be parsed from natural language strings (by removing the ^...$) because it will - # break cases like "15 Jul 2000" and a format list (see issue #447) - _TIMESTAMP_RE: ClassVar[Pattern[str]] = re.compile(r"^\-?\d+\.?\d+$") - _TIMESTAMP_EXPANDED_RE: ClassVar[Pattern[str]] = re.compile(r"^\-?\d+$") - _TIME_RE: ClassVar[Pattern[str]] = re.compile( - r"^(\d{2})(?:\:?(\d{2}))?(?:\:?(\d{2}))?(?:([\.\,])(\d+))?$" - ) - _WEEK_DATE_RE: ClassVar[Pattern[str]] = re.compile( - r"(?P\d{4})[\-]?W(?P\d{2})[\-]?(?P\d)?" - ) - - _BASE_INPUT_RE_MAP: ClassVar[Dict[_FORMAT_TYPE, Pattern[str]]] = { - "YYYY": _FOUR_DIGIT_RE, - "YY": _TWO_DIGIT_RE, - "MM": _TWO_DIGIT_RE, - "M": _ONE_OR_TWO_DIGIT_RE, - "DDDD": _THREE_DIGIT_RE, - "DDD": _ONE_OR_TWO_OR_THREE_DIGIT_RE, - "DD": _TWO_DIGIT_RE, - "D": _ONE_OR_TWO_DIGIT_RE, - "HH": _TWO_DIGIT_RE, - "H": _ONE_OR_TWO_DIGIT_RE, - "hh": _TWO_DIGIT_RE, - "h": _ONE_OR_TWO_DIGIT_RE, - "mm": _TWO_DIGIT_RE, - "m": _ONE_OR_TWO_DIGIT_RE, - "ss": _TWO_DIGIT_RE, - "s": _ONE_OR_TWO_DIGIT_RE, - "X": _TIMESTAMP_RE, - "x": _TIMESTAMP_EXPANDED_RE, - "ZZZ": _TZ_NAME_RE, - "ZZ": _TZ_ZZ_RE, - "Z": _TZ_Z_RE, - "S": _ONE_OR_MORE_DIGIT_RE, - "W": _WEEK_DATE_RE, - } - - SEPARATORS: ClassVar[List[str]] = ["-", "/", "."] - - locale: locales.Locale - _input_re_map: Dict[_FORMAT_TYPE, Pattern[str]] - - def __init__(self, locale: str = DEFAULT_LOCALE, cache_size: int = 0) -> None: - - self.locale = locales.get_locale(locale) - self._input_re_map = self._BASE_INPUT_RE_MAP.copy() - self._input_re_map.update( - { - "MMMM": self._generate_choice_re( - self.locale.month_names[1:], re.IGNORECASE - ), - "MMM": self._generate_choice_re( - self.locale.month_abbreviations[1:], re.IGNORECASE - ), - "Do": re.compile(self.locale.ordinal_day_re), - "dddd": self._generate_choice_re( - self.locale.day_names[1:], re.IGNORECASE - ), - "ddd": self._generate_choice_re( - self.locale.day_abbreviations[1:], re.IGNORECASE - ), - "d": re.compile(r"[1-7]"), - "a": self._generate_choice_re( - (self.locale.meridians["am"], self.locale.meridians["pm"]) - ), - # note: 'A' token accepts both 'am/pm' and 'AM/PM' formats to - # ensure backwards compatibility of this token - "A": self._generate_choice_re(self.locale.meridians.values()), - } - ) - if cache_size > 0: - self._generate_pattern_re = lru_cache(maxsize=cache_size)( # type: ignore - self._generate_pattern_re - ) - - # TODO: since we support more than ISO 8601, we should rename this function - # IDEA: break into multiple functions - def parse_iso( - self, datetime_string: str, normalize_whitespace: bool = False - ) -> datetime: - - if normalize_whitespace: - datetime_string = re.sub(r"\s+", " ", datetime_string.strip()) - - has_space_divider = " " in datetime_string - has_t_divider = "T" in datetime_string - - num_spaces = datetime_string.count(" ") - if has_space_divider and num_spaces != 1 or has_t_divider and num_spaces > 0: - raise ParserError( - f"Expected an ISO 8601-like string, but was given {datetime_string!r}. " - "Try passing in a format string to resolve this." - ) - - has_time = has_space_divider or has_t_divider - has_tz = False - - # date formats (ISO 8601 and others) to test against - # NOTE: YYYYMM is omitted to avoid confusion with YYMMDD (no longer part of ISO 8601, but is still often used) - formats = [ - "YYYY-MM-DD", - "YYYY-M-DD", - "YYYY-M-D", - "YYYY/MM/DD", - "YYYY/M/DD", - "YYYY/M/D", - "YYYY.MM.DD", - "YYYY.M.DD", - "YYYY.M.D", - "YYYYMMDD", - "YYYY-DDDD", - "YYYYDDDD", - "YYYY-MM", - "YYYY/MM", - "YYYY.MM", - "YYYY", - "W", - ] - - if has_time: - - if has_space_divider: - date_string, time_string = datetime_string.split(" ", 1) - else: - date_string, time_string = datetime_string.split("T", 1) - - time_parts = re.split(r"[\+\-Z]", time_string, 1, re.IGNORECASE) - - time_components: Optional[Match[str]] = self._TIME_RE.match(time_parts[0]) - - if time_components is None: - raise ParserError( - "Invalid time component provided. " - "Please specify a format or provide a valid time component in the basic or extended ISO 8601 time format." - ) - - ( - hours, - minutes, - seconds, - subseconds_sep, - subseconds, - ) = time_components.groups() - - has_tz = len(time_parts) == 2 - has_minutes = minutes is not None - has_seconds = seconds is not None - has_subseconds = subseconds is not None - - is_basic_time_format = ":" not in time_parts[0] - tz_format = "Z" - - # use 'ZZ' token instead since tz offset is present in non-basic format - if has_tz and ":" in time_parts[1]: - tz_format = "ZZ" - - time_sep = "" if is_basic_time_format else ":" - - if has_subseconds: - time_string = "HH{time_sep}mm{time_sep}ss{subseconds_sep}S".format( - time_sep=time_sep, subseconds_sep=subseconds_sep - ) - elif has_seconds: - time_string = "HH{time_sep}mm{time_sep}ss".format(time_sep=time_sep) - elif has_minutes: - time_string = f"HH{time_sep}mm" - else: - time_string = "HH" - - if has_space_divider: - formats = [f"{f} {time_string}" for f in formats] - else: - formats = [f"{f}T{time_string}" for f in formats] - - if has_time and has_tz: - # Add "Z" or "ZZ" to the format strings to indicate to - # _parse_token() that a timezone needs to be parsed - formats = [f"{f}{tz_format}" for f in formats] - - return self._parse_multiformat(datetime_string, formats) - - def parse( - self, - datetime_string: str, - fmt: Union[List[str], str], - normalize_whitespace: bool = False, - ) -> datetime: - - if normalize_whitespace: - datetime_string = re.sub(r"\s+", " ", datetime_string) - - if isinstance(fmt, list): - return self._parse_multiformat(datetime_string, fmt) - - try: - fmt_tokens: List[_FORMAT_TYPE] - fmt_pattern_re: Pattern[str] - fmt_tokens, fmt_pattern_re = self._generate_pattern_re(fmt) - except re.error as e: - raise ParserMatchError( - f"Failed to generate regular expression pattern: {e}." - ) - - match = fmt_pattern_re.search(datetime_string) - - if match is None: - raise ParserMatchError( - f"Failed to match {fmt!r} when parsing {datetime_string!r}." - ) - - parts: _Parts = {} - for token in fmt_tokens: - value: Union[Tuple[str, str, str], str] - if token == "Do": - value = match.group("value") - elif token == "W": - value = (match.group("year"), match.group("week"), match.group("day")) - else: - value = match.group(token) - - if value is None: - raise ParserMatchError( - f"Unable to find a match group for the specified token {token!r}." - ) - - self._parse_token(token, value, parts) # type: ignore - - return self._build_datetime(parts) - - def _generate_pattern_re(self, fmt: str) -> Tuple[List[_FORMAT_TYPE], Pattern[str]]: - - # fmt is a string of tokens like 'YYYY-MM-DD' - # we construct a new string by replacing each - # token by its pattern: - # 'YYYY-MM-DD' -> '(?P\d{4})-(?P\d{2})-(?P
    \d{2})' - tokens: List[_FORMAT_TYPE] = [] - offset = 0 - - # Escape all special RegEx chars - escaped_fmt = re.escape(fmt) - - # Extract the bracketed expressions to be reinserted later. - escaped_fmt = re.sub(self._ESCAPE_RE, "#", escaped_fmt) - - # Any number of S is the same as one. - # TODO: allow users to specify the number of digits to parse - escaped_fmt = re.sub(r"S+", "S", escaped_fmt) - - escaped_data = re.findall(self._ESCAPE_RE, fmt) - - fmt_pattern = escaped_fmt - - for m in self._FORMAT_RE.finditer(escaped_fmt): - token: _FORMAT_TYPE = cast(_FORMAT_TYPE, m.group(0)) - try: - input_re = self._input_re_map[token] - except KeyError: - raise ParserError(f"Unrecognized token {token!r}.") - input_pattern = f"(?P<{token}>{input_re.pattern})" - tokens.append(token) - # a pattern doesn't have the same length as the token - # it replaces! We keep the difference in the offset variable. - # This works because the string is scanned left-to-right and matches - # are returned in the order found by finditer. - fmt_pattern = ( - fmt_pattern[: m.start() + offset] - + input_pattern - + fmt_pattern[m.end() + offset :] - ) - offset += len(input_pattern) - (m.end() - m.start()) - - final_fmt_pattern = "" - split_fmt = fmt_pattern.split(r"\#") - - # Due to the way Python splits, 'split_fmt' will always be longer - for i in range(len(split_fmt)): - final_fmt_pattern += split_fmt[i] - if i < len(escaped_data): - final_fmt_pattern += escaped_data[i][1:-1] - - # Wrap final_fmt_pattern in a custom word boundary to strictly - # match the formatting pattern and filter out date and time formats - # that include junk such as: blah1998-09-12 blah, blah 1998-09-12blah, - # blah1998-09-12blah. The custom word boundary matches every character - # that is not a whitespace character to allow for searching for a date - # and time string in a natural language sentence. Therefore, searching - # for a string of the form YYYY-MM-DD in "blah 1998-09-12 blah" will - # work properly. - # Certain punctuation before or after the target pattern such as - # "1998-09-12," is permitted. For the full list of valid punctuation, - # see the documentation. - - starting_word_boundary = ( - r"(?\s])" # This is the list of punctuation that is ok before the - # pattern (i.e. "It can't not be these characters before the pattern") - r"(\b|^)" - # The \b is to block cases like 1201912 but allow 201912 for pattern YYYYMM. The ^ was necessary to allow a - # negative number through i.e. before epoch numbers - ) - ending_word_boundary = ( - r"(?=[\,\.\;\:\?\!\"\'\`\[\]\{\}\(\)\<\>]?" # Positive lookahead stating that these punctuation marks - # can appear after the pattern at most 1 time - r"(?!\S))" # Don't allow any non-whitespace character after the punctuation - ) - bounded_fmt_pattern = r"{}{}{}".format( - starting_word_boundary, final_fmt_pattern, ending_word_boundary - ) - - return tokens, re.compile(bounded_fmt_pattern, flags=re.IGNORECASE) - - @overload - def _parse_token( - self, - token: Literal[ - "YYYY", - "YY", - "MM", - "M", - "DDDD", - "DDD", - "DD", - "D", - "Do", - "HH", - "hh", - "h", - "H", - "mm", - "m", - "ss", - "s", - "x", - ], - value: Union[str, bytes, SupportsInt, bytearray], - parts: _Parts, - ) -> None: - ... # pragma: no cover - - @overload - def _parse_token( - self, - token: Literal["X"], - value: Union[str, bytes, SupportsFloat, bytearray], - parts: _Parts, - ) -> None: - ... # pragma: no cover - - @overload - def _parse_token( - self, - token: Literal["MMMM", "MMM", "dddd", "ddd", "S"], - value: Union[str, bytes, bytearray], - parts: _Parts, - ) -> None: - ... # pragma: no cover - - @overload - def _parse_token( - self, - token: Literal["a", "A", "ZZZ", "ZZ", "Z"], - value: Union[str, bytes], - parts: _Parts, - ) -> None: - ... # pragma: no cover - - @overload - def _parse_token( - self, - token: Literal["W"], - value: Tuple[_WEEKDATE_ELEMENT, _WEEKDATE_ELEMENT, Optional[_WEEKDATE_ELEMENT]], - parts: _Parts, - ) -> None: - ... # pragma: no cover - - def _parse_token( - self, - token: Any, - value: Any, - parts: _Parts, - ) -> None: - - if token == "YYYY": - parts["year"] = int(value) - - elif token == "YY": - value = int(value) - parts["year"] = 1900 + value if value > 68 else 2000 + value - - elif token in ["MMMM", "MMM"]: - # FIXME: month_number() is nullable - parts["month"] = self.locale.month_number(value.lower()) # type: ignore - - elif token in ["MM", "M"]: - parts["month"] = int(value) - - elif token in ["DDDD", "DDD"]: - parts["day_of_year"] = int(value) - - elif token in ["DD", "D"]: - parts["day"] = int(value) - - elif token == "Do": - parts["day"] = int(value) - - elif token == "dddd": - # locale day names are 1-indexed - day_of_week = [x.lower() for x in self.locale.day_names].index( - value.lower() - ) - parts["day_of_week"] = day_of_week - 1 - - elif token == "ddd": - # locale day abbreviations are 1-indexed - day_of_week = [x.lower() for x in self.locale.day_abbreviations].index( - value.lower() - ) - parts["day_of_week"] = day_of_week - 1 - - elif token.upper() in ["HH", "H"]: - parts["hour"] = int(value) - - elif token in ["mm", "m"]: - parts["minute"] = int(value) - - elif token in ["ss", "s"]: - parts["second"] = int(value) - - elif token == "S": - # We have the *most significant* digits of an arbitrary-precision integer. - # We want the six most significant digits as an integer, rounded. - # IDEA: add nanosecond support somehow? Need datetime support for it first. - value = value.ljust(7, "0") - - # floating-point (IEEE-754) defaults to half-to-even rounding - seventh_digit = int(value[6]) - if seventh_digit == 5: - rounding = int(value[5]) % 2 - elif seventh_digit > 5: - rounding = 1 - else: - rounding = 0 - - parts["microsecond"] = int(value[:6]) + rounding - - elif token == "X": - parts["timestamp"] = float(value) - - elif token == "x": - parts["expanded_timestamp"] = int(value) - - elif token in ["ZZZ", "ZZ", "Z"]: - parts["tzinfo"] = TzinfoParser.parse(value) - - elif token in ["a", "A"]: - if value in (self.locale.meridians["am"], self.locale.meridians["AM"]): - parts["am_pm"] = "am" - if "hour" in parts and not 0 <= parts["hour"] <= 12: - raise ParserMatchError( - f"Hour token value must be between 0 and 12 inclusive for token {token!r}." - ) - elif value in (self.locale.meridians["pm"], self.locale.meridians["PM"]): - parts["am_pm"] = "pm" - elif token == "W": - parts["weekdate"] = value - - @staticmethod - def _build_datetime(parts: _Parts) -> datetime: - weekdate = parts.get("weekdate") - - if weekdate is not None: - - year, week = int(weekdate[0]), int(weekdate[1]) - - if weekdate[2] is not None: - _day = int(weekdate[2]) - else: - # day not given, default to 1 - _day = 1 - - date_string = f"{year}-{week}-{_day}" - - # tokens for ISO 8601 weekdates - dt = datetime.strptime(date_string, "%G-%V-%u") - - parts["year"] = dt.year - parts["month"] = dt.month - parts["day"] = dt.day - - timestamp = parts.get("timestamp") - - if timestamp is not None: - return datetime.fromtimestamp(timestamp, tz=tz.tzutc()) - - expanded_timestamp = parts.get("expanded_timestamp") - - if expanded_timestamp is not None: - return datetime.fromtimestamp( - normalize_timestamp(expanded_timestamp), - tz=tz.tzutc(), - ) - - day_of_year = parts.get("day_of_year") - - if day_of_year is not None: - _year = parts.get("year") - month = parts.get("month") - if _year is None: - raise ParserError( - "Year component is required with the DDD and DDDD tokens." - ) - - if month is not None: - raise ParserError( - "Month component is not allowed with the DDD and DDDD tokens." - ) - - date_string = f"{_year}-{day_of_year}" - try: - dt = datetime.strptime(date_string, "%Y-%j") - except ValueError: - raise ParserError( - f"The provided day of year {day_of_year!r} is invalid." - ) - - parts["year"] = dt.year - parts["month"] = dt.month - parts["day"] = dt.day - - day_of_week: Optional[int] = parts.get("day_of_week") - day = parts.get("day") - - # If day is passed, ignore day of week - if day_of_week is not None and day is None: - year = parts.get("year", 1970) - month = parts.get("month", 1) - day = 1 - - # dddd => first day of week after epoch - # dddd YYYY => first day of week in specified year - # dddd MM YYYY => first day of week in specified year and month - # dddd MM => first day after epoch in specified month - next_weekday_dt = next_weekday(datetime(year, month, day), day_of_week) - parts["year"] = next_weekday_dt.year - parts["month"] = next_weekday_dt.month - parts["day"] = next_weekday_dt.day - - am_pm = parts.get("am_pm") - hour = parts.get("hour", 0) - - if am_pm == "pm" and hour < 12: - hour += 12 - elif am_pm == "am" and hour == 12: - hour = 0 - - # Support for midnight at the end of day - if hour == 24: - if parts.get("minute", 0) != 0: - raise ParserError("Midnight at the end of day must not contain minutes") - if parts.get("second", 0) != 0: - raise ParserError("Midnight at the end of day must not contain seconds") - if parts.get("microsecond", 0) != 0: - raise ParserError( - "Midnight at the end of day must not contain microseconds" - ) - hour = 0 - day_increment = 1 - else: - day_increment = 0 - - # account for rounding up to 1000000 - microsecond = parts.get("microsecond", 0) - if microsecond == 1000000: - microsecond = 0 - second_increment = 1 - else: - second_increment = 0 - - increment = timedelta(days=day_increment, seconds=second_increment) - - return ( - datetime( - year=parts.get("year", 1), - month=parts.get("month", 1), - day=parts.get("day", 1), - hour=hour, - minute=parts.get("minute", 0), - second=parts.get("second", 0), - microsecond=microsecond, - tzinfo=parts.get("tzinfo"), - ) - + increment - ) - - def _parse_multiformat(self, string: str, formats: Iterable[str]) -> datetime: - - _datetime: Optional[datetime] = None - - for fmt in formats: - try: - _datetime = self.parse(string, fmt) - break - except ParserMatchError: - pass - - if _datetime is None: - supported_formats = ", ".join(formats) - raise ParserError( - f"Could not match input {string!r} to any of the following formats: {supported_formats}." - ) - - return _datetime - - # generates a capture group of choices separated by an OR operator - @staticmethod - def _generate_choice_re( - choices: Iterable[str], flags: Union[int, re.RegexFlag] = 0 - ) -> Pattern[str]: - return re.compile(r"({})".format("|".join(choices)), flags=flags) - - -class TzinfoParser: - _TZINFO_RE: ClassVar[Pattern[str]] = re.compile( - r"^([\+\-])?(\d{2})(?:\:?(\d{2}))?$" - ) - - @classmethod - def parse(cls, tzinfo_string: str) -> dt_tzinfo: - - tzinfo: Optional[dt_tzinfo] = None - - if tzinfo_string == "local": - tzinfo = tz.tzlocal() - - elif tzinfo_string in ["utc", "UTC", "Z"]: - tzinfo = tz.tzutc() - - else: - - iso_match = cls._TZINFO_RE.match(tzinfo_string) - - if iso_match: - sign: Optional[str] - hours: str - minutes: Union[str, int, None] - sign, hours, minutes = iso_match.groups() - seconds = int(hours) * 3600 + int(minutes or 0) * 60 - - if sign == "-": - seconds *= -1 - - tzinfo = tz.tzoffset(None, seconds) - - else: - tzinfo = tz.gettz(tzinfo_string) - - if tzinfo is None: - raise ParserError(f"Could not parse timezone expression {tzinfo_string!r}.") - - return tzinfo diff --git a/.venv/Lib/site-packages/arrow/py.typed b/.venv/Lib/site-packages/arrow/py.typed deleted file mode 100644 index e69de29..0000000 diff --git a/.venv/Lib/site-packages/arrow/util.py b/.venv/Lib/site-packages/arrow/util.py deleted file mode 100644 index f3eaa21..0000000 --- a/.venv/Lib/site-packages/arrow/util.py +++ /dev/null @@ -1,117 +0,0 @@ -"""Helpful functions used internally within arrow.""" - -import datetime -from typing import Any, Optional, cast - -from dateutil.rrule import WEEKLY, rrule - -from arrow.constants import ( - MAX_ORDINAL, - MAX_TIMESTAMP, - MAX_TIMESTAMP_MS, - MAX_TIMESTAMP_US, - MIN_ORDINAL, -) - - -def next_weekday( - start_date: Optional[datetime.date], weekday: int -) -> datetime.datetime: - """Get next weekday from the specified start date. - - :param start_date: Datetime object representing the start date. - :param weekday: Next weekday to obtain. Can be a value between 0 (Monday) and 6 (Sunday). - :return: Datetime object corresponding to the next weekday after start_date. - - Usage:: - - # Get first Monday after epoch - >>> next_weekday(datetime(1970, 1, 1), 0) - 1970-01-05 00:00:00 - - # Get first Thursday after epoch - >>> next_weekday(datetime(1970, 1, 1), 3) - 1970-01-01 00:00:00 - - # Get first Sunday after epoch - >>> next_weekday(datetime(1970, 1, 1), 6) - 1970-01-04 00:00:00 - """ - if weekday < 0 or weekday > 6: - raise ValueError("Weekday must be between 0 (Monday) and 6 (Sunday).") - return cast( - datetime.datetime, - rrule(freq=WEEKLY, dtstart=start_date, byweekday=weekday, count=1)[0], - ) - - -def is_timestamp(value: Any) -> bool: - """Check if value is a valid timestamp.""" - if isinstance(value, bool): - return False - if not isinstance(value, (int, float, str)): - return False - try: - float(value) - return True - except ValueError: - return False - - -def validate_ordinal(value: Any) -> None: - """Raise an exception if value is an invalid Gregorian ordinal. - - :param value: the input to be checked - - """ - if isinstance(value, bool) or not isinstance(value, int): - raise TypeError(f"Ordinal must be an integer (got type {type(value)}).") - if not (MIN_ORDINAL <= value <= MAX_ORDINAL): - raise ValueError(f"Ordinal {value} is out of range.") - - -def normalize_timestamp(timestamp: float) -> float: - """Normalize millisecond and microsecond timestamps into normal timestamps.""" - if timestamp > MAX_TIMESTAMP: - if timestamp < MAX_TIMESTAMP_MS: - timestamp /= 1000 - elif timestamp < MAX_TIMESTAMP_US: - timestamp /= 1_000_000 - else: - raise ValueError(f"The specified timestamp {timestamp!r} is too large.") - return timestamp - - -# Credit to https://stackoverflow.com/a/1700069 -def iso_to_gregorian(iso_year: int, iso_week: int, iso_day: int) -> datetime.date: - """Converts an ISO week date into a datetime object. - - :param iso_year: the year - :param iso_week: the week number, each year has either 52 or 53 weeks - :param iso_day: the day numbered 1 through 7, beginning with Monday - - """ - - if not 1 <= iso_week <= 53: - raise ValueError("ISO Calendar week value must be between 1-53.") - - if not 1 <= iso_day <= 7: - raise ValueError("ISO Calendar day value must be between 1-7") - - # The first week of the year always contains 4 Jan. - fourth_jan = datetime.date(iso_year, 1, 4) - delta = datetime.timedelta(fourth_jan.isoweekday() - 1) - year_start = fourth_jan - delta - gregorian = year_start + datetime.timedelta(days=iso_day - 1, weeks=iso_week - 1) - - return gregorian - - -def validate_bounds(bounds: str) -> None: - if bounds != "()" and bounds != "(]" and bounds != "[)" and bounds != "[]": - raise ValueError( - "Invalid bounds. Please select between '()', '(]', '[)', or '[]'." - ) - - -__all__ = ["next_weekday", "is_timestamp", "validate_ordinal", "iso_to_gregorian"] diff --git a/.venv/Lib/site-packages/async_timeout-4.0.2.dist-info/INSTALLER b/.venv/Lib/site-packages/async_timeout-4.0.2.dist-info/INSTALLER deleted file mode 100644 index a1b589e..0000000 --- a/.venv/Lib/site-packages/async_timeout-4.0.2.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/.venv/Lib/site-packages/async_timeout-4.0.2.dist-info/LICENSE b/.venv/Lib/site-packages/async_timeout-4.0.2.dist-info/LICENSE deleted file mode 100644 index 033c86b..0000000 --- a/.venv/Lib/site-packages/async_timeout-4.0.2.dist-info/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2016-2020 aio-libs collaboration. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/.venv/Lib/site-packages/async_timeout-4.0.2.dist-info/METADATA b/.venv/Lib/site-packages/async_timeout-4.0.2.dist-info/METADATA deleted file mode 100644 index e68d234..0000000 --- a/.venv/Lib/site-packages/async_timeout-4.0.2.dist-info/METADATA +++ /dev/null @@ -1,133 +0,0 @@ -Metadata-Version: 2.1 -Name: async-timeout -Version: 4.0.2 -Summary: Timeout context manager for asyncio programs -Home-page: https://github.com/aio-libs/async-timeout -Author: Andrew Svetlov -Author-email: andrew.svetlov@gmail.com -License: Apache 2 -Project-URL: Chat: Gitter, https://gitter.im/aio-libs/Lobby -Project-URL: CI: GitHub Actions, https://github.com/aio-libs/async-timeout/actions -Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/async-timeout -Project-URL: GitHub: issues, https://github.com/aio-libs/async-timeout/issues -Project-URL: GitHub: repo, https://github.com/aio-libs/async-timeout -Platform: UNKNOWN -Classifier: Development Status :: 5 - Production/Stable -Classifier: Topic :: Software Development :: Libraries -Classifier: Framework :: AsyncIO -Classifier: Intended Audience :: Developers -Classifier: License :: OSI Approved :: Apache Software License -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3 :: Only -Classifier: Programming Language :: Python :: 3.6 -Classifier: Programming Language :: Python :: 3.7 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Requires-Python: >=3.6 -Description-Content-Type: text/x-rst -License-File: LICENSE -Requires-Dist: typing-extensions (>=3.6.5) ; python_version < "3.8" - -async-timeout -============= -.. image:: https://travis-ci.com/aio-libs/async-timeout.svg?branch=master - :target: https://travis-ci.com/aio-libs/async-timeout -.. image:: https://codecov.io/gh/aio-libs/async-timeout/branch/master/graph/badge.svg - :target: https://codecov.io/gh/aio-libs/async-timeout -.. image:: https://img.shields.io/pypi/v/async-timeout.svg - :target: https://pypi.python.org/pypi/async-timeout -.. image:: https://badges.gitter.im/Join%20Chat.svg - :target: https://gitter.im/aio-libs/Lobby - :alt: Chat on Gitter - -asyncio-compatible timeout context manager. - - -Usage example -------------- - - -The context manager is useful in cases when you want to apply timeout -logic around block of code or in cases when ``asyncio.wait_for()`` is -not suitable. Also it's much faster than ``asyncio.wait_for()`` -because ``timeout`` doesn't create a new task. - -The ``timeout(delay, *, loop=None)`` call returns a context manager -that cancels a block on *timeout* expiring:: - - async with timeout(1.5): - await inner() - -1. If ``inner()`` is executed faster than in ``1.5`` seconds nothing - happens. -2. Otherwise ``inner()`` is cancelled internally by sending - ``asyncio.CancelledError`` into but ``asyncio.TimeoutError`` is - raised outside of context manager scope. - -*timeout* parameter could be ``None`` for skipping timeout functionality. - - -Alternatively, ``timeout_at(when)`` can be used for scheduling -at the absolute time:: - - loop = asyncio.get_event_loop() - now = loop.time() - - async with timeout_at(now + 1.5): - await inner() - - -Please note: it is not POSIX time but a time with -undefined starting base, e.g. the time of the system power on. - - -Context manager has ``.expired`` property for check if timeout happens -exactly in context manager:: - - async with timeout(1.5) as cm: - await inner() - print(cm.expired) - -The property is ``True`` if ``inner()`` execution is cancelled by -timeout context manager. - -If ``inner()`` call explicitly raises ``TimeoutError`` ``cm.expired`` -is ``False``. - -The scheduled deadline time is available as ``.deadline`` property:: - - async with timeout(1.5) as cm: - cm.deadline - -Not finished yet timeout can be rescheduled by ``shift_by()`` -or ``shift_to()`` methods:: - - async with timeout(1.5) as cm: - cm.shift(1) # add another second on waiting - cm.update(loop.time() + 5) # reschedule to now+5 seconds - -Rescheduling is forbidden if the timeout is expired or after exit from ``async with`` -code block. - - -Installation ------------- - -:: - - $ pip install async-timeout - -The library is Python 3 only! - - - -Authors and License -------------------- - -The module is written by Andrew Svetlov. - -It's *Apache 2* licensed and freely available. - - diff --git a/.venv/Lib/site-packages/async_timeout-4.0.2.dist-info/RECORD b/.venv/Lib/site-packages/async_timeout-4.0.2.dist-info/RECORD deleted file mode 100644 index 60e4fb8..0000000 --- a/.venv/Lib/site-packages/async_timeout-4.0.2.dist-info/RECORD +++ /dev/null @@ -1,10 +0,0 @@ -async_timeout-4.0.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -async_timeout-4.0.2.dist-info/LICENSE,sha256=4Y17uPUT4sRrtYXJS1hb0wcg3TzLId2weG9y0WZY-Sw,568 -async_timeout-4.0.2.dist-info/METADATA,sha256=2pfMxxBst5vQ7SfMy5TDaDU0cRgCSQa7wcD5eI-Ew-8,4193 -async_timeout-4.0.2.dist-info/RECORD,, -async_timeout-4.0.2.dist-info/WHEEL,sha256=ewwEueio1C2XeHTvT17n8dZUJgOvyCWCt0WVNLClP9o,92 -async_timeout-4.0.2.dist-info/top_level.txt,sha256=9oM4e7Twq8iD_7_Q3Mz0E6GPIB6vJvRFo-UBwUQtBDU,14 -async_timeout-4.0.2.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 -async_timeout/__init__.py,sha256=N-JUI_VExhHnO0emkF_-h08dl4HBgOje16N4Ci-W-go,7487 -async_timeout/__pycache__/__init__.cpython-38.pyc,, -async_timeout/py.typed,sha256=tyozzRT1fziXETDxokmuyt6jhOmtjUbnVNJdZcG7ik0,12 diff --git a/.venv/Lib/site-packages/async_timeout-4.0.2.dist-info/WHEEL b/.venv/Lib/site-packages/async_timeout-4.0.2.dist-info/WHEEL deleted file mode 100644 index 5bad85f..0000000 --- a/.venv/Lib/site-packages/async_timeout-4.0.2.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: bdist_wheel (0.37.0) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/.venv/Lib/site-packages/async_timeout-4.0.2.dist-info/top_level.txt b/.venv/Lib/site-packages/async_timeout-4.0.2.dist-info/top_level.txt deleted file mode 100644 index ad29955..0000000 --- a/.venv/Lib/site-packages/async_timeout-4.0.2.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -async_timeout diff --git a/.venv/Lib/site-packages/async_timeout-4.0.2.dist-info/zip-safe b/.venv/Lib/site-packages/async_timeout-4.0.2.dist-info/zip-safe deleted file mode 100644 index 8b13789..0000000 --- a/.venv/Lib/site-packages/async_timeout-4.0.2.dist-info/zip-safe +++ /dev/null @@ -1 +0,0 @@ - diff --git a/.venv/Lib/site-packages/async_timeout/__init__.py b/.venv/Lib/site-packages/async_timeout/__init__.py deleted file mode 100644 index 179d1b0..0000000 --- a/.venv/Lib/site-packages/async_timeout/__init__.py +++ /dev/null @@ -1,247 +0,0 @@ -import asyncio -import enum -import sys -import warnings -from types import TracebackType -from typing import Any, Optional, Type - - -if sys.version_info >= (3, 8): - from typing import final -else: - from typing_extensions import final - - -__version__ = "4.0.2" - - -__all__ = ("timeout", "timeout_at", "Timeout") - - -def timeout(delay: Optional[float]) -> "Timeout": - """timeout context manager. - - Useful in cases when you want to apply timeout logic around block - of code or in cases when asyncio.wait_for is not suitable. For example: - - >>> async with timeout(0.001): - ... async with aiohttp.get('https://github.com') as r: - ... await r.text() - - - delay - value in seconds or None to disable timeout logic - """ - loop = _get_running_loop() - if delay is not None: - deadline = loop.time() + delay # type: Optional[float] - else: - deadline = None - return Timeout(deadline, loop) - - -def timeout_at(deadline: Optional[float]) -> "Timeout": - """Schedule the timeout at absolute time. - - deadline argument points on the time in the same clock system - as loop.time(). - - Please note: it is not POSIX time but a time with - undefined starting base, e.g. the time of the system power on. - - >>> async with timeout_at(loop.time() + 10): - ... async with aiohttp.get('https://github.com') as r: - ... await r.text() - - - """ - loop = _get_running_loop() - return Timeout(deadline, loop) - - -class _State(enum.Enum): - INIT = "INIT" - ENTER = "ENTER" - TIMEOUT = "TIMEOUT" - EXIT = "EXIT" - - -@final -class Timeout: - # Internal class, please don't instantiate it directly - # Use timeout() and timeout_at() public factories instead. - # - # Implementation note: `async with timeout()` is preferred - # over `with timeout()`. - # While technically the Timeout class implementation - # doesn't need to be async at all, - # the `async with` statement explicitly points that - # the context manager should be used from async function context. - # - # This design allows to avoid many silly misusages. - # - # TimeoutError is raised immadiatelly when scheduled - # if the deadline is passed. - # The purpose is to time out as sson as possible - # without waiting for the next await expression. - - __slots__ = ("_deadline", "_loop", "_state", "_timeout_handler") - - def __init__( - self, deadline: Optional[float], loop: asyncio.AbstractEventLoop - ) -> None: - self._loop = loop - self._state = _State.INIT - - self._timeout_handler = None # type: Optional[asyncio.Handle] - if deadline is None: - self._deadline = None # type: Optional[float] - else: - self.update(deadline) - - def __enter__(self) -> "Timeout": - warnings.warn( - "with timeout() is deprecated, use async with timeout() instead", - DeprecationWarning, - stacklevel=2, - ) - self._do_enter() - return self - - def __exit__( - self, - exc_type: Optional[Type[BaseException]], - exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType], - ) -> Optional[bool]: - self._do_exit(exc_type) - return None - - async def __aenter__(self) -> "Timeout": - self._do_enter() - return self - - async def __aexit__( - self, - exc_type: Optional[Type[BaseException]], - exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType], - ) -> Optional[bool]: - self._do_exit(exc_type) - return None - - @property - def expired(self) -> bool: - """Is timeout expired during execution?""" - return self._state == _State.TIMEOUT - - @property - def deadline(self) -> Optional[float]: - return self._deadline - - def reject(self) -> None: - """Reject scheduled timeout if any.""" - # cancel is maybe better name but - # task.cancel() raises CancelledError in asyncio world. - if self._state not in (_State.INIT, _State.ENTER): - raise RuntimeError(f"invalid state {self._state.value}") - self._reject() - - def _reject(self) -> None: - if self._timeout_handler is not None: - self._timeout_handler.cancel() - self._timeout_handler = None - - def shift(self, delay: float) -> None: - """Advance timeout on delay seconds. - - The delay can be negative. - - Raise RuntimeError if shift is called when deadline is not scheduled - """ - deadline = self._deadline - if deadline is None: - raise RuntimeError("cannot shift timeout if deadline is not scheduled") - self.update(deadline + delay) - - def update(self, deadline: float) -> None: - """Set deadline to absolute value. - - deadline argument points on the time in the same clock system - as loop.time(). - - If new deadline is in the past the timeout is raised immediatelly. - - Please note: it is not POSIX time but a time with - undefined starting base, e.g. the time of the system power on. - """ - if self._state == _State.EXIT: - raise RuntimeError("cannot reschedule after exit from context manager") - if self._state == _State.TIMEOUT: - raise RuntimeError("cannot reschedule expired timeout") - if self._timeout_handler is not None: - self._timeout_handler.cancel() - self._deadline = deadline - if self._state != _State.INIT: - self._reschedule() - - def _reschedule(self) -> None: - assert self._state == _State.ENTER - deadline = self._deadline - if deadline is None: - return - - now = self._loop.time() - if self._timeout_handler is not None: - self._timeout_handler.cancel() - - task = _current_task(self._loop) - if deadline <= now: - self._timeout_handler = self._loop.call_soon(self._on_timeout, task) - else: - self._timeout_handler = self._loop.call_at(deadline, self._on_timeout, task) - - def _do_enter(self) -> None: - if self._state != _State.INIT: - raise RuntimeError(f"invalid state {self._state.value}") - self._state = _State.ENTER - self._reschedule() - - def _do_exit(self, exc_type: Optional[Type[BaseException]]) -> None: - if exc_type is asyncio.CancelledError and self._state == _State.TIMEOUT: - self._timeout_handler = None - raise asyncio.TimeoutError - # timeout has not expired - self._state = _State.EXIT - self._reject() - return None - - def _on_timeout(self, task: "asyncio.Task[None]") -> None: - task.cancel() - self._state = _State.TIMEOUT - # drop the reference early - self._timeout_handler = None - - -if sys.version_info >= (3, 7): - - def _current_task(loop: asyncio.AbstractEventLoop) -> "Optional[asyncio.Task[Any]]": - return asyncio.current_task(loop=loop) - -else: - - def _current_task(loop: asyncio.AbstractEventLoop) -> "Optional[asyncio.Task[Any]]": - return asyncio.Task.current_task(loop=loop) - - -if sys.version_info >= (3, 7): - - def _get_running_loop() -> asyncio.AbstractEventLoop: - return asyncio.get_running_loop() - -else: - - def _get_running_loop() -> asyncio.AbstractEventLoop: - loop = asyncio.get_event_loop() - if not loop.is_running(): - raise RuntimeError("no running event loop") - return loop diff --git a/.venv/Lib/site-packages/async_timeout/__pycache__/__init__.cpython-38.pyc b/.venv/Lib/site-packages/async_timeout/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index 84b5027..0000000 Binary files a/.venv/Lib/site-packages/async_timeout/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/async_timeout/py.typed b/.venv/Lib/site-packages/async_timeout/py.typed deleted file mode 100644 index 3b94f91..0000000 --- a/.venv/Lib/site-packages/async_timeout/py.typed +++ /dev/null @@ -1 +0,0 @@ -Placeholder diff --git a/.venv/Lib/site-packages/attr/__init__.py b/.venv/Lib/site-packages/attr/__init__.py deleted file mode 100644 index 386305d..0000000 --- a/.venv/Lib/site-packages/attr/__init__.py +++ /dev/null @@ -1,79 +0,0 @@ -# SPDX-License-Identifier: MIT - - -import sys - -from functools import partial - -from . import converters, exceptions, filters, setters, validators -from ._cmp import cmp_using -from ._config import get_run_validators, set_run_validators -from ._funcs import asdict, assoc, astuple, evolve, has, resolve_types -from ._make import ( - NOTHING, - Attribute, - Factory, - attrib, - attrs, - fields, - fields_dict, - make_class, - validate, -) -from ._version_info import VersionInfo - - -__version__ = "22.1.0" -__version_info__ = VersionInfo._from_version_string(__version__) - -__title__ = "attrs" -__description__ = "Classes Without Boilerplate" -__url__ = "https://www.attrs.org/" -__uri__ = __url__ -__doc__ = __description__ + " <" + __uri__ + ">" - -__author__ = "Hynek Schlawack" -__email__ = "hs@ox.cx" - -__license__ = "MIT" -__copyright__ = "Copyright (c) 2015 Hynek Schlawack" - - -s = attributes = attrs -ib = attr = attrib -dataclass = partial(attrs, auto_attribs=True) # happy Easter ;) - -__all__ = [ - "Attribute", - "Factory", - "NOTHING", - "asdict", - "assoc", - "astuple", - "attr", - "attrib", - "attributes", - "attrs", - "cmp_using", - "converters", - "evolve", - "exceptions", - "fields", - "fields_dict", - "filters", - "get_run_validators", - "has", - "ib", - "make_class", - "resolve_types", - "s", - "set_run_validators", - "setters", - "validate", - "validators", -] - -if sys.version_info[:2] >= (3, 6): - from ._next_gen import define, field, frozen, mutable # noqa: F401 - - __all__.extend(("define", "field", "frozen", "mutable")) diff --git a/.venv/Lib/site-packages/attr/__init__.pyi b/.venv/Lib/site-packages/attr/__init__.pyi deleted file mode 100644 index 03cc4c8..0000000 --- a/.venv/Lib/site-packages/attr/__init__.pyi +++ /dev/null @@ -1,486 +0,0 @@ -import sys - -from typing import ( - Any, - Callable, - ClassVar, - Dict, - Generic, - List, - Mapping, - Optional, - Protocol, - Sequence, - Tuple, - Type, - TypeVar, - Union, - overload, -) - -# `import X as X` is required to make these public -from . import converters as converters -from . import exceptions as exceptions -from . import filters as filters -from . import setters as setters -from . import validators as validators -from ._cmp import cmp_using as cmp_using -from ._version_info import VersionInfo - -__version__: str -__version_info__: VersionInfo -__title__: str -__description__: str -__url__: str -__uri__: str -__author__: str -__email__: str -__license__: str -__copyright__: str - -_T = TypeVar("_T") -_C = TypeVar("_C", bound=type) - -_EqOrderType = Union[bool, Callable[[Any], Any]] -_ValidatorType = Callable[[Any, Attribute[_T], _T], Any] -_ConverterType = Callable[[Any], Any] -_FilterType = Callable[[Attribute[_T], _T], bool] -_ReprType = Callable[[Any], str] -_ReprArgType = Union[bool, _ReprType] -_OnSetAttrType = Callable[[Any, Attribute[Any], Any], Any] -_OnSetAttrArgType = Union[ - _OnSetAttrType, List[_OnSetAttrType], setters._NoOpType -] -_FieldTransformer = Callable[ - [type, List[Attribute[Any]]], List[Attribute[Any]] -] -# FIXME: in reality, if multiple validators are passed they must be in a list -# or tuple, but those are invariant and so would prevent subtypes of -# _ValidatorType from working when passed in a list or tuple. -_ValidatorArgType = Union[_ValidatorType[_T], Sequence[_ValidatorType[_T]]] - -# A protocol to be able to statically accept an attrs class. -class AttrsInstance(Protocol): - __attrs_attrs__: ClassVar[Any] - -# _make -- - -NOTHING: object - -# NOTE: Factory lies about its return type to make this possible: -# `x: List[int] # = Factory(list)` -# Work around mypy issue #4554 in the common case by using an overload. -if sys.version_info >= (3, 8): - from typing import Literal - @overload - def Factory(factory: Callable[[], _T]) -> _T: ... - @overload - def Factory( - factory: Callable[[Any], _T], - takes_self: Literal[True], - ) -> _T: ... - @overload - def Factory( - factory: Callable[[], _T], - takes_self: Literal[False], - ) -> _T: ... - -else: - @overload - def Factory(factory: Callable[[], _T]) -> _T: ... - @overload - def Factory( - factory: Union[Callable[[Any], _T], Callable[[], _T]], - takes_self: bool = ..., - ) -> _T: ... - -# Static type inference support via __dataclass_transform__ implemented as per: -# https://github.com/microsoft/pyright/blob/1.1.135/specs/dataclass_transforms.md -# This annotation must be applied to all overloads of "define" and "attrs" -# -# NOTE: This is a typing construct and does not exist at runtime. Extensions -# wrapping attrs decorators should declare a separate __dataclass_transform__ -# signature in the extension module using the specification linked above to -# provide pyright support. -def __dataclass_transform__( - *, - eq_default: bool = True, - order_default: bool = False, - kw_only_default: bool = False, - field_descriptors: Tuple[Union[type, Callable[..., Any]], ...] = (()), -) -> Callable[[_T], _T]: ... - -class Attribute(Generic[_T]): - name: str - default: Optional[_T] - validator: Optional[_ValidatorType[_T]] - repr: _ReprArgType - cmp: _EqOrderType - eq: _EqOrderType - order: _EqOrderType - hash: Optional[bool] - init: bool - converter: Optional[_ConverterType] - metadata: Dict[Any, Any] - type: Optional[Type[_T]] - kw_only: bool - on_setattr: _OnSetAttrType - def evolve(self, **changes: Any) -> "Attribute[Any]": ... - -# NOTE: We had several choices for the annotation to use for type arg: -# 1) Type[_T] -# - Pros: Handles simple cases correctly -# - Cons: Might produce less informative errors in the case of conflicting -# TypeVars e.g. `attr.ib(default='bad', type=int)` -# 2) Callable[..., _T] -# - Pros: Better error messages than #1 for conflicting TypeVars -# - Cons: Terrible error messages for validator checks. -# e.g. attr.ib(type=int, validator=validate_str) -# -> error: Cannot infer function type argument -# 3) type (and do all of the work in the mypy plugin) -# - Pros: Simple here, and we could customize the plugin with our own errors. -# - Cons: Would need to write mypy plugin code to handle all the cases. -# We chose option #1. - -# `attr` lies about its return type to make the following possible: -# attr() -> Any -# attr(8) -> int -# attr(validator=) -> Whatever the callable expects. -# This makes this type of assignments possible: -# x: int = attr(8) -# -# This form catches explicit None or no default but with no other arguments -# returns Any. -@overload -def attrib( - default: None = ..., - validator: None = ..., - repr: _ReprArgType = ..., - cmp: Optional[_EqOrderType] = ..., - hash: Optional[bool] = ..., - init: bool = ..., - metadata: Optional[Mapping[Any, Any]] = ..., - type: None = ..., - converter: None = ..., - factory: None = ..., - kw_only: bool = ..., - eq: Optional[_EqOrderType] = ..., - order: Optional[_EqOrderType] = ..., - on_setattr: Optional[_OnSetAttrArgType] = ..., -) -> Any: ... - -# This form catches an explicit None or no default and infers the type from the -# other arguments. -@overload -def attrib( - default: None = ..., - validator: Optional[_ValidatorArgType[_T]] = ..., - repr: _ReprArgType = ..., - cmp: Optional[_EqOrderType] = ..., - hash: Optional[bool] = ..., - init: bool = ..., - metadata: Optional[Mapping[Any, Any]] = ..., - type: Optional[Type[_T]] = ..., - converter: Optional[_ConverterType] = ..., - factory: Optional[Callable[[], _T]] = ..., - kw_only: bool = ..., - eq: Optional[_EqOrderType] = ..., - order: Optional[_EqOrderType] = ..., - on_setattr: Optional[_OnSetAttrArgType] = ..., -) -> _T: ... - -# This form catches an explicit default argument. -@overload -def attrib( - default: _T, - validator: Optional[_ValidatorArgType[_T]] = ..., - repr: _ReprArgType = ..., - cmp: Optional[_EqOrderType] = ..., - hash: Optional[bool] = ..., - init: bool = ..., - metadata: Optional[Mapping[Any, Any]] = ..., - type: Optional[Type[_T]] = ..., - converter: Optional[_ConverterType] = ..., - factory: Optional[Callable[[], _T]] = ..., - kw_only: bool = ..., - eq: Optional[_EqOrderType] = ..., - order: Optional[_EqOrderType] = ..., - on_setattr: Optional[_OnSetAttrArgType] = ..., -) -> _T: ... - -# This form covers type=non-Type: e.g. forward references (str), Any -@overload -def attrib( - default: Optional[_T] = ..., - validator: Optional[_ValidatorArgType[_T]] = ..., - repr: _ReprArgType = ..., - cmp: Optional[_EqOrderType] = ..., - hash: Optional[bool] = ..., - init: bool = ..., - metadata: Optional[Mapping[Any, Any]] = ..., - type: object = ..., - converter: Optional[_ConverterType] = ..., - factory: Optional[Callable[[], _T]] = ..., - kw_only: bool = ..., - eq: Optional[_EqOrderType] = ..., - order: Optional[_EqOrderType] = ..., - on_setattr: Optional[_OnSetAttrArgType] = ..., -) -> Any: ... -@overload -def field( - *, - default: None = ..., - validator: None = ..., - repr: _ReprArgType = ..., - hash: Optional[bool] = ..., - init: bool = ..., - metadata: Optional[Mapping[Any, Any]] = ..., - converter: None = ..., - factory: None = ..., - kw_only: bool = ..., - eq: Optional[bool] = ..., - order: Optional[bool] = ..., - on_setattr: Optional[_OnSetAttrArgType] = ..., -) -> Any: ... - -# This form catches an explicit None or no default and infers the type from the -# other arguments. -@overload -def field( - *, - default: None = ..., - validator: Optional[_ValidatorArgType[_T]] = ..., - repr: _ReprArgType = ..., - hash: Optional[bool] = ..., - init: bool = ..., - metadata: Optional[Mapping[Any, Any]] = ..., - converter: Optional[_ConverterType] = ..., - factory: Optional[Callable[[], _T]] = ..., - kw_only: bool = ..., - eq: Optional[_EqOrderType] = ..., - order: Optional[_EqOrderType] = ..., - on_setattr: Optional[_OnSetAttrArgType] = ..., -) -> _T: ... - -# This form catches an explicit default argument. -@overload -def field( - *, - default: _T, - validator: Optional[_ValidatorArgType[_T]] = ..., - repr: _ReprArgType = ..., - hash: Optional[bool] = ..., - init: bool = ..., - metadata: Optional[Mapping[Any, Any]] = ..., - converter: Optional[_ConverterType] = ..., - factory: Optional[Callable[[], _T]] = ..., - kw_only: bool = ..., - eq: Optional[_EqOrderType] = ..., - order: Optional[_EqOrderType] = ..., - on_setattr: Optional[_OnSetAttrArgType] = ..., -) -> _T: ... - -# This form covers type=non-Type: e.g. forward references (str), Any -@overload -def field( - *, - default: Optional[_T] = ..., - validator: Optional[_ValidatorArgType[_T]] = ..., - repr: _ReprArgType = ..., - hash: Optional[bool] = ..., - init: bool = ..., - metadata: Optional[Mapping[Any, Any]] = ..., - converter: Optional[_ConverterType] = ..., - factory: Optional[Callable[[], _T]] = ..., - kw_only: bool = ..., - eq: Optional[_EqOrderType] = ..., - order: Optional[_EqOrderType] = ..., - on_setattr: Optional[_OnSetAttrArgType] = ..., -) -> Any: ... -@overload -@__dataclass_transform__(order_default=True, field_descriptors=(attrib, field)) -def attrs( - maybe_cls: _C, - these: Optional[Dict[str, Any]] = ..., - repr_ns: Optional[str] = ..., - repr: bool = ..., - cmp: Optional[_EqOrderType] = ..., - hash: Optional[bool] = ..., - init: bool = ..., - slots: bool = ..., - frozen: bool = ..., - weakref_slot: bool = ..., - str: bool = ..., - auto_attribs: bool = ..., - kw_only: bool = ..., - cache_hash: bool = ..., - auto_exc: bool = ..., - eq: Optional[_EqOrderType] = ..., - order: Optional[_EqOrderType] = ..., - auto_detect: bool = ..., - collect_by_mro: bool = ..., - getstate_setstate: Optional[bool] = ..., - on_setattr: Optional[_OnSetAttrArgType] = ..., - field_transformer: Optional[_FieldTransformer] = ..., - match_args: bool = ..., -) -> _C: ... -@overload -@__dataclass_transform__(order_default=True, field_descriptors=(attrib, field)) -def attrs( - maybe_cls: None = ..., - these: Optional[Dict[str, Any]] = ..., - repr_ns: Optional[str] = ..., - repr: bool = ..., - cmp: Optional[_EqOrderType] = ..., - hash: Optional[bool] = ..., - init: bool = ..., - slots: bool = ..., - frozen: bool = ..., - weakref_slot: bool = ..., - str: bool = ..., - auto_attribs: bool = ..., - kw_only: bool = ..., - cache_hash: bool = ..., - auto_exc: bool = ..., - eq: Optional[_EqOrderType] = ..., - order: Optional[_EqOrderType] = ..., - auto_detect: bool = ..., - collect_by_mro: bool = ..., - getstate_setstate: Optional[bool] = ..., - on_setattr: Optional[_OnSetAttrArgType] = ..., - field_transformer: Optional[_FieldTransformer] = ..., - match_args: bool = ..., -) -> Callable[[_C], _C]: ... -@overload -@__dataclass_transform__(field_descriptors=(attrib, field)) -def define( - maybe_cls: _C, - *, - these: Optional[Dict[str, Any]] = ..., - repr: bool = ..., - hash: Optional[bool] = ..., - init: bool = ..., - slots: bool = ..., - frozen: bool = ..., - weakref_slot: bool = ..., - str: bool = ..., - auto_attribs: bool = ..., - kw_only: bool = ..., - cache_hash: bool = ..., - auto_exc: bool = ..., - eq: Optional[bool] = ..., - order: Optional[bool] = ..., - auto_detect: bool = ..., - getstate_setstate: Optional[bool] = ..., - on_setattr: Optional[_OnSetAttrArgType] = ..., - field_transformer: Optional[_FieldTransformer] = ..., - match_args: bool = ..., -) -> _C: ... -@overload -@__dataclass_transform__(field_descriptors=(attrib, field)) -def define( - maybe_cls: None = ..., - *, - these: Optional[Dict[str, Any]] = ..., - repr: bool = ..., - hash: Optional[bool] = ..., - init: bool = ..., - slots: bool = ..., - frozen: bool = ..., - weakref_slot: bool = ..., - str: bool = ..., - auto_attribs: bool = ..., - kw_only: bool = ..., - cache_hash: bool = ..., - auto_exc: bool = ..., - eq: Optional[bool] = ..., - order: Optional[bool] = ..., - auto_detect: bool = ..., - getstate_setstate: Optional[bool] = ..., - on_setattr: Optional[_OnSetAttrArgType] = ..., - field_transformer: Optional[_FieldTransformer] = ..., - match_args: bool = ..., -) -> Callable[[_C], _C]: ... - -mutable = define -frozen = define # they differ only in their defaults - -def fields(cls: Type[AttrsInstance]) -> Any: ... -def fields_dict(cls: Type[AttrsInstance]) -> Dict[str, Attribute[Any]]: ... -def validate(inst: AttrsInstance) -> None: ... -def resolve_types( - cls: _C, - globalns: Optional[Dict[str, Any]] = ..., - localns: Optional[Dict[str, Any]] = ..., - attribs: Optional[List[Attribute[Any]]] = ..., -) -> _C: ... - -# TODO: add support for returning a proper attrs class from the mypy plugin -# we use Any instead of _CountingAttr so that e.g. `make_class('Foo', -# [attr.ib()])` is valid -def make_class( - name: str, - attrs: Union[List[str], Tuple[str, ...], Dict[str, Any]], - bases: Tuple[type, ...] = ..., - repr_ns: Optional[str] = ..., - repr: bool = ..., - cmp: Optional[_EqOrderType] = ..., - hash: Optional[bool] = ..., - init: bool = ..., - slots: bool = ..., - frozen: bool = ..., - weakref_slot: bool = ..., - str: bool = ..., - auto_attribs: bool = ..., - kw_only: bool = ..., - cache_hash: bool = ..., - auto_exc: bool = ..., - eq: Optional[_EqOrderType] = ..., - order: Optional[_EqOrderType] = ..., - collect_by_mro: bool = ..., - on_setattr: Optional[_OnSetAttrArgType] = ..., - field_transformer: Optional[_FieldTransformer] = ..., -) -> type: ... - -# _funcs -- - -# TODO: add support for returning TypedDict from the mypy plugin -# FIXME: asdict/astuple do not honor their factory args. Waiting on one of -# these: -# https://github.com/python/mypy/issues/4236 -# https://github.com/python/typing/issues/253 -# XXX: remember to fix attrs.asdict/astuple too! -def asdict( - inst: AttrsInstance, - recurse: bool = ..., - filter: Optional[_FilterType[Any]] = ..., - dict_factory: Type[Mapping[Any, Any]] = ..., - retain_collection_types: bool = ..., - value_serializer: Optional[ - Callable[[type, Attribute[Any], Any], Any] - ] = ..., - tuple_keys: Optional[bool] = ..., -) -> Dict[str, Any]: ... - -# TODO: add support for returning NamedTuple from the mypy plugin -def astuple( - inst: AttrsInstance, - recurse: bool = ..., - filter: Optional[_FilterType[Any]] = ..., - tuple_factory: Type[Sequence[Any]] = ..., - retain_collection_types: bool = ..., -) -> Tuple[Any, ...]: ... -def has(cls: type) -> bool: ... -def assoc(inst: _T, **changes: Any) -> _T: ... -def evolve(inst: _T, **changes: Any) -> _T: ... - -# _config -- - -def set_run_validators(run: bool) -> None: ... -def get_run_validators() -> bool: ... - -# aliases -- - -s = attributes = attrs -ib = attr = attrib -dataclass = attrs # Technically, partial(attrs, auto_attribs=True) ;) diff --git a/.venv/Lib/site-packages/attr/__pycache__/__init__.cpython-38.pyc b/.venv/Lib/site-packages/attr/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index f6ae9b4..0000000 Binary files a/.venv/Lib/site-packages/attr/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/attr/__pycache__/_cmp.cpython-38.pyc b/.venv/Lib/site-packages/attr/__pycache__/_cmp.cpython-38.pyc deleted file mode 100644 index 9b0e6f0..0000000 Binary files a/.venv/Lib/site-packages/attr/__pycache__/_cmp.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/attr/__pycache__/_compat.cpython-38.pyc b/.venv/Lib/site-packages/attr/__pycache__/_compat.cpython-38.pyc deleted file mode 100644 index 0874156..0000000 Binary files a/.venv/Lib/site-packages/attr/__pycache__/_compat.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/attr/__pycache__/_config.cpython-38.pyc b/.venv/Lib/site-packages/attr/__pycache__/_config.cpython-38.pyc deleted file mode 100644 index 984eb4d..0000000 Binary files a/.venv/Lib/site-packages/attr/__pycache__/_config.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/attr/__pycache__/_funcs.cpython-38.pyc b/.venv/Lib/site-packages/attr/__pycache__/_funcs.cpython-38.pyc deleted file mode 100644 index b49b1ee..0000000 Binary files a/.venv/Lib/site-packages/attr/__pycache__/_funcs.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/attr/__pycache__/_make.cpython-38.pyc b/.venv/Lib/site-packages/attr/__pycache__/_make.cpython-38.pyc deleted file mode 100644 index add8af0..0000000 Binary files a/.venv/Lib/site-packages/attr/__pycache__/_make.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/attr/__pycache__/_next_gen.cpython-38.pyc b/.venv/Lib/site-packages/attr/__pycache__/_next_gen.cpython-38.pyc deleted file mode 100644 index 2834214..0000000 Binary files a/.venv/Lib/site-packages/attr/__pycache__/_next_gen.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/attr/__pycache__/_version_info.cpython-38.pyc b/.venv/Lib/site-packages/attr/__pycache__/_version_info.cpython-38.pyc deleted file mode 100644 index 645c4a9..0000000 Binary files a/.venv/Lib/site-packages/attr/__pycache__/_version_info.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/attr/__pycache__/converters.cpython-38.pyc b/.venv/Lib/site-packages/attr/__pycache__/converters.cpython-38.pyc deleted file mode 100644 index 00421ab..0000000 Binary files a/.venv/Lib/site-packages/attr/__pycache__/converters.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/attr/__pycache__/exceptions.cpython-38.pyc b/.venv/Lib/site-packages/attr/__pycache__/exceptions.cpython-38.pyc deleted file mode 100644 index 3e9195f..0000000 Binary files a/.venv/Lib/site-packages/attr/__pycache__/exceptions.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/attr/__pycache__/filters.cpython-38.pyc b/.venv/Lib/site-packages/attr/__pycache__/filters.cpython-38.pyc deleted file mode 100644 index c91be75..0000000 Binary files a/.venv/Lib/site-packages/attr/__pycache__/filters.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/attr/__pycache__/setters.cpython-38.pyc b/.venv/Lib/site-packages/attr/__pycache__/setters.cpython-38.pyc deleted file mode 100644 index 66eafc0..0000000 Binary files a/.venv/Lib/site-packages/attr/__pycache__/setters.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/attr/__pycache__/validators.cpython-38.pyc b/.venv/Lib/site-packages/attr/__pycache__/validators.cpython-38.pyc deleted file mode 100644 index 04e154e..0000000 Binary files a/.venv/Lib/site-packages/attr/__pycache__/validators.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/attr/_cmp.py b/.venv/Lib/site-packages/attr/_cmp.py deleted file mode 100644 index 81b99e4..0000000 --- a/.venv/Lib/site-packages/attr/_cmp.py +++ /dev/null @@ -1,155 +0,0 @@ -# SPDX-License-Identifier: MIT - - -import functools -import types - -from ._make import _make_ne - - -_operation_names = {"eq": "==", "lt": "<", "le": "<=", "gt": ">", "ge": ">="} - - -def cmp_using( - eq=None, - lt=None, - le=None, - gt=None, - ge=None, - require_same_type=True, - class_name="Comparable", -): - """ - Create a class that can be passed into `attr.ib`'s ``eq``, ``order``, and - ``cmp`` arguments to customize field comparison. - - The resulting class will have a full set of ordering methods if - at least one of ``{lt, le, gt, ge}`` and ``eq`` are provided. - - :param Optional[callable] eq: `callable` used to evaluate equality - of two objects. - :param Optional[callable] lt: `callable` used to evaluate whether - one object is less than another object. - :param Optional[callable] le: `callable` used to evaluate whether - one object is less than or equal to another object. - :param Optional[callable] gt: `callable` used to evaluate whether - one object is greater than another object. - :param Optional[callable] ge: `callable` used to evaluate whether - one object is greater than or equal to another object. - - :param bool require_same_type: When `True`, equality and ordering methods - will return `NotImplemented` if objects are not of the same type. - - :param Optional[str] class_name: Name of class. Defaults to 'Comparable'. - - See `comparison` for more details. - - .. versionadded:: 21.1.0 - """ - - body = { - "__slots__": ["value"], - "__init__": _make_init(), - "_requirements": [], - "_is_comparable_to": _is_comparable_to, - } - - # Add operations. - num_order_functions = 0 - has_eq_function = False - - if eq is not None: - has_eq_function = True - body["__eq__"] = _make_operator("eq", eq) - body["__ne__"] = _make_ne() - - if lt is not None: - num_order_functions += 1 - body["__lt__"] = _make_operator("lt", lt) - - if le is not None: - num_order_functions += 1 - body["__le__"] = _make_operator("le", le) - - if gt is not None: - num_order_functions += 1 - body["__gt__"] = _make_operator("gt", gt) - - if ge is not None: - num_order_functions += 1 - body["__ge__"] = _make_operator("ge", ge) - - type_ = types.new_class( - class_name, (object,), {}, lambda ns: ns.update(body) - ) - - # Add same type requirement. - if require_same_type: - type_._requirements.append(_check_same_type) - - # Add total ordering if at least one operation was defined. - if 0 < num_order_functions < 4: - if not has_eq_function: - # functools.total_ordering requires __eq__ to be defined, - # so raise early error here to keep a nice stack. - raise ValueError( - "eq must be define is order to complete ordering from " - "lt, le, gt, ge." - ) - type_ = functools.total_ordering(type_) - - return type_ - - -def _make_init(): - """ - Create __init__ method. - """ - - def __init__(self, value): - """ - Initialize object with *value*. - """ - self.value = value - - return __init__ - - -def _make_operator(name, func): - """ - Create operator method. - """ - - def method(self, other): - if not self._is_comparable_to(other): - return NotImplemented - - result = func(self.value, other.value) - if result is NotImplemented: - return NotImplemented - - return result - - method.__name__ = "__%s__" % (name,) - method.__doc__ = "Return a %s b. Computed by attrs." % ( - _operation_names[name], - ) - - return method - - -def _is_comparable_to(self, other): - """ - Check whether `other` is comparable to `self`. - """ - for func in self._requirements: - if not func(self, other): - return False - return True - - -def _check_same_type(self, other): - """ - Return True if *self* and *other* are of the same type, False otherwise. - """ - return other.value.__class__ is self.value.__class__ diff --git a/.venv/Lib/site-packages/attr/_cmp.pyi b/.venv/Lib/site-packages/attr/_cmp.pyi deleted file mode 100644 index 35437ef..0000000 --- a/.venv/Lib/site-packages/attr/_cmp.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Any, Callable, Optional, Type - -_CompareWithType = Callable[[Any, Any], bool] - -def cmp_using( - eq: Optional[_CompareWithType], - lt: Optional[_CompareWithType], - le: Optional[_CompareWithType], - gt: Optional[_CompareWithType], - ge: Optional[_CompareWithType], - require_same_type: bool, - class_name: str, -) -> Type: ... diff --git a/.venv/Lib/site-packages/attr/_compat.py b/.venv/Lib/site-packages/attr/_compat.py deleted file mode 100644 index 5826493..0000000 --- a/.venv/Lib/site-packages/attr/_compat.py +++ /dev/null @@ -1,185 +0,0 @@ -# SPDX-License-Identifier: MIT - - -import inspect -import platform -import sys -import threading -import types -import warnings - -from collections.abc import Mapping, Sequence # noqa - - -PYPY = platform.python_implementation() == "PyPy" -PY36 = sys.version_info[:2] >= (3, 6) -HAS_F_STRINGS = PY36 -PY310 = sys.version_info[:2] >= (3, 10) - - -if PYPY or PY36: - ordered_dict = dict -else: - from collections import OrderedDict - - ordered_dict = OrderedDict - - -def just_warn(*args, **kw): - warnings.warn( - "Running interpreter doesn't sufficiently support code object " - "introspection. Some features like bare super() or accessing " - "__class__ will not work with slotted classes.", - RuntimeWarning, - stacklevel=2, - ) - - -class _AnnotationExtractor: - """ - Extract type annotations from a callable, returning None whenever there - is none. - """ - - __slots__ = ["sig"] - - def __init__(self, callable): - try: - self.sig = inspect.signature(callable) - except (ValueError, TypeError): # inspect failed - self.sig = None - - def get_first_param_type(self): - """ - Return the type annotation of the first argument if it's not empty. - """ - if not self.sig: - return None - - params = list(self.sig.parameters.values()) - if params and params[0].annotation is not inspect.Parameter.empty: - return params[0].annotation - - return None - - def get_return_type(self): - """ - Return the return type if it's not empty. - """ - if ( - self.sig - and self.sig.return_annotation is not inspect.Signature.empty - ): - return self.sig.return_annotation - - return None - - -def make_set_closure_cell(): - """Return a function of two arguments (cell, value) which sets - the value stored in the closure cell `cell` to `value`. - """ - # pypy makes this easy. (It also supports the logic below, but - # why not do the easy/fast thing?) - if PYPY: - - def set_closure_cell(cell, value): - cell.__setstate__((value,)) - - return set_closure_cell - - # Otherwise gotta do it the hard way. - - # Create a function that will set its first cellvar to `value`. - def set_first_cellvar_to(value): - x = value - return - - # This function will be eliminated as dead code, but - # not before its reference to `x` forces `x` to be - # represented as a closure cell rather than a local. - def force_x_to_be_a_cell(): # pragma: no cover - return x - - try: - # Extract the code object and make sure our assumptions about - # the closure behavior are correct. - co = set_first_cellvar_to.__code__ - if co.co_cellvars != ("x",) or co.co_freevars != (): - raise AssertionError # pragma: no cover - - # Convert this code object to a code object that sets the - # function's first _freevar_ (not cellvar) to the argument. - if sys.version_info >= (3, 8): - - def set_closure_cell(cell, value): - cell.cell_contents = value - - else: - args = [co.co_argcount] - args.append(co.co_kwonlyargcount) - args.extend( - [ - co.co_nlocals, - co.co_stacksize, - co.co_flags, - co.co_code, - co.co_consts, - co.co_names, - co.co_varnames, - co.co_filename, - co.co_name, - co.co_firstlineno, - co.co_lnotab, - # These two arguments are reversed: - co.co_cellvars, - co.co_freevars, - ] - ) - set_first_freevar_code = types.CodeType(*args) - - def set_closure_cell(cell, value): - # Create a function using the set_first_freevar_code, - # whose first closure cell is `cell`. Calling it will - # change the value of that cell. - setter = types.FunctionType( - set_first_freevar_code, {}, "setter", (), (cell,) - ) - # And call it to set the cell. - setter(value) - - # Make sure it works on this interpreter: - def make_func_with_cell(): - x = None - - def func(): - return x # pragma: no cover - - return func - - cell = make_func_with_cell().__closure__[0] - set_closure_cell(cell, 100) - if cell.cell_contents != 100: - raise AssertionError # pragma: no cover - - except Exception: - return just_warn - else: - return set_closure_cell - - -set_closure_cell = make_set_closure_cell() - -# Thread-local global to track attrs instances which are already being repr'd. -# This is needed because there is no other (thread-safe) way to pass info -# about the instances that are already being repr'd through the call stack -# in order to ensure we don't perform infinite recursion. -# -# For instance, if an instance contains a dict which contains that instance, -# we need to know that we're already repr'ing the outside instance from within -# the dict's repr() call. -# -# This lives here rather than in _make.py so that the functions in _make.py -# don't have a direct reference to the thread-local in their globals dict. -# If they have such a reference, it breaks cloudpickle. -repr_context = threading.local() diff --git a/.venv/Lib/site-packages/attr/_config.py b/.venv/Lib/site-packages/attr/_config.py deleted file mode 100644 index 96d4200..0000000 --- a/.venv/Lib/site-packages/attr/_config.py +++ /dev/null @@ -1,31 +0,0 @@ -# SPDX-License-Identifier: MIT - - -__all__ = ["set_run_validators", "get_run_validators"] - -_run_validators = True - - -def set_run_validators(run): - """ - Set whether or not validators are run. By default, they are run. - - .. deprecated:: 21.3.0 It will not be removed, but it also will not be - moved to new ``attrs`` namespace. Use `attrs.validators.set_disabled()` - instead. - """ - if not isinstance(run, bool): - raise TypeError("'run' must be bool.") - global _run_validators - _run_validators = run - - -def get_run_validators(): - """ - Return whether or not validators are run. - - .. deprecated:: 21.3.0 It will not be removed, but it also will not be - moved to new ``attrs`` namespace. Use `attrs.validators.get_disabled()` - instead. - """ - return _run_validators diff --git a/.venv/Lib/site-packages/attr/_funcs.py b/.venv/Lib/site-packages/attr/_funcs.py deleted file mode 100644 index a982d7c..0000000 --- a/.venv/Lib/site-packages/attr/_funcs.py +++ /dev/null @@ -1,420 +0,0 @@ -# SPDX-License-Identifier: MIT - - -import copy - -from ._make import NOTHING, _obj_setattr, fields -from .exceptions import AttrsAttributeNotFoundError - - -def asdict( - inst, - recurse=True, - filter=None, - dict_factory=dict, - retain_collection_types=False, - value_serializer=None, -): - """ - Return the ``attrs`` attribute values of *inst* as a dict. - - Optionally recurse into other ``attrs``-decorated classes. - - :param inst: Instance of an ``attrs``-decorated class. - :param bool recurse: Recurse into classes that are also - ``attrs``-decorated. - :param callable filter: A callable whose return code determines whether an - attribute or element is included (``True``) or dropped (``False``). Is - called with the `attrs.Attribute` as the first argument and the - value as the second argument. - :param callable dict_factory: A callable to produce dictionaries from. For - example, to produce ordered dictionaries instead of normal Python - dictionaries, pass in ``collections.OrderedDict``. - :param bool retain_collection_types: Do not convert to ``list`` when - encountering an attribute whose type is ``tuple`` or ``set``. Only - meaningful if ``recurse`` is ``True``. - :param Optional[callable] value_serializer: A hook that is called for every - attribute or dict key/value. It receives the current instance, field - and value and must return the (updated) value. The hook is run *after* - the optional *filter* has been applied. - - :rtype: return type of *dict_factory* - - :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` - class. - - .. versionadded:: 16.0.0 *dict_factory* - .. versionadded:: 16.1.0 *retain_collection_types* - .. versionadded:: 20.3.0 *value_serializer* - .. versionadded:: 21.3.0 If a dict has a collection for a key, it is - serialized as a tuple. - """ - attrs = fields(inst.__class__) - rv = dict_factory() - for a in attrs: - v = getattr(inst, a.name) - if filter is not None and not filter(a, v): - continue - - if value_serializer is not None: - v = value_serializer(inst, a, v) - - if recurse is True: - if has(v.__class__): - rv[a.name] = asdict( - v, - recurse=True, - filter=filter, - dict_factory=dict_factory, - retain_collection_types=retain_collection_types, - value_serializer=value_serializer, - ) - elif isinstance(v, (tuple, list, set, frozenset)): - cf = v.__class__ if retain_collection_types is True else list - rv[a.name] = cf( - [ - _asdict_anything( - i, - is_key=False, - filter=filter, - dict_factory=dict_factory, - retain_collection_types=retain_collection_types, - value_serializer=value_serializer, - ) - for i in v - ] - ) - elif isinstance(v, dict): - df = dict_factory - rv[a.name] = df( - ( - _asdict_anything( - kk, - is_key=True, - filter=filter, - dict_factory=df, - retain_collection_types=retain_collection_types, - value_serializer=value_serializer, - ), - _asdict_anything( - vv, - is_key=False, - filter=filter, - dict_factory=df, - retain_collection_types=retain_collection_types, - value_serializer=value_serializer, - ), - ) - for kk, vv in v.items() - ) - else: - rv[a.name] = v - else: - rv[a.name] = v - return rv - - -def _asdict_anything( - val, - is_key, - filter, - dict_factory, - retain_collection_types, - value_serializer, -): - """ - ``asdict`` only works on attrs instances, this works on anything. - """ - if getattr(val.__class__, "__attrs_attrs__", None) is not None: - # Attrs class. - rv = asdict( - val, - recurse=True, - filter=filter, - dict_factory=dict_factory, - retain_collection_types=retain_collection_types, - value_serializer=value_serializer, - ) - elif isinstance(val, (tuple, list, set, frozenset)): - if retain_collection_types is True: - cf = val.__class__ - elif is_key: - cf = tuple - else: - cf = list - - rv = cf( - [ - _asdict_anything( - i, - is_key=False, - filter=filter, - dict_factory=dict_factory, - retain_collection_types=retain_collection_types, - value_serializer=value_serializer, - ) - for i in val - ] - ) - elif isinstance(val, dict): - df = dict_factory - rv = df( - ( - _asdict_anything( - kk, - is_key=True, - filter=filter, - dict_factory=df, - retain_collection_types=retain_collection_types, - value_serializer=value_serializer, - ), - _asdict_anything( - vv, - is_key=False, - filter=filter, - dict_factory=df, - retain_collection_types=retain_collection_types, - value_serializer=value_serializer, - ), - ) - for kk, vv in val.items() - ) - else: - rv = val - if value_serializer is not None: - rv = value_serializer(None, None, rv) - - return rv - - -def astuple( - inst, - recurse=True, - filter=None, - tuple_factory=tuple, - retain_collection_types=False, -): - """ - Return the ``attrs`` attribute values of *inst* as a tuple. - - Optionally recurse into other ``attrs``-decorated classes. - - :param inst: Instance of an ``attrs``-decorated class. - :param bool recurse: Recurse into classes that are also - ``attrs``-decorated. - :param callable filter: A callable whose return code determines whether an - attribute or element is included (``True``) or dropped (``False``). Is - called with the `attrs.Attribute` as the first argument and the - value as the second argument. - :param callable tuple_factory: A callable to produce tuples from. For - example, to produce lists instead of tuples. - :param bool retain_collection_types: Do not convert to ``list`` - or ``dict`` when encountering an attribute which type is - ``tuple``, ``dict`` or ``set``. Only meaningful if ``recurse`` is - ``True``. - - :rtype: return type of *tuple_factory* - - :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` - class. - - .. versionadded:: 16.2.0 - """ - attrs = fields(inst.__class__) - rv = [] - retain = retain_collection_types # Very long. :/ - for a in attrs: - v = getattr(inst, a.name) - if filter is not None and not filter(a, v): - continue - if recurse is True: - if has(v.__class__): - rv.append( - astuple( - v, - recurse=True, - filter=filter, - tuple_factory=tuple_factory, - retain_collection_types=retain, - ) - ) - elif isinstance(v, (tuple, list, set, frozenset)): - cf = v.__class__ if retain is True else list - rv.append( - cf( - [ - astuple( - j, - recurse=True, - filter=filter, - tuple_factory=tuple_factory, - retain_collection_types=retain, - ) - if has(j.__class__) - else j - for j in v - ] - ) - ) - elif isinstance(v, dict): - df = v.__class__ if retain is True else dict - rv.append( - df( - ( - astuple( - kk, - tuple_factory=tuple_factory, - retain_collection_types=retain, - ) - if has(kk.__class__) - else kk, - astuple( - vv, - tuple_factory=tuple_factory, - retain_collection_types=retain, - ) - if has(vv.__class__) - else vv, - ) - for kk, vv in v.items() - ) - ) - else: - rv.append(v) - else: - rv.append(v) - - return rv if tuple_factory is list else tuple_factory(rv) - - -def has(cls): - """ - Check whether *cls* is a class with ``attrs`` attributes. - - :param type cls: Class to introspect. - :raise TypeError: If *cls* is not a class. - - :rtype: bool - """ - return getattr(cls, "__attrs_attrs__", None) is not None - - -def assoc(inst, **changes): - """ - Copy *inst* and apply *changes*. - - :param inst: Instance of a class with ``attrs`` attributes. - :param changes: Keyword changes in the new copy. - - :return: A copy of inst with *changes* incorporated. - - :raise attr.exceptions.AttrsAttributeNotFoundError: If *attr_name* couldn't - be found on *cls*. - :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` - class. - - .. deprecated:: 17.1.0 - Use `attrs.evolve` instead if you can. - This function will not be removed du to the slightly different approach - compared to `attrs.evolve`. - """ - import warnings - - warnings.warn( - "assoc is deprecated and will be removed after 2018/01.", - DeprecationWarning, - stacklevel=2, - ) - new = copy.copy(inst) - attrs = fields(inst.__class__) - for k, v in changes.items(): - a = getattr(attrs, k, NOTHING) - if a is NOTHING: - raise AttrsAttributeNotFoundError( - "{k} is not an attrs attribute on {cl}.".format( - k=k, cl=new.__class__ - ) - ) - _obj_setattr(new, k, v) - return new - - -def evolve(inst, **changes): - """ - Create a new instance, based on *inst* with *changes* applied. - - :param inst: Instance of a class with ``attrs`` attributes. - :param changes: Keyword changes in the new copy. - - :return: A copy of inst with *changes* incorporated. - - :raise TypeError: If *attr_name* couldn't be found in the class - ``__init__``. - :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` - class. - - .. versionadded:: 17.1.0 - """ - cls = inst.__class__ - attrs = fields(cls) - for a in attrs: - if not a.init: - continue - attr_name = a.name # To deal with private attributes. - init_name = attr_name if attr_name[0] != "_" else attr_name[1:] - if init_name not in changes: - changes[init_name] = getattr(inst, attr_name) - - return cls(**changes) - - -def resolve_types(cls, globalns=None, localns=None, attribs=None): - """ - Resolve any strings and forward annotations in type annotations. - - This is only required if you need concrete types in `Attribute`'s *type* - field. In other words, you don't need to resolve your types if you only - use them for static type checking. - - With no arguments, names will be looked up in the module in which the class - was created. If this is not what you want, e.g. if the name only exists - inside a method, you may pass *globalns* or *localns* to specify other - dictionaries in which to look up these names. See the docs of - `typing.get_type_hints` for more details. - - :param type cls: Class to resolve. - :param Optional[dict] globalns: Dictionary containing global variables. - :param Optional[dict] localns: Dictionary containing local variables. - :param Optional[list] attribs: List of attribs for the given class. - This is necessary when calling from inside a ``field_transformer`` - since *cls* is not an ``attrs`` class yet. - - :raise TypeError: If *cls* is not a class. - :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` - class and you didn't pass any attribs. - :raise NameError: If types cannot be resolved because of missing variables. - - :returns: *cls* so you can use this function also as a class decorator. - Please note that you have to apply it **after** `attrs.define`. That - means the decorator has to come in the line **before** `attrs.define`. - - .. versionadded:: 20.1.0 - .. versionadded:: 21.1.0 *attribs* - - """ - # Since calling get_type_hints is expensive we cache whether we've - # done it already. - if getattr(cls, "__attrs_types_resolved__", None) != cls: - import typing - - hints = typing.get_type_hints(cls, globalns=globalns, localns=localns) - for field in fields(cls) if attribs is None else attribs: - if field.name in hints: - # Since fields have been frozen we must work around it. - _obj_setattr(field, "type", hints[field.name]) - # We store the class we resolved so that subclasses know they haven't - # been resolved. - cls.__attrs_types_resolved__ = cls - - # Return the class so you can use it as a decorator too. - return cls diff --git a/.venv/Lib/site-packages/attr/_make.py b/.venv/Lib/site-packages/attr/_make.py deleted file mode 100644 index 4d1afe3..0000000 --- a/.venv/Lib/site-packages/attr/_make.py +++ /dev/null @@ -1,3006 +0,0 @@ -# SPDX-License-Identifier: MIT - -import copy -import linecache -import sys -import types -import typing - -from operator import itemgetter - -# We need to import _compat itself in addition to the _compat members to avoid -# having the thread-local in the globals here. -from . import _compat, _config, setters -from ._compat import ( - HAS_F_STRINGS, - PY310, - PYPY, - _AnnotationExtractor, - ordered_dict, - set_closure_cell, -) -from .exceptions import ( - DefaultAlreadySetError, - FrozenInstanceError, - NotAnAttrsClassError, - UnannotatedAttributeError, -) - - -# This is used at least twice, so cache it here. -_obj_setattr = object.__setattr__ -_init_converter_pat = "__attr_converter_%s" -_init_factory_pat = "__attr_factory_{}" -_tuple_property_pat = ( - " {attr_name} = _attrs_property(_attrs_itemgetter({index}))" -) -_classvar_prefixes = ( - "typing.ClassVar", - "t.ClassVar", - "ClassVar", - "typing_extensions.ClassVar", -) -# we don't use a double-underscore prefix because that triggers -# name mangling when trying to create a slot for the field -# (when slots=True) -_hash_cache_field = "_attrs_cached_hash" - -_empty_metadata_singleton = types.MappingProxyType({}) - -# Unique object for unequivocal getattr() defaults. -_sentinel = object() - -_ng_default_on_setattr = setters.pipe(setters.convert, setters.validate) - - -class _Nothing: - """ - Sentinel class to indicate the lack of a value when ``None`` is ambiguous. - - ``_Nothing`` is a singleton. There is only ever one of it. - - .. versionchanged:: 21.1.0 ``bool(NOTHING)`` is now False. - """ - - _singleton = None - - def __new__(cls): - if _Nothing._singleton is None: - _Nothing._singleton = super().__new__(cls) - return _Nothing._singleton - - def __repr__(self): - return "NOTHING" - - def __bool__(self): - return False - - -NOTHING = _Nothing() -""" -Sentinel to indicate the lack of a value when ``None`` is ambiguous. -""" - - -class _CacheHashWrapper(int): - """ - An integer subclass that pickles / copies as None - - This is used for non-slots classes with ``cache_hash=True``, to avoid - serializing a potentially (even likely) invalid hash value. Since ``None`` - is the default value for uncalculated hashes, whenever this is copied, - the copy's value for the hash should automatically reset. - - See GH #613 for more details. - """ - - def __reduce__(self, _none_constructor=type(None), _args=()): - return _none_constructor, _args - - -def attrib( - default=NOTHING, - validator=None, - repr=True, - cmp=None, - hash=None, - init=True, - metadata=None, - type=None, - converter=None, - factory=None, - kw_only=False, - eq=None, - order=None, - on_setattr=None, -): - """ - Create a new attribute on a class. - - .. warning:: - - Does *not* do anything unless the class is also decorated with - `attr.s`! - - :param default: A value that is used if an ``attrs``-generated ``__init__`` - is used and no value is passed while instantiating or the attribute is - excluded using ``init=False``. - - If the value is an instance of `attrs.Factory`, its callable will be - used to construct a new value (useful for mutable data types like lists - or dicts). - - If a default is not set (or set manually to `attrs.NOTHING`), a value - *must* be supplied when instantiating; otherwise a `TypeError` - will be raised. - - The default can also be set using decorator notation as shown below. - - :type default: Any value - - :param callable factory: Syntactic sugar for - ``default=attr.Factory(factory)``. - - :param validator: `callable` that is called by ``attrs``-generated - ``__init__`` methods after the instance has been initialized. They - receive the initialized instance, the :func:`~attrs.Attribute`, and the - passed value. - - The return value is *not* inspected so the validator has to throw an - exception itself. - - If a `list` is passed, its items are treated as validators and must - all pass. - - Validators can be globally disabled and re-enabled using - `get_run_validators`. - - The validator can also be set using decorator notation as shown below. - - :type validator: `callable` or a `list` of `callable`\\ s. - - :param repr: Include this attribute in the generated ``__repr__`` - method. If ``True``, include the attribute; if ``False``, omit it. By - default, the built-in ``repr()`` function is used. To override how the - attribute value is formatted, pass a ``callable`` that takes a single - value and returns a string. Note that the resulting string is used - as-is, i.e. it will be used directly *instead* of calling ``repr()`` - (the default). - :type repr: a `bool` or a `callable` to use a custom function. - - :param eq: If ``True`` (default), include this attribute in the - generated ``__eq__`` and ``__ne__`` methods that check two instances - for equality. To override how the attribute value is compared, - pass a ``callable`` that takes a single value and returns the value - to be compared. - :type eq: a `bool` or a `callable`. - - :param order: If ``True`` (default), include this attributes in the - generated ``__lt__``, ``__le__``, ``__gt__`` and ``__ge__`` methods. - To override how the attribute value is ordered, - pass a ``callable`` that takes a single value and returns the value - to be ordered. - :type order: a `bool` or a `callable`. - - :param cmp: Setting *cmp* is equivalent to setting *eq* and *order* to the - same value. Must not be mixed with *eq* or *order*. - :type cmp: a `bool` or a `callable`. - - :param Optional[bool] hash: Include this attribute in the generated - ``__hash__`` method. If ``None`` (default), mirror *eq*'s value. This - is the correct behavior according the Python spec. Setting this value - to anything else than ``None`` is *discouraged*. - :param bool init: Include this attribute in the generated ``__init__`` - method. It is possible to set this to ``False`` and set a default - value. In that case this attributed is unconditionally initialized - with the specified default value or factory. - :param callable converter: `callable` that is called by - ``attrs``-generated ``__init__`` methods to convert attribute's value - to the desired format. It is given the passed-in value, and the - returned value will be used as the new value of the attribute. The - value is converted before being passed to the validator, if any. - :param metadata: An arbitrary mapping, to be used by third-party - components. See `extending_metadata`. - :param type: The type of the attribute. In Python 3.6 or greater, the - preferred method to specify the type is using a variable annotation - (see :pep:`526`). - This argument is provided for backward compatibility. - Regardless of the approach used, the type will be stored on - ``Attribute.type``. - - Please note that ``attrs`` doesn't do anything with this metadata by - itself. You can use it as part of your own code or for - `static type checking `. - :param kw_only: Make this attribute keyword-only (Python 3+) - in the generated ``__init__`` (if ``init`` is ``False``, this - parameter is ignored). - :param on_setattr: Allows to overwrite the *on_setattr* setting from - `attr.s`. If left `None`, the *on_setattr* value from `attr.s` is used. - Set to `attrs.setters.NO_OP` to run **no** `setattr` hooks for this - attribute -- regardless of the setting in `attr.s`. - :type on_setattr: `callable`, or a list of callables, or `None`, or - `attrs.setters.NO_OP` - - .. versionadded:: 15.2.0 *convert* - .. versionadded:: 16.3.0 *metadata* - .. versionchanged:: 17.1.0 *validator* can be a ``list`` now. - .. versionchanged:: 17.1.0 - *hash* is ``None`` and therefore mirrors *eq* by default. - .. versionadded:: 17.3.0 *type* - .. deprecated:: 17.4.0 *convert* - .. versionadded:: 17.4.0 *converter* as a replacement for the deprecated - *convert* to achieve consistency with other noun-based arguments. - .. versionadded:: 18.1.0 - ``factory=f`` is syntactic sugar for ``default=attr.Factory(f)``. - .. versionadded:: 18.2.0 *kw_only* - .. versionchanged:: 19.2.0 *convert* keyword argument removed. - .. versionchanged:: 19.2.0 *repr* also accepts a custom callable. - .. deprecated:: 19.2.0 *cmp* Removal on or after 2021-06-01. - .. versionadded:: 19.2.0 *eq* and *order* - .. versionadded:: 20.1.0 *on_setattr* - .. versionchanged:: 20.3.0 *kw_only* backported to Python 2 - .. versionchanged:: 21.1.0 - *eq*, *order*, and *cmp* also accept a custom callable - .. versionchanged:: 21.1.0 *cmp* undeprecated - """ - eq, eq_key, order, order_key = _determine_attrib_eq_order( - cmp, eq, order, True - ) - - if hash is not None and hash is not True and hash is not False: - raise TypeError( - "Invalid value for hash. Must be True, False, or None." - ) - - if factory is not None: - if default is not NOTHING: - raise ValueError( - "The `default` and `factory` arguments are mutually " - "exclusive." - ) - if not callable(factory): - raise ValueError("The `factory` argument must be a callable.") - default = Factory(factory) - - if metadata is None: - metadata = {} - - # Apply syntactic sugar by auto-wrapping. - if isinstance(on_setattr, (list, tuple)): - on_setattr = setters.pipe(*on_setattr) - - if validator and isinstance(validator, (list, tuple)): - validator = and_(*validator) - - if converter and isinstance(converter, (list, tuple)): - converter = pipe(*converter) - - return _CountingAttr( - default=default, - validator=validator, - repr=repr, - cmp=None, - hash=hash, - init=init, - converter=converter, - metadata=metadata, - type=type, - kw_only=kw_only, - eq=eq, - eq_key=eq_key, - order=order, - order_key=order_key, - on_setattr=on_setattr, - ) - - -def _compile_and_eval(script, globs, locs=None, filename=""): - """ - "Exec" the script with the given global (globs) and local (locs) variables. - """ - bytecode = compile(script, filename, "exec") - eval(bytecode, globs, locs) - - -def _make_method(name, script, filename, globs): - """ - Create the method with the script given and return the method object. - """ - locs = {} - - # In order of debuggers like PDB being able to step through the code, - # we add a fake linecache entry. - count = 1 - base_filename = filename - while True: - linecache_tuple = ( - len(script), - None, - script.splitlines(True), - filename, - ) - old_val = linecache.cache.setdefault(filename, linecache_tuple) - if old_val == linecache_tuple: - break - else: - filename = "{}-{}>".format(base_filename[:-1], count) - count += 1 - - _compile_and_eval(script, globs, locs, filename) - - return locs[name] - - -def _make_attr_tuple_class(cls_name, attr_names): - """ - Create a tuple subclass to hold `Attribute`s for an `attrs` class. - - The subclass is a bare tuple with properties for names. - - class MyClassAttributes(tuple): - __slots__ = () - x = property(itemgetter(0)) - """ - attr_class_name = "{}Attributes".format(cls_name) - attr_class_template = [ - "class {}(tuple):".format(attr_class_name), - " __slots__ = ()", - ] - if attr_names: - for i, attr_name in enumerate(attr_names): - attr_class_template.append( - _tuple_property_pat.format(index=i, attr_name=attr_name) - ) - else: - attr_class_template.append(" pass") - globs = {"_attrs_itemgetter": itemgetter, "_attrs_property": property} - _compile_and_eval("\n".join(attr_class_template), globs) - return globs[attr_class_name] - - -# Tuple class for extracted attributes from a class definition. -# `base_attrs` is a subset of `attrs`. -_Attributes = _make_attr_tuple_class( - "_Attributes", - [ - # all attributes to build dunder methods for - "attrs", - # attributes that have been inherited - "base_attrs", - # map inherited attributes to their originating classes - "base_attrs_map", - ], -) - - -def _is_class_var(annot): - """ - Check whether *annot* is a typing.ClassVar. - - The string comparison hack is used to avoid evaluating all string - annotations which would put attrs-based classes at a performance - disadvantage compared to plain old classes. - """ - annot = str(annot) - - # Annotation can be quoted. - if annot.startswith(("'", '"')) and annot.endswith(("'", '"')): - annot = annot[1:-1] - - return annot.startswith(_classvar_prefixes) - - -def _has_own_attribute(cls, attrib_name): - """ - Check whether *cls* defines *attrib_name* (and doesn't just inherit it). - - Requires Python 3. - """ - attr = getattr(cls, attrib_name, _sentinel) - if attr is _sentinel: - return False - - for base_cls in cls.__mro__[1:]: - a = getattr(base_cls, attrib_name, None) - if attr is a: - return False - - return True - - -def _get_annotations(cls): - """ - Get annotations for *cls*. - """ - if _has_own_attribute(cls, "__annotations__"): - return cls.__annotations__ - - return {} - - -def _counter_getter(e): - """ - Key function for sorting to avoid re-creating a lambda for every class. - """ - return e[1].counter - - -def _collect_base_attrs(cls, taken_attr_names): - """ - Collect attr.ibs from base classes of *cls*, except *taken_attr_names*. - """ - base_attrs = [] - base_attr_map = {} # A dictionary of base attrs to their classes. - - # Traverse the MRO and collect attributes. - for base_cls in reversed(cls.__mro__[1:-1]): - for a in getattr(base_cls, "__attrs_attrs__", []): - if a.inherited or a.name in taken_attr_names: - continue - - a = a.evolve(inherited=True) - base_attrs.append(a) - base_attr_map[a.name] = base_cls - - # For each name, only keep the freshest definition i.e. the furthest at the - # back. base_attr_map is fine because it gets overwritten with every new - # instance. - filtered = [] - seen = set() - for a in reversed(base_attrs): - if a.name in seen: - continue - filtered.insert(0, a) - seen.add(a.name) - - return filtered, base_attr_map - - -def _collect_base_attrs_broken(cls, taken_attr_names): - """ - Collect attr.ibs from base classes of *cls*, except *taken_attr_names*. - - N.B. *taken_attr_names* will be mutated. - - Adhere to the old incorrect behavior. - - Notably it collects from the front and considers inherited attributes which - leads to the buggy behavior reported in #428. - """ - base_attrs = [] - base_attr_map = {} # A dictionary of base attrs to their classes. - - # Traverse the MRO and collect attributes. - for base_cls in cls.__mro__[1:-1]: - for a in getattr(base_cls, "__attrs_attrs__", []): - if a.name in taken_attr_names: - continue - - a = a.evolve(inherited=True) - taken_attr_names.add(a.name) - base_attrs.append(a) - base_attr_map[a.name] = base_cls - - return base_attrs, base_attr_map - - -def _transform_attrs( - cls, these, auto_attribs, kw_only, collect_by_mro, field_transformer -): - """ - Transform all `_CountingAttr`s on a class into `Attribute`s. - - If *these* is passed, use that and don't look for them on the class. - - *collect_by_mro* is True, collect them in the correct MRO order, otherwise - use the old -- incorrect -- order. See #428. - - Return an `_Attributes`. - """ - cd = cls.__dict__ - anns = _get_annotations(cls) - - if these is not None: - ca_list = [(name, ca) for name, ca in these.items()] - - if not isinstance(these, ordered_dict): - ca_list.sort(key=_counter_getter) - elif auto_attribs is True: - ca_names = { - name - for name, attr in cd.items() - if isinstance(attr, _CountingAttr) - } - ca_list = [] - annot_names = set() - for attr_name, type in anns.items(): - if _is_class_var(type): - continue - annot_names.add(attr_name) - a = cd.get(attr_name, NOTHING) - - if not isinstance(a, _CountingAttr): - if a is NOTHING: - a = attrib() - else: - a = attrib(default=a) - ca_list.append((attr_name, a)) - - unannotated = ca_names - annot_names - if len(unannotated) > 0: - raise UnannotatedAttributeError( - "The following `attr.ib`s lack a type annotation: " - + ", ".join( - sorted(unannotated, key=lambda n: cd.get(n).counter) - ) - + "." - ) - else: - ca_list = sorted( - ( - (name, attr) - for name, attr in cd.items() - if isinstance(attr, _CountingAttr) - ), - key=lambda e: e[1].counter, - ) - - own_attrs = [ - Attribute.from_counting_attr( - name=attr_name, ca=ca, type=anns.get(attr_name) - ) - for attr_name, ca in ca_list - ] - - if collect_by_mro: - base_attrs, base_attr_map = _collect_base_attrs( - cls, {a.name for a in own_attrs} - ) - else: - base_attrs, base_attr_map = _collect_base_attrs_broken( - cls, {a.name for a in own_attrs} - ) - - if kw_only: - own_attrs = [a.evolve(kw_only=True) for a in own_attrs] - base_attrs = [a.evolve(kw_only=True) for a in base_attrs] - - attrs = base_attrs + own_attrs - - # Mandatory vs non-mandatory attr order only matters when they are part of - # the __init__ signature and when they aren't kw_only (which are moved to - # the end and can be mandatory or non-mandatory in any order, as they will - # be specified as keyword args anyway). Check the order of those attrs: - had_default = False - for a in (a for a in attrs if a.init is not False and a.kw_only is False): - if had_default is True and a.default is NOTHING: - raise ValueError( - "No mandatory attributes allowed after an attribute with a " - "default value or factory. Attribute in question: %r" % (a,) - ) - - if had_default is False and a.default is not NOTHING: - had_default = True - - if field_transformer is not None: - attrs = field_transformer(cls, attrs) - - # Create AttrsClass *after* applying the field_transformer since it may - # add or remove attributes! - attr_names = [a.name for a in attrs] - AttrsClass = _make_attr_tuple_class(cls.__name__, attr_names) - - return _Attributes((AttrsClass(attrs), base_attrs, base_attr_map)) - - -if PYPY: - - def _frozen_setattrs(self, name, value): - """ - Attached to frozen classes as __setattr__. - """ - if isinstance(self, BaseException) and name in ( - "__cause__", - "__context__", - ): - BaseException.__setattr__(self, name, value) - return - - raise FrozenInstanceError() - -else: - - def _frozen_setattrs(self, name, value): - """ - Attached to frozen classes as __setattr__. - """ - raise FrozenInstanceError() - - -def _frozen_delattrs(self, name): - """ - Attached to frozen classes as __delattr__. - """ - raise FrozenInstanceError() - - -class _ClassBuilder: - """ - Iteratively build *one* class. - """ - - __slots__ = ( - "_attr_names", - "_attrs", - "_base_attr_map", - "_base_names", - "_cache_hash", - "_cls", - "_cls_dict", - "_delete_attribs", - "_frozen", - "_has_pre_init", - "_has_post_init", - "_is_exc", - "_on_setattr", - "_slots", - "_weakref_slot", - "_wrote_own_setattr", - "_has_custom_setattr", - ) - - def __init__( - self, - cls, - these, - slots, - frozen, - weakref_slot, - getstate_setstate, - auto_attribs, - kw_only, - cache_hash, - is_exc, - collect_by_mro, - on_setattr, - has_custom_setattr, - field_transformer, - ): - attrs, base_attrs, base_map = _transform_attrs( - cls, - these, - auto_attribs, - kw_only, - collect_by_mro, - field_transformer, - ) - - self._cls = cls - self._cls_dict = dict(cls.__dict__) if slots else {} - self._attrs = attrs - self._base_names = {a.name for a in base_attrs} - self._base_attr_map = base_map - self._attr_names = tuple(a.name for a in attrs) - self._slots = slots - self._frozen = frozen - self._weakref_slot = weakref_slot - self._cache_hash = cache_hash - self._has_pre_init = bool(getattr(cls, "__attrs_pre_init__", False)) - self._has_post_init = bool(getattr(cls, "__attrs_post_init__", False)) - self._delete_attribs = not bool(these) - self._is_exc = is_exc - self._on_setattr = on_setattr - - self._has_custom_setattr = has_custom_setattr - self._wrote_own_setattr = False - - self._cls_dict["__attrs_attrs__"] = self._attrs - - if frozen: - self._cls_dict["__setattr__"] = _frozen_setattrs - self._cls_dict["__delattr__"] = _frozen_delattrs - - self._wrote_own_setattr = True - elif on_setattr in ( - _ng_default_on_setattr, - setters.validate, - setters.convert, - ): - has_validator = has_converter = False - for a in attrs: - if a.validator is not None: - has_validator = True - if a.converter is not None: - has_converter = True - - if has_validator and has_converter: - break - if ( - ( - on_setattr == _ng_default_on_setattr - and not (has_validator or has_converter) - ) - or (on_setattr == setters.validate and not has_validator) - or (on_setattr == setters.convert and not has_converter) - ): - # If class-level on_setattr is set to convert + validate, but - # there's no field to convert or validate, pretend like there's - # no on_setattr. - self._on_setattr = None - - if getstate_setstate: - ( - self._cls_dict["__getstate__"], - self._cls_dict["__setstate__"], - ) = self._make_getstate_setstate() - - def __repr__(self): - return "<_ClassBuilder(cls={cls})>".format(cls=self._cls.__name__) - - def build_class(self): - """ - Finalize class based on the accumulated configuration. - - Builder cannot be used after calling this method. - """ - if self._slots is True: - return self._create_slots_class() - else: - return self._patch_original_class() - - def _patch_original_class(self): - """ - Apply accumulated methods and return the class. - """ - cls = self._cls - base_names = self._base_names - - # Clean class of attribute definitions (`attr.ib()`s). - if self._delete_attribs: - for name in self._attr_names: - if ( - name not in base_names - and getattr(cls, name, _sentinel) is not _sentinel - ): - try: - delattr(cls, name) - except AttributeError: - # This can happen if a base class defines a class - # variable and we want to set an attribute with the - # same name by using only a type annotation. - pass - - # Attach our dunder methods. - for name, value in self._cls_dict.items(): - setattr(cls, name, value) - - # If we've inherited an attrs __setattr__ and don't write our own, - # reset it to object's. - if not self._wrote_own_setattr and getattr( - cls, "__attrs_own_setattr__", False - ): - cls.__attrs_own_setattr__ = False - - if not self._has_custom_setattr: - cls.__setattr__ = _obj_setattr - - return cls - - def _create_slots_class(self): - """ - Build and return a new class with a `__slots__` attribute. - """ - cd = { - k: v - for k, v in self._cls_dict.items() - if k not in tuple(self._attr_names) + ("__dict__", "__weakref__") - } - - # If our class doesn't have its own implementation of __setattr__ - # (either from the user or by us), check the bases, if one of them has - # an attrs-made __setattr__, that needs to be reset. We don't walk the - # MRO because we only care about our immediate base classes. - # XXX: This can be confused by subclassing a slotted attrs class with - # XXX: a non-attrs class and subclass the resulting class with an attrs - # XXX: class. See `test_slotted_confused` for details. For now that's - # XXX: OK with us. - if not self._wrote_own_setattr: - cd["__attrs_own_setattr__"] = False - - if not self._has_custom_setattr: - for base_cls in self._cls.__bases__: - if base_cls.__dict__.get("__attrs_own_setattr__", False): - cd["__setattr__"] = _obj_setattr - break - - # Traverse the MRO to collect existing slots - # and check for an existing __weakref__. - existing_slots = dict() - weakref_inherited = False - for base_cls in self._cls.__mro__[1:-1]: - if base_cls.__dict__.get("__weakref__", None) is not None: - weakref_inherited = True - existing_slots.update( - { - name: getattr(base_cls, name) - for name in getattr(base_cls, "__slots__", []) - } - ) - - base_names = set(self._base_names) - - names = self._attr_names - if ( - self._weakref_slot - and "__weakref__" not in getattr(self._cls, "__slots__", ()) - and "__weakref__" not in names - and not weakref_inherited - ): - names += ("__weakref__",) - - # We only add the names of attributes that aren't inherited. - # Setting __slots__ to inherited attributes wastes memory. - slot_names = [name for name in names if name not in base_names] - # There are slots for attributes from current class - # that are defined in parent classes. - # As their descriptors may be overridden by a child class, - # we collect them here and update the class dict - reused_slots = { - slot: slot_descriptor - for slot, slot_descriptor in existing_slots.items() - if slot in slot_names - } - slot_names = [name for name in slot_names if name not in reused_slots] - cd.update(reused_slots) - if self._cache_hash: - slot_names.append(_hash_cache_field) - cd["__slots__"] = tuple(slot_names) - - cd["__qualname__"] = self._cls.__qualname__ - - # Create new class based on old class and our methods. - cls = type(self._cls)(self._cls.__name__, self._cls.__bases__, cd) - - # The following is a fix for - # . On Python 3, - # if a method mentions `__class__` or uses the no-arg super(), the - # compiler will bake a reference to the class in the method itself - # as `method.__closure__`. Since we replace the class with a - # clone, we rewrite these references so it keeps working. - for item in cls.__dict__.values(): - if isinstance(item, (classmethod, staticmethod)): - # Class- and staticmethods hide their functions inside. - # These might need to be rewritten as well. - closure_cells = getattr(item.__func__, "__closure__", None) - elif isinstance(item, property): - # Workaround for property `super()` shortcut (PY3-only). - # There is no universal way for other descriptors. - closure_cells = getattr(item.fget, "__closure__", None) - else: - closure_cells = getattr(item, "__closure__", None) - - if not closure_cells: # Catch None or the empty list. - continue - for cell in closure_cells: - try: - match = cell.cell_contents is self._cls - except ValueError: # ValueError: Cell is empty - pass - else: - if match: - set_closure_cell(cell, cls) - - return cls - - def add_repr(self, ns): - self._cls_dict["__repr__"] = self._add_method_dunders( - _make_repr(self._attrs, ns, self._cls) - ) - return self - - def add_str(self): - repr = self._cls_dict.get("__repr__") - if repr is None: - raise ValueError( - "__str__ can only be generated if a __repr__ exists." - ) - - def __str__(self): - return self.__repr__() - - self._cls_dict["__str__"] = self._add_method_dunders(__str__) - return self - - def _make_getstate_setstate(self): - """ - Create custom __setstate__ and __getstate__ methods. - """ - # __weakref__ is not writable. - state_attr_names = tuple( - an for an in self._attr_names if an != "__weakref__" - ) - - def slots_getstate(self): - """ - Automatically created by attrs. - """ - return tuple(getattr(self, name) for name in state_attr_names) - - hash_caching_enabled = self._cache_hash - - def slots_setstate(self, state): - """ - Automatically created by attrs. - """ - __bound_setattr = _obj_setattr.__get__(self, Attribute) - for name, value in zip(state_attr_names, state): - __bound_setattr(name, value) - - # The hash code cache is not included when the object is - # serialized, but it still needs to be initialized to None to - # indicate that the first call to __hash__ should be a cache - # miss. - if hash_caching_enabled: - __bound_setattr(_hash_cache_field, None) - - return slots_getstate, slots_setstate - - def make_unhashable(self): - self._cls_dict["__hash__"] = None - return self - - def add_hash(self): - self._cls_dict["__hash__"] = self._add_method_dunders( - _make_hash( - self._cls, - self._attrs, - frozen=self._frozen, - cache_hash=self._cache_hash, - ) - ) - - return self - - def add_init(self): - self._cls_dict["__init__"] = self._add_method_dunders( - _make_init( - self._cls, - self._attrs, - self._has_pre_init, - self._has_post_init, - self._frozen, - self._slots, - self._cache_hash, - self._base_attr_map, - self._is_exc, - self._on_setattr, - attrs_init=False, - ) - ) - - return self - - def add_match_args(self): - self._cls_dict["__match_args__"] = tuple( - field.name - for field in self._attrs - if field.init and not field.kw_only - ) - - def add_attrs_init(self): - self._cls_dict["__attrs_init__"] = self._add_method_dunders( - _make_init( - self._cls, - self._attrs, - self._has_pre_init, - self._has_post_init, - self._frozen, - self._slots, - self._cache_hash, - self._base_attr_map, - self._is_exc, - self._on_setattr, - attrs_init=True, - ) - ) - - return self - - def add_eq(self): - cd = self._cls_dict - - cd["__eq__"] = self._add_method_dunders( - _make_eq(self._cls, self._attrs) - ) - cd["__ne__"] = self._add_method_dunders(_make_ne()) - - return self - - def add_order(self): - cd = self._cls_dict - - cd["__lt__"], cd["__le__"], cd["__gt__"], cd["__ge__"] = ( - self._add_method_dunders(meth) - for meth in _make_order(self._cls, self._attrs) - ) - - return self - - def add_setattr(self): - if self._frozen: - return self - - sa_attrs = {} - for a in self._attrs: - on_setattr = a.on_setattr or self._on_setattr - if on_setattr and on_setattr is not setters.NO_OP: - sa_attrs[a.name] = a, on_setattr - - if not sa_attrs: - return self - - if self._has_custom_setattr: - # We need to write a __setattr__ but there already is one! - raise ValueError( - "Can't combine custom __setattr__ with on_setattr hooks." - ) - - # docstring comes from _add_method_dunders - def __setattr__(self, name, val): - try: - a, hook = sa_attrs[name] - except KeyError: - nval = val - else: - nval = hook(self, a, val) - - _obj_setattr(self, name, nval) - - self._cls_dict["__attrs_own_setattr__"] = True - self._cls_dict["__setattr__"] = self._add_method_dunders(__setattr__) - self._wrote_own_setattr = True - - return self - - def _add_method_dunders(self, method): - """ - Add __module__ and __qualname__ to a *method* if possible. - """ - try: - method.__module__ = self._cls.__module__ - except AttributeError: - pass - - try: - method.__qualname__ = ".".join( - (self._cls.__qualname__, method.__name__) - ) - except AttributeError: - pass - - try: - method.__doc__ = "Method generated by attrs for class %s." % ( - self._cls.__qualname__, - ) - except AttributeError: - pass - - return method - - -def _determine_attrs_eq_order(cmp, eq, order, default_eq): - """ - Validate the combination of *cmp*, *eq*, and *order*. Derive the effective - values of eq and order. If *eq* is None, set it to *default_eq*. - """ - if cmp is not None and any((eq is not None, order is not None)): - raise ValueError("Don't mix `cmp` with `eq' and `order`.") - - # cmp takes precedence due to bw-compatibility. - if cmp is not None: - return cmp, cmp - - # If left None, equality is set to the specified default and ordering - # mirrors equality. - if eq is None: - eq = default_eq - - if order is None: - order = eq - - if eq is False and order is True: - raise ValueError("`order` can only be True if `eq` is True too.") - - return eq, order - - -def _determine_attrib_eq_order(cmp, eq, order, default_eq): - """ - Validate the combination of *cmp*, *eq*, and *order*. Derive the effective - values of eq and order. If *eq* is None, set it to *default_eq*. - """ - if cmp is not None and any((eq is not None, order is not None)): - raise ValueError("Don't mix `cmp` with `eq' and `order`.") - - def decide_callable_or_boolean(value): - """ - Decide whether a key function is used. - """ - if callable(value): - value, key = True, value - else: - key = None - return value, key - - # cmp takes precedence due to bw-compatibility. - if cmp is not None: - cmp, cmp_key = decide_callable_or_boolean(cmp) - return cmp, cmp_key, cmp, cmp_key - - # If left None, equality is set to the specified default and ordering - # mirrors equality. - if eq is None: - eq, eq_key = default_eq, None - else: - eq, eq_key = decide_callable_or_boolean(eq) - - if order is None: - order, order_key = eq, eq_key - else: - order, order_key = decide_callable_or_boolean(order) - - if eq is False and order is True: - raise ValueError("`order` can only be True if `eq` is True too.") - - return eq, eq_key, order, order_key - - -def _determine_whether_to_implement( - cls, flag, auto_detect, dunders, default=True -): - """ - Check whether we should implement a set of methods for *cls*. - - *flag* is the argument passed into @attr.s like 'init', *auto_detect* the - same as passed into @attr.s and *dunders* is a tuple of attribute names - whose presence signal that the user has implemented it themselves. - - Return *default* if no reason for either for or against is found. - """ - if flag is True or flag is False: - return flag - - if flag is None and auto_detect is False: - return default - - # Logically, flag is None and auto_detect is True here. - for dunder in dunders: - if _has_own_attribute(cls, dunder): - return False - - return default - - -def attrs( - maybe_cls=None, - these=None, - repr_ns=None, - repr=None, - cmp=None, - hash=None, - init=None, - slots=False, - frozen=False, - weakref_slot=True, - str=False, - auto_attribs=False, - kw_only=False, - cache_hash=False, - auto_exc=False, - eq=None, - order=None, - auto_detect=False, - collect_by_mro=False, - getstate_setstate=None, - on_setattr=None, - field_transformer=None, - match_args=True, -): - r""" - A class decorator that adds `dunder - `_\ -methods according to the - specified attributes using `attr.ib` or the *these* argument. - - :param these: A dictionary of name to `attr.ib` mappings. This is - useful to avoid the definition of your attributes within the class body - because you can't (e.g. if you want to add ``__repr__`` methods to - Django models) or don't want to. - - If *these* is not ``None``, ``attrs`` will *not* search the class body - for attributes and will *not* remove any attributes from it. - - If *these* is an ordered dict (`dict` on Python 3.6+, - `collections.OrderedDict` otherwise), the order is deduced from - the order of the attributes inside *these*. Otherwise the order - of the definition of the attributes is used. - - :type these: `dict` of `str` to `attr.ib` - - :param str repr_ns: When using nested classes, there's no way in Python 2 - to automatically detect that. Therefore it's possible to set the - namespace explicitly for a more meaningful ``repr`` output. - :param bool auto_detect: Instead of setting the *init*, *repr*, *eq*, - *order*, and *hash* arguments explicitly, assume they are set to - ``True`` **unless any** of the involved methods for one of the - arguments is implemented in the *current* class (i.e. it is *not* - inherited from some base class). - - So for example by implementing ``__eq__`` on a class yourself, - ``attrs`` will deduce ``eq=False`` and will create *neither* - ``__eq__`` *nor* ``__ne__`` (but Python classes come with a sensible - ``__ne__`` by default, so it *should* be enough to only implement - ``__eq__`` in most cases). - - .. warning:: - - If you prevent ``attrs`` from creating the ordering methods for you - (``order=False``, e.g. by implementing ``__le__``), it becomes - *your* responsibility to make sure its ordering is sound. The best - way is to use the `functools.total_ordering` decorator. - - - Passing ``True`` or ``False`` to *init*, *repr*, *eq*, *order*, - *cmp*, or *hash* overrides whatever *auto_detect* would determine. - - *auto_detect* requires Python 3. Setting it ``True`` on Python 2 raises - an `attrs.exceptions.PythonTooOldError`. - - :param bool repr: Create a ``__repr__`` method with a human readable - representation of ``attrs`` attributes.. - :param bool str: Create a ``__str__`` method that is identical to - ``__repr__``. This is usually not necessary except for - `Exception`\ s. - :param Optional[bool] eq: If ``True`` or ``None`` (default), add ``__eq__`` - and ``__ne__`` methods that check two instances for equality. - - They compare the instances as if they were tuples of their ``attrs`` - attributes if and only if the types of both classes are *identical*! - :param Optional[bool] order: If ``True``, add ``__lt__``, ``__le__``, - ``__gt__``, and ``__ge__`` methods that behave like *eq* above and - allow instances to be ordered. If ``None`` (default) mirror value of - *eq*. - :param Optional[bool] cmp: Setting *cmp* is equivalent to setting *eq* - and *order* to the same value. Must not be mixed with *eq* or *order*. - :param Optional[bool] hash: If ``None`` (default), the ``__hash__`` method - is generated according how *eq* and *frozen* are set. - - 1. If *both* are True, ``attrs`` will generate a ``__hash__`` for you. - 2. If *eq* is True and *frozen* is False, ``__hash__`` will be set to - None, marking it unhashable (which it is). - 3. If *eq* is False, ``__hash__`` will be left untouched meaning the - ``__hash__`` method of the base class will be used (if base class is - ``object``, this means it will fall back to id-based hashing.). - - Although not recommended, you can decide for yourself and force - ``attrs`` to create one (e.g. if the class is immutable even though you - didn't freeze it programmatically) by passing ``True`` or not. Both of - these cases are rather special and should be used carefully. - - See our documentation on `hashing`, Python's documentation on - `object.__hash__`, and the `GitHub issue that led to the default \ - behavior `_ for more - details. - :param bool init: Create a ``__init__`` method that initializes the - ``attrs`` attributes. Leading underscores are stripped for the argument - name. If a ``__attrs_pre_init__`` method exists on the class, it will - be called before the class is initialized. If a ``__attrs_post_init__`` - method exists on the class, it will be called after the class is fully - initialized. - - If ``init`` is ``False``, an ``__attrs_init__`` method will be - injected instead. This allows you to define a custom ``__init__`` - method that can do pre-init work such as ``super().__init__()``, - and then call ``__attrs_init__()`` and ``__attrs_post_init__()``. - :param bool slots: Create a `slotted class ` that's more - memory-efficient. Slotted classes are generally superior to the default - dict classes, but have some gotchas you should know about, so we - encourage you to read the `glossary entry `. - :param bool frozen: Make instances immutable after initialization. If - someone attempts to modify a frozen instance, - `attr.exceptions.FrozenInstanceError` is raised. - - .. note:: - - 1. This is achieved by installing a custom ``__setattr__`` method - on your class, so you can't implement your own. - - 2. True immutability is impossible in Python. - - 3. This *does* have a minor a runtime performance `impact - ` when initializing new instances. In other words: - ``__init__`` is slightly slower with ``frozen=True``. - - 4. If a class is frozen, you cannot modify ``self`` in - ``__attrs_post_init__`` or a self-written ``__init__``. You can - circumvent that limitation by using - ``object.__setattr__(self, "attribute_name", value)``. - - 5. Subclasses of a frozen class are frozen too. - - :param bool weakref_slot: Make instances weak-referenceable. This has no - effect unless ``slots`` is also enabled. - :param bool auto_attribs: If ``True``, collect :pep:`526`-annotated - attributes (Python 3.6 and later only) from the class body. - - In this case, you **must** annotate every field. If ``attrs`` - encounters a field that is set to an `attr.ib` but lacks a type - annotation, an `attr.exceptions.UnannotatedAttributeError` is - raised. Use ``field_name: typing.Any = attr.ib(...)`` if you don't - want to set a type. - - If you assign a value to those attributes (e.g. ``x: int = 42``), that - value becomes the default value like if it were passed using - ``attr.ib(default=42)``. Passing an instance of `attrs.Factory` also - works as expected in most cases (see warning below). - - Attributes annotated as `typing.ClassVar`, and attributes that are - neither annotated nor set to an `attr.ib` are **ignored**. - - .. warning:: - For features that use the attribute name to create decorators (e.g. - `validators `), you still *must* assign `attr.ib` to - them. Otherwise Python will either not find the name or try to use - the default value to call e.g. ``validator`` on it. - - These errors can be quite confusing and probably the most common bug - report on our bug tracker. - - :param bool kw_only: Make all attributes keyword-only (Python 3+) - in the generated ``__init__`` (if ``init`` is ``False``, this - parameter is ignored). - :param bool cache_hash: Ensure that the object's hash code is computed - only once and stored on the object. If this is set to ``True``, - hashing must be either explicitly or implicitly enabled for this - class. If the hash code is cached, avoid any reassignments of - fields involved in hash code computation or mutations of the objects - those fields point to after object creation. If such changes occur, - the behavior of the object's hash code is undefined. - :param bool auto_exc: If the class subclasses `BaseException` - (which implicitly includes any subclass of any exception), the - following happens to behave like a well-behaved Python exceptions - class: - - - the values for *eq*, *order*, and *hash* are ignored and the - instances compare and hash by the instance's ids (N.B. ``attrs`` will - *not* remove existing implementations of ``__hash__`` or the equality - methods. It just won't add own ones.), - - all attributes that are either passed into ``__init__`` or have a - default value are additionally available as a tuple in the ``args`` - attribute, - - the value of *str* is ignored leaving ``__str__`` to base classes. - :param bool collect_by_mro: Setting this to `True` fixes the way ``attrs`` - collects attributes from base classes. The default behavior is - incorrect in certain cases of multiple inheritance. It should be on by - default but is kept off for backward-compatibility. - - See issue `#428 `_ for - more details. - - :param Optional[bool] getstate_setstate: - .. note:: - This is usually only interesting for slotted classes and you should - probably just set *auto_detect* to `True`. - - If `True`, ``__getstate__`` and - ``__setstate__`` are generated and attached to the class. This is - necessary for slotted classes to be pickleable. If left `None`, it's - `True` by default for slotted classes and ``False`` for dict classes. - - If *auto_detect* is `True`, and *getstate_setstate* is left `None`, - and **either** ``__getstate__`` or ``__setstate__`` is detected directly - on the class (i.e. not inherited), it is set to `False` (this is usually - what you want). - - :param on_setattr: A callable that is run whenever the user attempts to set - an attribute (either by assignment like ``i.x = 42`` or by using - `setattr` like ``setattr(i, "x", 42)``). It receives the same arguments - as validators: the instance, the attribute that is being modified, and - the new value. - - If no exception is raised, the attribute is set to the return value of - the callable. - - If a list of callables is passed, they're automatically wrapped in an - `attrs.setters.pipe`. - :type on_setattr: `callable`, or a list of callables, or `None`, or - `attrs.setters.NO_OP` - - :param Optional[callable] field_transformer: - A function that is called with the original class object and all - fields right before ``attrs`` finalizes the class. You can use - this, e.g., to automatically add converters or validators to - fields based on their types. See `transform-fields` for more details. - - :param bool match_args: - If `True` (default), set ``__match_args__`` on the class to support - :pep:`634` (Structural Pattern Matching). It is a tuple of all - non-keyword-only ``__init__`` parameter names on Python 3.10 and later. - Ignored on older Python versions. - - .. versionadded:: 16.0.0 *slots* - .. versionadded:: 16.1.0 *frozen* - .. versionadded:: 16.3.0 *str* - .. versionadded:: 16.3.0 Support for ``__attrs_post_init__``. - .. versionchanged:: 17.1.0 - *hash* supports ``None`` as value which is also the default now. - .. versionadded:: 17.3.0 *auto_attribs* - .. versionchanged:: 18.1.0 - If *these* is passed, no attributes are deleted from the class body. - .. versionchanged:: 18.1.0 If *these* is ordered, the order is retained. - .. versionadded:: 18.2.0 *weakref_slot* - .. deprecated:: 18.2.0 - ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` now raise a - `DeprecationWarning` if the classes compared are subclasses of - each other. ``__eq`` and ``__ne__`` never tried to compared subclasses - to each other. - .. versionchanged:: 19.2.0 - ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` now do not consider - subclasses comparable anymore. - .. versionadded:: 18.2.0 *kw_only* - .. versionadded:: 18.2.0 *cache_hash* - .. versionadded:: 19.1.0 *auto_exc* - .. deprecated:: 19.2.0 *cmp* Removal on or after 2021-06-01. - .. versionadded:: 19.2.0 *eq* and *order* - .. versionadded:: 20.1.0 *auto_detect* - .. versionadded:: 20.1.0 *collect_by_mro* - .. versionadded:: 20.1.0 *getstate_setstate* - .. versionadded:: 20.1.0 *on_setattr* - .. versionadded:: 20.3.0 *field_transformer* - .. versionchanged:: 21.1.0 - ``init=False`` injects ``__attrs_init__`` - .. versionchanged:: 21.1.0 Support for ``__attrs_pre_init__`` - .. versionchanged:: 21.1.0 *cmp* undeprecated - .. versionadded:: 21.3.0 *match_args* - """ - eq_, order_ = _determine_attrs_eq_order(cmp, eq, order, None) - hash_ = hash # work around the lack of nonlocal - - if isinstance(on_setattr, (list, tuple)): - on_setattr = setters.pipe(*on_setattr) - - def wrap(cls): - is_frozen = frozen or _has_frozen_base_class(cls) - is_exc = auto_exc is True and issubclass(cls, BaseException) - has_own_setattr = auto_detect and _has_own_attribute( - cls, "__setattr__" - ) - - if has_own_setattr and is_frozen: - raise ValueError("Can't freeze a class with a custom __setattr__.") - - builder = _ClassBuilder( - cls, - these, - slots, - is_frozen, - weakref_slot, - _determine_whether_to_implement( - cls, - getstate_setstate, - auto_detect, - ("__getstate__", "__setstate__"), - default=slots, - ), - auto_attribs, - kw_only, - cache_hash, - is_exc, - collect_by_mro, - on_setattr, - has_own_setattr, - field_transformer, - ) - if _determine_whether_to_implement( - cls, repr, auto_detect, ("__repr__",) - ): - builder.add_repr(repr_ns) - if str is True: - builder.add_str() - - eq = _determine_whether_to_implement( - cls, eq_, auto_detect, ("__eq__", "__ne__") - ) - if not is_exc and eq is True: - builder.add_eq() - if not is_exc and _determine_whether_to_implement( - cls, order_, auto_detect, ("__lt__", "__le__", "__gt__", "__ge__") - ): - builder.add_order() - - builder.add_setattr() - - if ( - hash_ is None - and auto_detect is True - and _has_own_attribute(cls, "__hash__") - ): - hash = False - else: - hash = hash_ - if hash is not True and hash is not False and hash is not None: - # Can't use `hash in` because 1 == True for example. - raise TypeError( - "Invalid value for hash. Must be True, False, or None." - ) - elif hash is False or (hash is None and eq is False) or is_exc: - # Don't do anything. Should fall back to __object__'s __hash__ - # which is by id. - if cache_hash: - raise TypeError( - "Invalid value for cache_hash. To use hash caching," - " hashing must be either explicitly or implicitly " - "enabled." - ) - elif hash is True or ( - hash is None and eq is True and is_frozen is True - ): - # Build a __hash__ if told so, or if it's safe. - builder.add_hash() - else: - # Raise TypeError on attempts to hash. - if cache_hash: - raise TypeError( - "Invalid value for cache_hash. To use hash caching," - " hashing must be either explicitly or implicitly " - "enabled." - ) - builder.make_unhashable() - - if _determine_whether_to_implement( - cls, init, auto_detect, ("__init__",) - ): - builder.add_init() - else: - builder.add_attrs_init() - if cache_hash: - raise TypeError( - "Invalid value for cache_hash. To use hash caching," - " init must be True." - ) - - if ( - PY310 - and match_args - and not _has_own_attribute(cls, "__match_args__") - ): - builder.add_match_args() - - return builder.build_class() - - # maybe_cls's type depends on the usage of the decorator. It's a class - # if it's used as `@attrs` but ``None`` if used as `@attrs()`. - if maybe_cls is None: - return wrap - else: - return wrap(maybe_cls) - - -_attrs = attrs -""" -Internal alias so we can use it in functions that take an argument called -*attrs*. -""" - - -def _has_frozen_base_class(cls): - """ - Check whether *cls* has a frozen ancestor by looking at its - __setattr__. - """ - return cls.__setattr__ is _frozen_setattrs - - -def _generate_unique_filename(cls, func_name): - """ - Create a "filename" suitable for a function being generated. - """ - unique_filename = "".format( - func_name, - cls.__module__, - getattr(cls, "__qualname__", cls.__name__), - ) - return unique_filename - - -def _make_hash(cls, attrs, frozen, cache_hash): - attrs = tuple( - a for a in attrs if a.hash is True or (a.hash is None and a.eq is True) - ) - - tab = " " - - unique_filename = _generate_unique_filename(cls, "hash") - type_hash = hash(unique_filename) - # If eq is custom generated, we need to include the functions in globs - globs = {} - - hash_def = "def __hash__(self" - hash_func = "hash((" - closing_braces = "))" - if not cache_hash: - hash_def += "):" - else: - hash_def += ", *" - - hash_def += ( - ", _cache_wrapper=" - + "__import__('attr._make')._make._CacheHashWrapper):" - ) - hash_func = "_cache_wrapper(" + hash_func - closing_braces += ")" - - method_lines = [hash_def] - - def append_hash_computation_lines(prefix, indent): - """ - Generate the code for actually computing the hash code. - Below this will either be returned directly or used to compute - a value which is then cached, depending on the value of cache_hash - """ - - method_lines.extend( - [ - indent + prefix + hash_func, - indent + " %d," % (type_hash,), - ] - ) - - for a in attrs: - if a.eq_key: - cmp_name = "_%s_key" % (a.name,) - globs[cmp_name] = a.eq_key - method_lines.append( - indent + " %s(self.%s)," % (cmp_name, a.name) - ) - else: - method_lines.append(indent + " self.%s," % a.name) - - method_lines.append(indent + " " + closing_braces) - - if cache_hash: - method_lines.append(tab + "if self.%s is None:" % _hash_cache_field) - if frozen: - append_hash_computation_lines( - "object.__setattr__(self, '%s', " % _hash_cache_field, tab * 2 - ) - method_lines.append(tab * 2 + ")") # close __setattr__ - else: - append_hash_computation_lines( - "self.%s = " % _hash_cache_field, tab * 2 - ) - method_lines.append(tab + "return self.%s" % _hash_cache_field) - else: - append_hash_computation_lines("return ", tab) - - script = "\n".join(method_lines) - return _make_method("__hash__", script, unique_filename, globs) - - -def _add_hash(cls, attrs): - """ - Add a hash method to *cls*. - """ - cls.__hash__ = _make_hash(cls, attrs, frozen=False, cache_hash=False) - return cls - - -def _make_ne(): - """ - Create __ne__ method. - """ - - def __ne__(self, other): - """ - Check equality and either forward a NotImplemented or - return the result negated. - """ - result = self.__eq__(other) - if result is NotImplemented: - return NotImplemented - - return not result - - return __ne__ - - -def _make_eq(cls, attrs): - """ - Create __eq__ method for *cls* with *attrs*. - """ - attrs = [a for a in attrs if a.eq] - - unique_filename = _generate_unique_filename(cls, "eq") - lines = [ - "def __eq__(self, other):", - " if other.__class__ is not self.__class__:", - " return NotImplemented", - ] - - # We can't just do a big self.x = other.x and... clause due to - # irregularities like nan == nan is false but (nan,) == (nan,) is true. - globs = {} - if attrs: - lines.append(" return (") - others = [" ) == ("] - for a in attrs: - if a.eq_key: - cmp_name = "_%s_key" % (a.name,) - # Add the key function to the global namespace - # of the evaluated function. - globs[cmp_name] = a.eq_key - lines.append( - " %s(self.%s)," - % ( - cmp_name, - a.name, - ) - ) - others.append( - " %s(other.%s)," - % ( - cmp_name, - a.name, - ) - ) - else: - lines.append(" self.%s," % (a.name,)) - others.append(" other.%s," % (a.name,)) - - lines += others + [" )"] - else: - lines.append(" return True") - - script = "\n".join(lines) - - return _make_method("__eq__", script, unique_filename, globs) - - -def _make_order(cls, attrs): - """ - Create ordering methods for *cls* with *attrs*. - """ - attrs = [a for a in attrs if a.order] - - def attrs_to_tuple(obj): - """ - Save us some typing. - """ - return tuple( - key(value) if key else value - for value, key in ( - (getattr(obj, a.name), a.order_key) for a in attrs - ) - ) - - def __lt__(self, other): - """ - Automatically created by attrs. - """ - if other.__class__ is self.__class__: - return attrs_to_tuple(self) < attrs_to_tuple(other) - - return NotImplemented - - def __le__(self, other): - """ - Automatically created by attrs. - """ - if other.__class__ is self.__class__: - return attrs_to_tuple(self) <= attrs_to_tuple(other) - - return NotImplemented - - def __gt__(self, other): - """ - Automatically created by attrs. - """ - if other.__class__ is self.__class__: - return attrs_to_tuple(self) > attrs_to_tuple(other) - - return NotImplemented - - def __ge__(self, other): - """ - Automatically created by attrs. - """ - if other.__class__ is self.__class__: - return attrs_to_tuple(self) >= attrs_to_tuple(other) - - return NotImplemented - - return __lt__, __le__, __gt__, __ge__ - - -def _add_eq(cls, attrs=None): - """ - Add equality methods to *cls* with *attrs*. - """ - if attrs is None: - attrs = cls.__attrs_attrs__ - - cls.__eq__ = _make_eq(cls, attrs) - cls.__ne__ = _make_ne() - - return cls - - -if HAS_F_STRINGS: - - def _make_repr(attrs, ns, cls): - unique_filename = _generate_unique_filename(cls, "repr") - # Figure out which attributes to include, and which function to use to - # format them. The a.repr value can be either bool or a custom - # callable. - attr_names_with_reprs = tuple( - (a.name, (repr if a.repr is True else a.repr), a.init) - for a in attrs - if a.repr is not False - ) - globs = { - name + "_repr": r - for name, r, _ in attr_names_with_reprs - if r != repr - } - globs["_compat"] = _compat - globs["AttributeError"] = AttributeError - globs["NOTHING"] = NOTHING - attribute_fragments = [] - for name, r, i in attr_names_with_reprs: - accessor = ( - "self." + name - if i - else 'getattr(self, "' + name + '", NOTHING)' - ) - fragment = ( - "%s={%s!r}" % (name, accessor) - if r == repr - else "%s={%s_repr(%s)}" % (name, name, accessor) - ) - attribute_fragments.append(fragment) - repr_fragment = ", ".join(attribute_fragments) - - if ns is None: - cls_name_fragment = ( - '{self.__class__.__qualname__.rsplit(">.", 1)[-1]}' - ) - else: - cls_name_fragment = ns + ".{self.__class__.__name__}" - - lines = [ - "def __repr__(self):", - " try:", - " already_repring = _compat.repr_context.already_repring", - " except AttributeError:", - " already_repring = {id(self),}", - " _compat.repr_context.already_repring = already_repring", - " else:", - " if id(self) in already_repring:", - " return '...'", - " else:", - " already_repring.add(id(self))", - " try:", - " return f'%s(%s)'" % (cls_name_fragment, repr_fragment), - " finally:", - " already_repring.remove(id(self))", - ] - - return _make_method( - "__repr__", "\n".join(lines), unique_filename, globs=globs - ) - -else: - - def _make_repr(attrs, ns, _): - """ - Make a repr method that includes relevant *attrs*, adding *ns* to the - full name. - """ - - # Figure out which attributes to include, and which function to use to - # format them. The a.repr value can be either bool or a custom - # callable. - attr_names_with_reprs = tuple( - (a.name, repr if a.repr is True else a.repr) - for a in attrs - if a.repr is not False - ) - - def __repr__(self): - """ - Automatically created by attrs. - """ - try: - already_repring = _compat.repr_context.already_repring - except AttributeError: - already_repring = set() - _compat.repr_context.already_repring = already_repring - - if id(self) in already_repring: - return "..." - real_cls = self.__class__ - if ns is None: - class_name = real_cls.__qualname__.rsplit(">.", 1)[-1] - else: - class_name = ns + "." + real_cls.__name__ - - # Since 'self' remains on the stack (i.e.: strongly referenced) - # for the duration of this call, it's safe to depend on id(...) - # stability, and not need to track the instance and therefore - # worry about properties like weakref- or hash-ability. - already_repring.add(id(self)) - try: - result = [class_name, "("] - first = True - for name, attr_repr in attr_names_with_reprs: - if first: - first = False - else: - result.append(", ") - result.extend( - (name, "=", attr_repr(getattr(self, name, NOTHING))) - ) - return "".join(result) + ")" - finally: - already_repring.remove(id(self)) - - return __repr__ - - -def _add_repr(cls, ns=None, attrs=None): - """ - Add a repr method to *cls*. - """ - if attrs is None: - attrs = cls.__attrs_attrs__ - - cls.__repr__ = _make_repr(attrs, ns, cls) - return cls - - -def fields(cls): - """ - Return the tuple of ``attrs`` attributes for a class. - - The tuple also allows accessing the fields by their names (see below for - examples). - - :param type cls: Class to introspect. - - :raise TypeError: If *cls* is not a class. - :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` - class. - - :rtype: tuple (with name accessors) of `attrs.Attribute` - - .. versionchanged:: 16.2.0 Returned tuple allows accessing the fields - by name. - """ - if not isinstance(cls, type): - raise TypeError("Passed object must be a class.") - attrs = getattr(cls, "__attrs_attrs__", None) - if attrs is None: - raise NotAnAttrsClassError( - "{cls!r} is not an attrs-decorated class.".format(cls=cls) - ) - return attrs - - -def fields_dict(cls): - """ - Return an ordered dictionary of ``attrs`` attributes for a class, whose - keys are the attribute names. - - :param type cls: Class to introspect. - - :raise TypeError: If *cls* is not a class. - :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` - class. - - :rtype: an ordered dict where keys are attribute names and values are - `attrs.Attribute`\\ s. This will be a `dict` if it's - naturally ordered like on Python 3.6+ or an - :class:`~collections.OrderedDict` otherwise. - - .. versionadded:: 18.1.0 - """ - if not isinstance(cls, type): - raise TypeError("Passed object must be a class.") - attrs = getattr(cls, "__attrs_attrs__", None) - if attrs is None: - raise NotAnAttrsClassError( - "{cls!r} is not an attrs-decorated class.".format(cls=cls) - ) - return ordered_dict((a.name, a) for a in attrs) - - -def validate(inst): - """ - Validate all attributes on *inst* that have a validator. - - Leaves all exceptions through. - - :param inst: Instance of a class with ``attrs`` attributes. - """ - if _config._run_validators is False: - return - - for a in fields(inst.__class__): - v = a.validator - if v is not None: - v(inst, a, getattr(inst, a.name)) - - -def _is_slot_cls(cls): - return "__slots__" in cls.__dict__ - - -def _is_slot_attr(a_name, base_attr_map): - """ - Check if the attribute name comes from a slot class. - """ - return a_name in base_attr_map and _is_slot_cls(base_attr_map[a_name]) - - -def _make_init( - cls, - attrs, - pre_init, - post_init, - frozen, - slots, - cache_hash, - base_attr_map, - is_exc, - cls_on_setattr, - attrs_init, -): - has_cls_on_setattr = ( - cls_on_setattr is not None and cls_on_setattr is not setters.NO_OP - ) - - if frozen and has_cls_on_setattr: - raise ValueError("Frozen classes can't use on_setattr.") - - needs_cached_setattr = cache_hash or frozen - filtered_attrs = [] - attr_dict = {} - for a in attrs: - if not a.init and a.default is NOTHING: - continue - - filtered_attrs.append(a) - attr_dict[a.name] = a - - if a.on_setattr is not None: - if frozen is True: - raise ValueError("Frozen classes can't use on_setattr.") - - needs_cached_setattr = True - elif has_cls_on_setattr and a.on_setattr is not setters.NO_OP: - needs_cached_setattr = True - - unique_filename = _generate_unique_filename(cls, "init") - - script, globs, annotations = _attrs_to_init_script( - filtered_attrs, - frozen, - slots, - pre_init, - post_init, - cache_hash, - base_attr_map, - is_exc, - has_cls_on_setattr, - attrs_init, - ) - if cls.__module__ in sys.modules: - # This makes typing.get_type_hints(CLS.__init__) resolve string types. - globs.update(sys.modules[cls.__module__].__dict__) - - globs.update({"NOTHING": NOTHING, "attr_dict": attr_dict}) - - if needs_cached_setattr: - # Save the lookup overhead in __init__ if we need to circumvent - # setattr hooks. - globs["_setattr"] = _obj_setattr - - init = _make_method( - "__attrs_init__" if attrs_init else "__init__", - script, - unique_filename, - globs, - ) - init.__annotations__ = annotations - - return init - - -def _setattr(attr_name, value_var, has_on_setattr): - """ - Use the cached object.setattr to set *attr_name* to *value_var*. - """ - return "_setattr(self, '%s', %s)" % (attr_name, value_var) - - -def _setattr_with_converter(attr_name, value_var, has_on_setattr): - """ - Use the cached object.setattr to set *attr_name* to *value_var*, but run - its converter first. - """ - return "_setattr(self, '%s', %s(%s))" % ( - attr_name, - _init_converter_pat % (attr_name,), - value_var, - ) - - -def _assign(attr_name, value, has_on_setattr): - """ - Unless *attr_name* has an on_setattr hook, use normal assignment. Otherwise - relegate to _setattr. - """ - if has_on_setattr: - return _setattr(attr_name, value, True) - - return "self.%s = %s" % (attr_name, value) - - -def _assign_with_converter(attr_name, value_var, has_on_setattr): - """ - Unless *attr_name* has an on_setattr hook, use normal assignment after - conversion. Otherwise relegate to _setattr_with_converter. - """ - if has_on_setattr: - return _setattr_with_converter(attr_name, value_var, True) - - return "self.%s = %s(%s)" % ( - attr_name, - _init_converter_pat % (attr_name,), - value_var, - ) - - -def _attrs_to_init_script( - attrs, - frozen, - slots, - pre_init, - post_init, - cache_hash, - base_attr_map, - is_exc, - has_cls_on_setattr, - attrs_init, -): - """ - Return a script of an initializer for *attrs* and a dict of globals. - - The globals are expected by the generated script. - - If *frozen* is True, we cannot set the attributes directly so we use - a cached ``object.__setattr__``. - """ - lines = [] - if pre_init: - lines.append("self.__attrs_pre_init__()") - - if frozen is True: - if slots is True: - fmt_setter = _setattr - fmt_setter_with_converter = _setattr_with_converter - else: - # Dict frozen classes assign directly to __dict__. - # But only if the attribute doesn't come from an ancestor slot - # class. - # Note _inst_dict will be used again below if cache_hash is True - lines.append("_inst_dict = self.__dict__") - - def fmt_setter(attr_name, value_var, has_on_setattr): - if _is_slot_attr(attr_name, base_attr_map): - return _setattr(attr_name, value_var, has_on_setattr) - - return "_inst_dict['%s'] = %s" % (attr_name, value_var) - - def fmt_setter_with_converter( - attr_name, value_var, has_on_setattr - ): - if has_on_setattr or _is_slot_attr(attr_name, base_attr_map): - return _setattr_with_converter( - attr_name, value_var, has_on_setattr - ) - - return "_inst_dict['%s'] = %s(%s)" % ( - attr_name, - _init_converter_pat % (attr_name,), - value_var, - ) - - else: - # Not frozen. - fmt_setter = _assign - fmt_setter_with_converter = _assign_with_converter - - args = [] - kw_only_args = [] - attrs_to_validate = [] - - # This is a dictionary of names to validator and converter callables. - # Injecting this into __init__ globals lets us avoid lookups. - names_for_globals = {} - annotations = {"return": None} - - for a in attrs: - if a.validator: - attrs_to_validate.append(a) - - attr_name = a.name - has_on_setattr = a.on_setattr is not None or ( - a.on_setattr is not setters.NO_OP and has_cls_on_setattr - ) - arg_name = a.name.lstrip("_") - - has_factory = isinstance(a.default, Factory) - if has_factory and a.default.takes_self: - maybe_self = "self" - else: - maybe_self = "" - - if a.init is False: - if has_factory: - init_factory_name = _init_factory_pat.format(a.name) - if a.converter is not None: - lines.append( - fmt_setter_with_converter( - attr_name, - init_factory_name + "(%s)" % (maybe_self,), - has_on_setattr, - ) - ) - conv_name = _init_converter_pat % (a.name,) - names_for_globals[conv_name] = a.converter - else: - lines.append( - fmt_setter( - attr_name, - init_factory_name + "(%s)" % (maybe_self,), - has_on_setattr, - ) - ) - names_for_globals[init_factory_name] = a.default.factory - else: - if a.converter is not None: - lines.append( - fmt_setter_with_converter( - attr_name, - "attr_dict['%s'].default" % (attr_name,), - has_on_setattr, - ) - ) - conv_name = _init_converter_pat % (a.name,) - names_for_globals[conv_name] = a.converter - else: - lines.append( - fmt_setter( - attr_name, - "attr_dict['%s'].default" % (attr_name,), - has_on_setattr, - ) - ) - elif a.default is not NOTHING and not has_factory: - arg = "%s=attr_dict['%s'].default" % (arg_name, attr_name) - if a.kw_only: - kw_only_args.append(arg) - else: - args.append(arg) - - if a.converter is not None: - lines.append( - fmt_setter_with_converter( - attr_name, arg_name, has_on_setattr - ) - ) - names_for_globals[ - _init_converter_pat % (a.name,) - ] = a.converter - else: - lines.append(fmt_setter(attr_name, arg_name, has_on_setattr)) - - elif has_factory: - arg = "%s=NOTHING" % (arg_name,) - if a.kw_only: - kw_only_args.append(arg) - else: - args.append(arg) - lines.append("if %s is not NOTHING:" % (arg_name,)) - - init_factory_name = _init_factory_pat.format(a.name) - if a.converter is not None: - lines.append( - " " - + fmt_setter_with_converter( - attr_name, arg_name, has_on_setattr - ) - ) - lines.append("else:") - lines.append( - " " - + fmt_setter_with_converter( - attr_name, - init_factory_name + "(" + maybe_self + ")", - has_on_setattr, - ) - ) - names_for_globals[ - _init_converter_pat % (a.name,) - ] = a.converter - else: - lines.append( - " " + fmt_setter(attr_name, arg_name, has_on_setattr) - ) - lines.append("else:") - lines.append( - " " - + fmt_setter( - attr_name, - init_factory_name + "(" + maybe_self + ")", - has_on_setattr, - ) - ) - names_for_globals[init_factory_name] = a.default.factory - else: - if a.kw_only: - kw_only_args.append(arg_name) - else: - args.append(arg_name) - - if a.converter is not None: - lines.append( - fmt_setter_with_converter( - attr_name, arg_name, has_on_setattr - ) - ) - names_for_globals[ - _init_converter_pat % (a.name,) - ] = a.converter - else: - lines.append(fmt_setter(attr_name, arg_name, has_on_setattr)) - - if a.init is True: - if a.type is not None and a.converter is None: - annotations[arg_name] = a.type - elif a.converter is not None: - # Try to get the type from the converter. - t = _AnnotationExtractor(a.converter).get_first_param_type() - if t: - annotations[arg_name] = t - - if attrs_to_validate: # we can skip this if there are no validators. - names_for_globals["_config"] = _config - lines.append("if _config._run_validators is True:") - for a in attrs_to_validate: - val_name = "__attr_validator_" + a.name - attr_name = "__attr_" + a.name - lines.append( - " %s(self, %s, self.%s)" % (val_name, attr_name, a.name) - ) - names_for_globals[val_name] = a.validator - names_for_globals[attr_name] = a - - if post_init: - lines.append("self.__attrs_post_init__()") - - # because this is set only after __attrs_post_init__ is called, a crash - # will result if post-init tries to access the hash code. This seemed - # preferable to setting this beforehand, in which case alteration to - # field values during post-init combined with post-init accessing the - # hash code would result in silent bugs. - if cache_hash: - if frozen: - if slots: - # if frozen and slots, then _setattr defined above - init_hash_cache = "_setattr(self, '%s', %s)" - else: - # if frozen and not slots, then _inst_dict defined above - init_hash_cache = "_inst_dict['%s'] = %s" - else: - init_hash_cache = "self.%s = %s" - lines.append(init_hash_cache % (_hash_cache_field, "None")) - - # For exceptions we rely on BaseException.__init__ for proper - # initialization. - if is_exc: - vals = ",".join("self." + a.name for a in attrs if a.init) - - lines.append("BaseException.__init__(self, %s)" % (vals,)) - - args = ", ".join(args) - if kw_only_args: - args += "%s*, %s" % ( - ", " if args else "", # leading comma - ", ".join(kw_only_args), # kw_only args - ) - return ( - """\ -def {init_name}(self, {args}): - {lines} -""".format( - init_name=("__attrs_init__" if attrs_init else "__init__"), - args=args, - lines="\n ".join(lines) if lines else "pass", - ), - names_for_globals, - annotations, - ) - - -class Attribute: - """ - *Read-only* representation of an attribute. - - The class has *all* arguments of `attr.ib` (except for ``factory`` - which is only syntactic sugar for ``default=Factory(...)`` plus the - following: - - - ``name`` (`str`): The name of the attribute. - - ``inherited`` (`bool`): Whether or not that attribute has been inherited - from a base class. - - ``eq_key`` and ``order_key`` (`typing.Callable` or `None`): The callables - that are used for comparing and ordering objects by this attribute, - respectively. These are set by passing a callable to `attr.ib`'s ``eq``, - ``order``, or ``cmp`` arguments. See also :ref:`comparison customization - `. - - Instances of this class are frequently used for introspection purposes - like: - - - `fields` returns a tuple of them. - - Validators get them passed as the first argument. - - The :ref:`field transformer ` hook receives a list of - them. - - .. versionadded:: 20.1.0 *inherited* - .. versionadded:: 20.1.0 *on_setattr* - .. versionchanged:: 20.2.0 *inherited* is not taken into account for - equality checks and hashing anymore. - .. versionadded:: 21.1.0 *eq_key* and *order_key* - - For the full version history of the fields, see `attr.ib`. - """ - - __slots__ = ( - "name", - "default", - "validator", - "repr", - "eq", - "eq_key", - "order", - "order_key", - "hash", - "init", - "metadata", - "type", - "converter", - "kw_only", - "inherited", - "on_setattr", - ) - - def __init__( - self, - name, - default, - validator, - repr, - cmp, # XXX: unused, remove along with other cmp code. - hash, - init, - inherited, - metadata=None, - type=None, - converter=None, - kw_only=False, - eq=None, - eq_key=None, - order=None, - order_key=None, - on_setattr=None, - ): - eq, eq_key, order, order_key = _determine_attrib_eq_order( - cmp, eq_key or eq, order_key or order, True - ) - - # Cache this descriptor here to speed things up later. - bound_setattr = _obj_setattr.__get__(self, Attribute) - - # Despite the big red warning, people *do* instantiate `Attribute` - # themselves. - bound_setattr("name", name) - bound_setattr("default", default) - bound_setattr("validator", validator) - bound_setattr("repr", repr) - bound_setattr("eq", eq) - bound_setattr("eq_key", eq_key) - bound_setattr("order", order) - bound_setattr("order_key", order_key) - bound_setattr("hash", hash) - bound_setattr("init", init) - bound_setattr("converter", converter) - bound_setattr( - "metadata", - ( - types.MappingProxyType(dict(metadata)) # Shallow copy - if metadata - else _empty_metadata_singleton - ), - ) - bound_setattr("type", type) - bound_setattr("kw_only", kw_only) - bound_setattr("inherited", inherited) - bound_setattr("on_setattr", on_setattr) - - def __setattr__(self, name, value): - raise FrozenInstanceError() - - @classmethod - def from_counting_attr(cls, name, ca, type=None): - # type holds the annotated value. deal with conflicts: - if type is None: - type = ca.type - elif ca.type is not None: - raise ValueError( - "Type annotation and type argument cannot both be present" - ) - inst_dict = { - k: getattr(ca, k) - for k in Attribute.__slots__ - if k - not in ( - "name", - "validator", - "default", - "type", - "inherited", - ) # exclude methods and deprecated alias - } - return cls( - name=name, - validator=ca._validator, - default=ca._default, - type=type, - cmp=None, - inherited=False, - **inst_dict - ) - - # Don't use attr.evolve since fields(Attribute) doesn't work - def evolve(self, **changes): - """ - Copy *self* and apply *changes*. - - This works similarly to `attr.evolve` but that function does not work - with ``Attribute``. - - It is mainly meant to be used for `transform-fields`. - - .. versionadded:: 20.3.0 - """ - new = copy.copy(self) - - new._setattrs(changes.items()) - - return new - - # Don't use _add_pickle since fields(Attribute) doesn't work - def __getstate__(self): - """ - Play nice with pickle. - """ - return tuple( - getattr(self, name) if name != "metadata" else dict(self.metadata) - for name in self.__slots__ - ) - - def __setstate__(self, state): - """ - Play nice with pickle. - """ - self._setattrs(zip(self.__slots__, state)) - - def _setattrs(self, name_values_pairs): - bound_setattr = _obj_setattr.__get__(self, Attribute) - for name, value in name_values_pairs: - if name != "metadata": - bound_setattr(name, value) - else: - bound_setattr( - name, - types.MappingProxyType(dict(value)) - if value - else _empty_metadata_singleton, - ) - - -_a = [ - Attribute( - name=name, - default=NOTHING, - validator=None, - repr=True, - cmp=None, - eq=True, - order=False, - hash=(name != "metadata"), - init=True, - inherited=False, - ) - for name in Attribute.__slots__ -] - -Attribute = _add_hash( - _add_eq( - _add_repr(Attribute, attrs=_a), - attrs=[a for a in _a if a.name != "inherited"], - ), - attrs=[a for a in _a if a.hash and a.name != "inherited"], -) - - -class _CountingAttr: - """ - Intermediate representation of attributes that uses a counter to preserve - the order in which the attributes have been defined. - - *Internal* data structure of the attrs library. Running into is most - likely the result of a bug like a forgotten `@attr.s` decorator. - """ - - __slots__ = ( - "counter", - "_default", - "repr", - "eq", - "eq_key", - "order", - "order_key", - "hash", - "init", - "metadata", - "_validator", - "converter", - "type", - "kw_only", - "on_setattr", - ) - __attrs_attrs__ = tuple( - Attribute( - name=name, - default=NOTHING, - validator=None, - repr=True, - cmp=None, - hash=True, - init=True, - kw_only=False, - eq=True, - eq_key=None, - order=False, - order_key=None, - inherited=False, - on_setattr=None, - ) - for name in ( - "counter", - "_default", - "repr", - "eq", - "order", - "hash", - "init", - "on_setattr", - ) - ) + ( - Attribute( - name="metadata", - default=None, - validator=None, - repr=True, - cmp=None, - hash=False, - init=True, - kw_only=False, - eq=True, - eq_key=None, - order=False, - order_key=None, - inherited=False, - on_setattr=None, - ), - ) - cls_counter = 0 - - def __init__( - self, - default, - validator, - repr, - cmp, - hash, - init, - converter, - metadata, - type, - kw_only, - eq, - eq_key, - order, - order_key, - on_setattr, - ): - _CountingAttr.cls_counter += 1 - self.counter = _CountingAttr.cls_counter - self._default = default - self._validator = validator - self.converter = converter - self.repr = repr - self.eq = eq - self.eq_key = eq_key - self.order = order - self.order_key = order_key - self.hash = hash - self.init = init - self.metadata = metadata - self.type = type - self.kw_only = kw_only - self.on_setattr = on_setattr - - def validator(self, meth): - """ - Decorator that adds *meth* to the list of validators. - - Returns *meth* unchanged. - - .. versionadded:: 17.1.0 - """ - if self._validator is None: - self._validator = meth - else: - self._validator = and_(self._validator, meth) - return meth - - def default(self, meth): - """ - Decorator that allows to set the default for an attribute. - - Returns *meth* unchanged. - - :raises DefaultAlreadySetError: If default has been set before. - - .. versionadded:: 17.1.0 - """ - if self._default is not NOTHING: - raise DefaultAlreadySetError() - - self._default = Factory(meth, takes_self=True) - - return meth - - -_CountingAttr = _add_eq(_add_repr(_CountingAttr)) - - -class Factory: - """ - Stores a factory callable. - - If passed as the default value to `attrs.field`, the factory is used to - generate a new value. - - :param callable factory: A callable that takes either none or exactly one - mandatory positional argument depending on *takes_self*. - :param bool takes_self: Pass the partially initialized instance that is - being initialized as a positional argument. - - .. versionadded:: 17.1.0 *takes_self* - """ - - __slots__ = ("factory", "takes_self") - - def __init__(self, factory, takes_self=False): - """ - `Factory` is part of the default machinery so if we want a default - value here, we have to implement it ourselves. - """ - self.factory = factory - self.takes_self = takes_self - - def __getstate__(self): - """ - Play nice with pickle. - """ - return tuple(getattr(self, name) for name in self.__slots__) - - def __setstate__(self, state): - """ - Play nice with pickle. - """ - for name, value in zip(self.__slots__, state): - setattr(self, name, value) - - -_f = [ - Attribute( - name=name, - default=NOTHING, - validator=None, - repr=True, - cmp=None, - eq=True, - order=False, - hash=True, - init=True, - inherited=False, - ) - for name in Factory.__slots__ -] - -Factory = _add_hash(_add_eq(_add_repr(Factory, attrs=_f), attrs=_f), attrs=_f) - - -def make_class(name, attrs, bases=(object,), **attributes_arguments): - """ - A quick way to create a new class called *name* with *attrs*. - - :param str name: The name for the new class. - - :param attrs: A list of names or a dictionary of mappings of names to - attributes. - - If *attrs* is a list or an ordered dict (`dict` on Python 3.6+, - `collections.OrderedDict` otherwise), the order is deduced from - the order of the names or attributes inside *attrs*. Otherwise the - order of the definition of the attributes is used. - :type attrs: `list` or `dict` - - :param tuple bases: Classes that the new class will subclass. - - :param attributes_arguments: Passed unmodified to `attr.s`. - - :return: A new class with *attrs*. - :rtype: type - - .. versionadded:: 17.1.0 *bases* - .. versionchanged:: 18.1.0 If *attrs* is ordered, the order is retained. - """ - if isinstance(attrs, dict): - cls_dict = attrs - elif isinstance(attrs, (list, tuple)): - cls_dict = {a: attrib() for a in attrs} - else: - raise TypeError("attrs argument must be a dict or a list.") - - pre_init = cls_dict.pop("__attrs_pre_init__", None) - post_init = cls_dict.pop("__attrs_post_init__", None) - user_init = cls_dict.pop("__init__", None) - - body = {} - if pre_init is not None: - body["__attrs_pre_init__"] = pre_init - if post_init is not None: - body["__attrs_post_init__"] = post_init - if user_init is not None: - body["__init__"] = user_init - - type_ = types.new_class(name, bases, {}, lambda ns: ns.update(body)) - - # For pickling to work, the __module__ variable needs to be set to the - # frame where the class is created. Bypass this step in environments where - # sys._getframe is not defined (Jython for example) or sys._getframe is not - # defined for arguments greater than 0 (IronPython). - try: - type_.__module__ = sys._getframe(1).f_globals.get( - "__name__", "__main__" - ) - except (AttributeError, ValueError): - pass - - # We do it here for proper warnings with meaningful stacklevel. - cmp = attributes_arguments.pop("cmp", None) - ( - attributes_arguments["eq"], - attributes_arguments["order"], - ) = _determine_attrs_eq_order( - cmp, - attributes_arguments.get("eq"), - attributes_arguments.get("order"), - True, - ) - - return _attrs(these=cls_dict, **attributes_arguments)(type_) - - -# These are required by within this module so we define them here and merely -# import into .validators / .converters. - - -@attrs(slots=True, hash=True) -class _AndValidator: - """ - Compose many validators to a single one. - """ - - _validators = attrib() - - def __call__(self, inst, attr, value): - for v in self._validators: - v(inst, attr, value) - - -def and_(*validators): - """ - A validator that composes multiple validators into one. - - When called on a value, it runs all wrapped validators. - - :param callables validators: Arbitrary number of validators. - - .. versionadded:: 17.1.0 - """ - vals = [] - for validator in validators: - vals.extend( - validator._validators - if isinstance(validator, _AndValidator) - else [validator] - ) - - return _AndValidator(tuple(vals)) - - -def pipe(*converters): - """ - A converter that composes multiple converters into one. - - When called on a value, it runs all wrapped converters, returning the - *last* value. - - Type annotations will be inferred from the wrapped converters', if - they have any. - - :param callables converters: Arbitrary number of converters. - - .. versionadded:: 20.1.0 - """ - - def pipe_converter(val): - for converter in converters: - val = converter(val) - - return val - - if not converters: - # If the converter list is empty, pipe_converter is the identity. - A = typing.TypeVar("A") - pipe_converter.__annotations__ = {"val": A, "return": A} - else: - # Get parameter type from first converter. - t = _AnnotationExtractor(converters[0]).get_first_param_type() - if t: - pipe_converter.__annotations__["val"] = t - - # Get return type from last converter. - rt = _AnnotationExtractor(converters[-1]).get_return_type() - if rt: - pipe_converter.__annotations__["return"] = rt - - return pipe_converter diff --git a/.venv/Lib/site-packages/attr/_next_gen.py b/.venv/Lib/site-packages/attr/_next_gen.py deleted file mode 100644 index 5a06a74..0000000 --- a/.venv/Lib/site-packages/attr/_next_gen.py +++ /dev/null @@ -1,220 +0,0 @@ -# SPDX-License-Identifier: MIT - -""" -These are Python 3.6+-only and keyword-only APIs that call `attr.s` and -`attr.ib` with different default values. -""" - - -from functools import partial - -from . import setters -from ._funcs import asdict as _asdict -from ._funcs import astuple as _astuple -from ._make import ( - NOTHING, - _frozen_setattrs, - _ng_default_on_setattr, - attrib, - attrs, -) -from .exceptions import UnannotatedAttributeError - - -def define( - maybe_cls=None, - *, - these=None, - repr=None, - hash=None, - init=None, - slots=True, - frozen=False, - weakref_slot=True, - str=False, - auto_attribs=None, - kw_only=False, - cache_hash=False, - auto_exc=True, - eq=None, - order=False, - auto_detect=True, - getstate_setstate=None, - on_setattr=None, - field_transformer=None, - match_args=True, -): - r""" - Define an ``attrs`` class. - - Differences to the classic `attr.s` that it uses underneath: - - - Automatically detect whether or not *auto_attribs* should be `True` (c.f. - *auto_attribs* parameter). - - If *frozen* is `False`, run converters and validators when setting an - attribute by default. - - *slots=True* - - .. caution:: - - Usually this has only upsides and few visible effects in everyday - programming. But it *can* lead to some suprising behaviors, so please - make sure to read :term:`slotted classes`. - - *auto_exc=True* - - *auto_detect=True* - - *order=False* - - Some options that were only relevant on Python 2 or were kept around for - backwards-compatibility have been removed. - - Please note that these are all defaults and you can change them as you - wish. - - :param Optional[bool] auto_attribs: If set to `True` or `False`, it behaves - exactly like `attr.s`. If left `None`, `attr.s` will try to guess: - - 1. If any attributes are annotated and no unannotated `attrs.fields`\ s - are found, it assumes *auto_attribs=True*. - 2. Otherwise it assumes *auto_attribs=False* and tries to collect - `attrs.fields`\ s. - - For now, please refer to `attr.s` for the rest of the parameters. - - .. versionadded:: 20.1.0 - .. versionchanged:: 21.3.0 Converters are also run ``on_setattr``. - """ - - def do_it(cls, auto_attribs): - return attrs( - maybe_cls=cls, - these=these, - repr=repr, - hash=hash, - init=init, - slots=slots, - frozen=frozen, - weakref_slot=weakref_slot, - str=str, - auto_attribs=auto_attribs, - kw_only=kw_only, - cache_hash=cache_hash, - auto_exc=auto_exc, - eq=eq, - order=order, - auto_detect=auto_detect, - collect_by_mro=True, - getstate_setstate=getstate_setstate, - on_setattr=on_setattr, - field_transformer=field_transformer, - match_args=match_args, - ) - - def wrap(cls): - """ - Making this a wrapper ensures this code runs during class creation. - - We also ensure that frozen-ness of classes is inherited. - """ - nonlocal frozen, on_setattr - - had_on_setattr = on_setattr not in (None, setters.NO_OP) - - # By default, mutable classes convert & validate on setattr. - if frozen is False and on_setattr is None: - on_setattr = _ng_default_on_setattr - - # However, if we subclass a frozen class, we inherit the immutability - # and disable on_setattr. - for base_cls in cls.__bases__: - if base_cls.__setattr__ is _frozen_setattrs: - if had_on_setattr: - raise ValueError( - "Frozen classes can't use on_setattr " - "(frozen-ness was inherited)." - ) - - on_setattr = setters.NO_OP - break - - if auto_attribs is not None: - return do_it(cls, auto_attribs) - - try: - return do_it(cls, True) - except UnannotatedAttributeError: - return do_it(cls, False) - - # maybe_cls's type depends on the usage of the decorator. It's a class - # if it's used as `@attrs` but ``None`` if used as `@attrs()`. - if maybe_cls is None: - return wrap - else: - return wrap(maybe_cls) - - -mutable = define -frozen = partial(define, frozen=True, on_setattr=None) - - -def field( - *, - default=NOTHING, - validator=None, - repr=True, - hash=None, - init=True, - metadata=None, - converter=None, - factory=None, - kw_only=False, - eq=None, - order=None, - on_setattr=None, -): - """ - Identical to `attr.ib`, except keyword-only and with some arguments - removed. - - .. versionadded:: 20.1.0 - """ - return attrib( - default=default, - validator=validator, - repr=repr, - hash=hash, - init=init, - metadata=metadata, - converter=converter, - factory=factory, - kw_only=kw_only, - eq=eq, - order=order, - on_setattr=on_setattr, - ) - - -def asdict(inst, *, recurse=True, filter=None, value_serializer=None): - """ - Same as `attr.asdict`, except that collections types are always retained - and dict is always used as *dict_factory*. - - .. versionadded:: 21.3.0 - """ - return _asdict( - inst=inst, - recurse=recurse, - filter=filter, - value_serializer=value_serializer, - retain_collection_types=True, - ) - - -def astuple(inst, *, recurse=True, filter=None): - """ - Same as `attr.astuple`, except that collections types are always retained - and `tuple` is always used as the *tuple_factory*. - - .. versionadded:: 21.3.0 - """ - return _astuple( - inst=inst, recurse=recurse, filter=filter, retain_collection_types=True - ) diff --git a/.venv/Lib/site-packages/attr/_version_info.py b/.venv/Lib/site-packages/attr/_version_info.py deleted file mode 100644 index 51a1312..0000000 --- a/.venv/Lib/site-packages/attr/_version_info.py +++ /dev/null @@ -1,86 +0,0 @@ -# SPDX-License-Identifier: MIT - - -from functools import total_ordering - -from ._funcs import astuple -from ._make import attrib, attrs - - -@total_ordering -@attrs(eq=False, order=False, slots=True, frozen=True) -class VersionInfo: - """ - A version object that can be compared to tuple of length 1--4: - - >>> attr.VersionInfo(19, 1, 0, "final") <= (19, 2) - True - >>> attr.VersionInfo(19, 1, 0, "final") < (19, 1, 1) - True - >>> vi = attr.VersionInfo(19, 2, 0, "final") - >>> vi < (19, 1, 1) - False - >>> vi < (19,) - False - >>> vi == (19, 2,) - True - >>> vi == (19, 2, 1) - False - - .. versionadded:: 19.2 - """ - - year = attrib(type=int) - minor = attrib(type=int) - micro = attrib(type=int) - releaselevel = attrib(type=str) - - @classmethod - def _from_version_string(cls, s): - """ - Parse *s* and return a _VersionInfo. - """ - v = s.split(".") - if len(v) == 3: - v.append("final") - - return cls( - year=int(v[0]), minor=int(v[1]), micro=int(v[2]), releaselevel=v[3] - ) - - def _ensure_tuple(self, other): - """ - Ensure *other* is a tuple of a valid length. - - Returns a possibly transformed *other* and ourselves as a tuple of - the same length as *other*. - """ - - if self.__class__ is other.__class__: - other = astuple(other) - - if not isinstance(other, tuple): - raise NotImplementedError - - if not (1 <= len(other) <= 4): - raise NotImplementedError - - return astuple(self)[: len(other)], other - - def __eq__(self, other): - try: - us, them = self._ensure_tuple(other) - except NotImplementedError: - return NotImplemented - - return us == them - - def __lt__(self, other): - try: - us, them = self._ensure_tuple(other) - except NotImplementedError: - return NotImplemented - - # Since alphabetically "dev0" < "final" < "post1" < "post2", we don't - # have to do anything special with releaselevel for now. - return us < them diff --git a/.venv/Lib/site-packages/attr/_version_info.pyi b/.venv/Lib/site-packages/attr/_version_info.pyi deleted file mode 100644 index 45ced08..0000000 --- a/.venv/Lib/site-packages/attr/_version_info.pyi +++ /dev/null @@ -1,9 +0,0 @@ -class VersionInfo: - @property - def year(self) -> int: ... - @property - def minor(self) -> int: ... - @property - def micro(self) -> int: ... - @property - def releaselevel(self) -> str: ... diff --git a/.venv/Lib/site-packages/attr/converters.py b/.venv/Lib/site-packages/attr/converters.py deleted file mode 100644 index a73626c..0000000 --- a/.venv/Lib/site-packages/attr/converters.py +++ /dev/null @@ -1,144 +0,0 @@ -# SPDX-License-Identifier: MIT - -""" -Commonly useful converters. -""" - - -import typing - -from ._compat import _AnnotationExtractor -from ._make import NOTHING, Factory, pipe - - -__all__ = [ - "default_if_none", - "optional", - "pipe", - "to_bool", -] - - -def optional(converter): - """ - A converter that allows an attribute to be optional. An optional attribute - is one which can be set to ``None``. - - Type annotations will be inferred from the wrapped converter's, if it - has any. - - :param callable converter: the converter that is used for non-``None`` - values. - - .. versionadded:: 17.1.0 - """ - - def optional_converter(val): - if val is None: - return None - return converter(val) - - xtr = _AnnotationExtractor(converter) - - t = xtr.get_first_param_type() - if t: - optional_converter.__annotations__["val"] = typing.Optional[t] - - rt = xtr.get_return_type() - if rt: - optional_converter.__annotations__["return"] = typing.Optional[rt] - - return optional_converter - - -def default_if_none(default=NOTHING, factory=None): - """ - A converter that allows to replace ``None`` values by *default* or the - result of *factory*. - - :param default: Value to be used if ``None`` is passed. Passing an instance - of `attrs.Factory` is supported, however the ``takes_self`` option - is *not*. - :param callable factory: A callable that takes no parameters whose result - is used if ``None`` is passed. - - :raises TypeError: If **neither** *default* or *factory* is passed. - :raises TypeError: If **both** *default* and *factory* are passed. - :raises ValueError: If an instance of `attrs.Factory` is passed with - ``takes_self=True``. - - .. versionadded:: 18.2.0 - """ - if default is NOTHING and factory is None: - raise TypeError("Must pass either `default` or `factory`.") - - if default is not NOTHING and factory is not None: - raise TypeError( - "Must pass either `default` or `factory` but not both." - ) - - if factory is not None: - default = Factory(factory) - - if isinstance(default, Factory): - if default.takes_self: - raise ValueError( - "`takes_self` is not supported by default_if_none." - ) - - def default_if_none_converter(val): - if val is not None: - return val - - return default.factory() - - else: - - def default_if_none_converter(val): - if val is not None: - return val - - return default - - return default_if_none_converter - - -def to_bool(val): - """ - Convert "boolean" strings (e.g., from env. vars.) to real booleans. - - Values mapping to :code:`True`: - - - :code:`True` - - :code:`"true"` / :code:`"t"` - - :code:`"yes"` / :code:`"y"` - - :code:`"on"` - - :code:`"1"` - - :code:`1` - - Values mapping to :code:`False`: - - - :code:`False` - - :code:`"false"` / :code:`"f"` - - :code:`"no"` / :code:`"n"` - - :code:`"off"` - - :code:`"0"` - - :code:`0` - - :raises ValueError: for any other value. - - .. versionadded:: 21.3.0 - """ - if isinstance(val, str): - val = val.lower() - truthy = {True, "true", "t", "yes", "y", "on", "1", 1} - falsy = {False, "false", "f", "no", "n", "off", "0", 0} - try: - if val in truthy: - return True - if val in falsy: - return False - except TypeError: - # Raised when "val" is not hashable (e.g., lists) - pass - raise ValueError("Cannot convert value to bool: {}".format(val)) diff --git a/.venv/Lib/site-packages/attr/converters.pyi b/.venv/Lib/site-packages/attr/converters.pyi deleted file mode 100644 index 0f58088..0000000 --- a/.venv/Lib/site-packages/attr/converters.pyi +++ /dev/null @@ -1,13 +0,0 @@ -from typing import Callable, Optional, TypeVar, overload - -from . import _ConverterType - -_T = TypeVar("_T") - -def pipe(*validators: _ConverterType) -> _ConverterType: ... -def optional(converter: _ConverterType) -> _ConverterType: ... -@overload -def default_if_none(default: _T) -> _ConverterType: ... -@overload -def default_if_none(*, factory: Callable[[], _T]) -> _ConverterType: ... -def to_bool(val: str) -> bool: ... diff --git a/.venv/Lib/site-packages/attr/exceptions.py b/.venv/Lib/site-packages/attr/exceptions.py deleted file mode 100644 index 5dc51e0..0000000 --- a/.venv/Lib/site-packages/attr/exceptions.py +++ /dev/null @@ -1,92 +0,0 @@ -# SPDX-License-Identifier: MIT - - -class FrozenError(AttributeError): - """ - A frozen/immutable instance or attribute have been attempted to be - modified. - - It mirrors the behavior of ``namedtuples`` by using the same error message - and subclassing `AttributeError`. - - .. versionadded:: 20.1.0 - """ - - msg = "can't set attribute" - args = [msg] - - -class FrozenInstanceError(FrozenError): - """ - A frozen instance has been attempted to be modified. - - .. versionadded:: 16.1.0 - """ - - -class FrozenAttributeError(FrozenError): - """ - A frozen attribute has been attempted to be modified. - - .. versionadded:: 20.1.0 - """ - - -class AttrsAttributeNotFoundError(ValueError): - """ - An ``attrs`` function couldn't find an attribute that the user asked for. - - .. versionadded:: 16.2.0 - """ - - -class NotAnAttrsClassError(ValueError): - """ - A non-``attrs`` class has been passed into an ``attrs`` function. - - .. versionadded:: 16.2.0 - """ - - -class DefaultAlreadySetError(RuntimeError): - """ - A default has been set using ``attr.ib()`` and is attempted to be reset - using the decorator. - - .. versionadded:: 17.1.0 - """ - - -class UnannotatedAttributeError(RuntimeError): - """ - A class with ``auto_attribs=True`` has an ``attr.ib()`` without a type - annotation. - - .. versionadded:: 17.3.0 - """ - - -class PythonTooOldError(RuntimeError): - """ - It was attempted to use an ``attrs`` feature that requires a newer Python - version. - - .. versionadded:: 18.2.0 - """ - - -class NotCallableError(TypeError): - """ - A ``attr.ib()`` requiring a callable has been set with a value - that is not callable. - - .. versionadded:: 19.2.0 - """ - - def __init__(self, msg, value): - super(TypeError, self).__init__(msg, value) - self.msg = msg - self.value = value - - def __str__(self): - return str(self.msg) diff --git a/.venv/Lib/site-packages/attr/exceptions.pyi b/.venv/Lib/site-packages/attr/exceptions.pyi deleted file mode 100644 index f268011..0000000 --- a/.venv/Lib/site-packages/attr/exceptions.pyi +++ /dev/null @@ -1,17 +0,0 @@ -from typing import Any - -class FrozenError(AttributeError): - msg: str = ... - -class FrozenInstanceError(FrozenError): ... -class FrozenAttributeError(FrozenError): ... -class AttrsAttributeNotFoundError(ValueError): ... -class NotAnAttrsClassError(ValueError): ... -class DefaultAlreadySetError(RuntimeError): ... -class UnannotatedAttributeError(RuntimeError): ... -class PythonTooOldError(RuntimeError): ... - -class NotCallableError(TypeError): - msg: str = ... - value: Any = ... - def __init__(self, msg: str, value: Any) -> None: ... diff --git a/.venv/Lib/site-packages/attr/filters.py b/.venv/Lib/site-packages/attr/filters.py deleted file mode 100644 index baa25e9..0000000 --- a/.venv/Lib/site-packages/attr/filters.py +++ /dev/null @@ -1,51 +0,0 @@ -# SPDX-License-Identifier: MIT - -""" -Commonly useful filters for `attr.asdict`. -""" - -from ._make import Attribute - - -def _split_what(what): - """ - Returns a tuple of `frozenset`s of classes and attributes. - """ - return ( - frozenset(cls for cls in what if isinstance(cls, type)), - frozenset(cls for cls in what if isinstance(cls, Attribute)), - ) - - -def include(*what): - """ - Include *what*. - - :param what: What to include. - :type what: `list` of `type` or `attrs.Attribute`\\ s - - :rtype: `callable` - """ - cls, attrs = _split_what(what) - - def include_(attribute, value): - return value.__class__ in cls or attribute in attrs - - return include_ - - -def exclude(*what): - """ - Exclude *what*. - - :param what: What to exclude. - :type what: `list` of classes or `attrs.Attribute`\\ s. - - :rtype: `callable` - """ - cls, attrs = _split_what(what) - - def exclude_(attribute, value): - return value.__class__ not in cls and attribute not in attrs - - return exclude_ diff --git a/.venv/Lib/site-packages/attr/filters.pyi b/.venv/Lib/site-packages/attr/filters.pyi deleted file mode 100644 index 9938668..0000000 --- a/.venv/Lib/site-packages/attr/filters.pyi +++ /dev/null @@ -1,6 +0,0 @@ -from typing import Any, Union - -from . import Attribute, _FilterType - -def include(*what: Union[type, Attribute[Any]]) -> _FilterType[Any]: ... -def exclude(*what: Union[type, Attribute[Any]]) -> _FilterType[Any]: ... diff --git a/.venv/Lib/site-packages/attr/py.typed b/.venv/Lib/site-packages/attr/py.typed deleted file mode 100644 index e69de29..0000000 diff --git a/.venv/Lib/site-packages/attr/setters.py b/.venv/Lib/site-packages/attr/setters.py deleted file mode 100644 index 12ed675..0000000 --- a/.venv/Lib/site-packages/attr/setters.py +++ /dev/null @@ -1,73 +0,0 @@ -# SPDX-License-Identifier: MIT - -""" -Commonly used hooks for on_setattr. -""" - - -from . import _config -from .exceptions import FrozenAttributeError - - -def pipe(*setters): - """ - Run all *setters* and return the return value of the last one. - - .. versionadded:: 20.1.0 - """ - - def wrapped_pipe(instance, attrib, new_value): - rv = new_value - - for setter in setters: - rv = setter(instance, attrib, rv) - - return rv - - return wrapped_pipe - - -def frozen(_, __, ___): - """ - Prevent an attribute to be modified. - - .. versionadded:: 20.1.0 - """ - raise FrozenAttributeError() - - -def validate(instance, attrib, new_value): - """ - Run *attrib*'s validator on *new_value* if it has one. - - .. versionadded:: 20.1.0 - """ - if _config._run_validators is False: - return new_value - - v = attrib.validator - if not v: - return new_value - - v(instance, attrib, new_value) - - return new_value - - -def convert(instance, attrib, new_value): - """ - Run *attrib*'s converter -- if it has one -- on *new_value* and return the - result. - - .. versionadded:: 20.1.0 - """ - c = attrib.converter - if c: - return c(new_value) - - return new_value - - -# Sentinel for disabling class-wide *on_setattr* hooks for certain attributes. -# autodata stopped working, so the docstring is inlined in the API docs. -NO_OP = object() diff --git a/.venv/Lib/site-packages/attr/setters.pyi b/.venv/Lib/site-packages/attr/setters.pyi deleted file mode 100644 index 3f5603c..0000000 --- a/.venv/Lib/site-packages/attr/setters.pyi +++ /dev/null @@ -1,19 +0,0 @@ -from typing import Any, NewType, NoReturn, TypeVar, cast - -from . import Attribute, _OnSetAttrType - -_T = TypeVar("_T") - -def frozen( - instance: Any, attribute: Attribute[Any], new_value: Any -) -> NoReturn: ... -def pipe(*setters: _OnSetAttrType) -> _OnSetAttrType: ... -def validate(instance: Any, attribute: Attribute[_T], new_value: _T) -> _T: ... - -# convert is allowed to return Any, because they can be chained using pipe. -def convert( - instance: Any, attribute: Attribute[Any], new_value: Any -) -> Any: ... - -_NoOpType = NewType("_NoOpType", object) -NO_OP: _NoOpType diff --git a/.venv/Lib/site-packages/attr/validators.py b/.venv/Lib/site-packages/attr/validators.py deleted file mode 100644 index eece517..0000000 --- a/.venv/Lib/site-packages/attr/validators.py +++ /dev/null @@ -1,594 +0,0 @@ -# SPDX-License-Identifier: MIT - -""" -Commonly useful validators. -""" - - -import operator -import re - -from contextlib import contextmanager - -from ._config import get_run_validators, set_run_validators -from ._make import _AndValidator, and_, attrib, attrs -from .exceptions import NotCallableError - - -try: - Pattern = re.Pattern -except AttributeError: # Python <3.7 lacks a Pattern type. - Pattern = type(re.compile("")) - - -__all__ = [ - "and_", - "deep_iterable", - "deep_mapping", - "disabled", - "ge", - "get_disabled", - "gt", - "in_", - "instance_of", - "is_callable", - "le", - "lt", - "matches_re", - "max_len", - "min_len", - "optional", - "provides", - "set_disabled", -] - - -def set_disabled(disabled): - """ - Globally disable or enable running validators. - - By default, they are run. - - :param disabled: If ``True``, disable running all validators. - :type disabled: bool - - .. warning:: - - This function is not thread-safe! - - .. versionadded:: 21.3.0 - """ - set_run_validators(not disabled) - - -def get_disabled(): - """ - Return a bool indicating whether validators are currently disabled or not. - - :return: ``True`` if validators are currently disabled. - :rtype: bool - - .. versionadded:: 21.3.0 - """ - return not get_run_validators() - - -@contextmanager -def disabled(): - """ - Context manager that disables running validators within its context. - - .. warning:: - - This context manager is not thread-safe! - - .. versionadded:: 21.3.0 - """ - set_run_validators(False) - try: - yield - finally: - set_run_validators(True) - - -@attrs(repr=False, slots=True, hash=True) -class _InstanceOfValidator: - type = attrib() - - def __call__(self, inst, attr, value): - """ - We use a callable class to be able to change the ``__repr__``. - """ - if not isinstance(value, self.type): - raise TypeError( - "'{name}' must be {type!r} (got {value!r} that is a " - "{actual!r}).".format( - name=attr.name, - type=self.type, - actual=value.__class__, - value=value, - ), - attr, - self.type, - value, - ) - - def __repr__(self): - return "".format( - type=self.type - ) - - -def instance_of(type): - """ - A validator that raises a `TypeError` if the initializer is called - with a wrong type for this particular attribute (checks are performed using - `isinstance` therefore it's also valid to pass a tuple of types). - - :param type: The type to check for. - :type type: type or tuple of types - - :raises TypeError: With a human readable error message, the attribute - (of type `attrs.Attribute`), the expected type, and the value it - got. - """ - return _InstanceOfValidator(type) - - -@attrs(repr=False, frozen=True, slots=True) -class _MatchesReValidator: - pattern = attrib() - match_func = attrib() - - def __call__(self, inst, attr, value): - """ - We use a callable class to be able to change the ``__repr__``. - """ - if not self.match_func(value): - raise ValueError( - "'{name}' must match regex {pattern!r}" - " ({value!r} doesn't)".format( - name=attr.name, pattern=self.pattern.pattern, value=value - ), - attr, - self.pattern, - value, - ) - - def __repr__(self): - return "".format( - pattern=self.pattern - ) - - -def matches_re(regex, flags=0, func=None): - r""" - A validator that raises `ValueError` if the initializer is called - with a string that doesn't match *regex*. - - :param regex: a regex string or precompiled pattern to match against - :param int flags: flags that will be passed to the underlying re function - (default 0) - :param callable func: which underlying `re` function to call. Valid options - are `re.fullmatch`, `re.search`, and `re.match`; the default ``None`` - means `re.fullmatch`. For performance reasons, the pattern is always - precompiled using `re.compile`. - - .. versionadded:: 19.2.0 - .. versionchanged:: 21.3.0 *regex* can be a pre-compiled pattern. - """ - valid_funcs = (re.fullmatch, None, re.search, re.match) - if func not in valid_funcs: - raise ValueError( - "'func' must be one of {}.".format( - ", ".join( - sorted( - e and e.__name__ or "None" for e in set(valid_funcs) - ) - ) - ) - ) - - if isinstance(regex, Pattern): - if flags: - raise TypeError( - "'flags' can only be used with a string pattern; " - "pass flags to re.compile() instead" - ) - pattern = regex - else: - pattern = re.compile(regex, flags) - - if func is re.match: - match_func = pattern.match - elif func is re.search: - match_func = pattern.search - else: - match_func = pattern.fullmatch - - return _MatchesReValidator(pattern, match_func) - - -@attrs(repr=False, slots=True, hash=True) -class _ProvidesValidator: - interface = attrib() - - def __call__(self, inst, attr, value): - """ - We use a callable class to be able to change the ``__repr__``. - """ - if not self.interface.providedBy(value): - raise TypeError( - "'{name}' must provide {interface!r} which {value!r} " - "doesn't.".format( - name=attr.name, interface=self.interface, value=value - ), - attr, - self.interface, - value, - ) - - def __repr__(self): - return "".format( - interface=self.interface - ) - - -def provides(interface): - """ - A validator that raises a `TypeError` if the initializer is called - with an object that does not provide the requested *interface* (checks are - performed using ``interface.providedBy(value)`` (see `zope.interface - `_). - - :param interface: The interface to check for. - :type interface: ``zope.interface.Interface`` - - :raises TypeError: With a human readable error message, the attribute - (of type `attrs.Attribute`), the expected interface, and the - value it got. - """ - return _ProvidesValidator(interface) - - -@attrs(repr=False, slots=True, hash=True) -class _OptionalValidator: - validator = attrib() - - def __call__(self, inst, attr, value): - if value is None: - return - - self.validator(inst, attr, value) - - def __repr__(self): - return "".format( - what=repr(self.validator) - ) - - -def optional(validator): - """ - A validator that makes an attribute optional. An optional attribute is one - which can be set to ``None`` in addition to satisfying the requirements of - the sub-validator. - - :param validator: A validator (or a list of validators) that is used for - non-``None`` values. - :type validator: callable or `list` of callables. - - .. versionadded:: 15.1.0 - .. versionchanged:: 17.1.0 *validator* can be a list of validators. - """ - if isinstance(validator, list): - return _OptionalValidator(_AndValidator(validator)) - return _OptionalValidator(validator) - - -@attrs(repr=False, slots=True, hash=True) -class _InValidator: - options = attrib() - - def __call__(self, inst, attr, value): - try: - in_options = value in self.options - except TypeError: # e.g. `1 in "abc"` - in_options = False - - if not in_options: - raise ValueError( - "'{name}' must be in {options!r} (got {value!r})".format( - name=attr.name, options=self.options, value=value - ), - attr, - self.options, - value, - ) - - def __repr__(self): - return "".format( - options=self.options - ) - - -def in_(options): - """ - A validator that raises a `ValueError` if the initializer is called - with a value that does not belong in the options provided. The check is - performed using ``value in options``. - - :param options: Allowed options. - :type options: list, tuple, `enum.Enum`, ... - - :raises ValueError: With a human readable error message, the attribute (of - type `attrs.Attribute`), the expected options, and the value it - got. - - .. versionadded:: 17.1.0 - .. versionchanged:: 22.1.0 - The ValueError was incomplete until now and only contained the human - readable error message. Now it contains all the information that has - been promised since 17.1.0. - """ - return _InValidator(options) - - -@attrs(repr=False, slots=False, hash=True) -class _IsCallableValidator: - def __call__(self, inst, attr, value): - """ - We use a callable class to be able to change the ``__repr__``. - """ - if not callable(value): - message = ( - "'{name}' must be callable " - "(got {value!r} that is a {actual!r})." - ) - raise NotCallableError( - msg=message.format( - name=attr.name, value=value, actual=value.__class__ - ), - value=value, - ) - - def __repr__(self): - return "" - - -def is_callable(): - """ - A validator that raises a `attr.exceptions.NotCallableError` if the - initializer is called with a value for this particular attribute - that is not callable. - - .. versionadded:: 19.1.0 - - :raises `attr.exceptions.NotCallableError`: With a human readable error - message containing the attribute (`attrs.Attribute`) name, - and the value it got. - """ - return _IsCallableValidator() - - -@attrs(repr=False, slots=True, hash=True) -class _DeepIterable: - member_validator = attrib(validator=is_callable()) - iterable_validator = attrib( - default=None, validator=optional(is_callable()) - ) - - def __call__(self, inst, attr, value): - """ - We use a callable class to be able to change the ``__repr__``. - """ - if self.iterable_validator is not None: - self.iterable_validator(inst, attr, value) - - for member in value: - self.member_validator(inst, attr, member) - - def __repr__(self): - iterable_identifier = ( - "" - if self.iterable_validator is None - else " {iterable!r}".format(iterable=self.iterable_validator) - ) - return ( - "" - ).format( - iterable_identifier=iterable_identifier, - member=self.member_validator, - ) - - -def deep_iterable(member_validator, iterable_validator=None): - """ - A validator that performs deep validation of an iterable. - - :param member_validator: Validator(s) to apply to iterable members - :param iterable_validator: Validator to apply to iterable itself - (optional) - - .. versionadded:: 19.1.0 - - :raises TypeError: if any sub-validators fail - """ - if isinstance(member_validator, (list, tuple)): - member_validator = and_(*member_validator) - return _DeepIterable(member_validator, iterable_validator) - - -@attrs(repr=False, slots=True, hash=True) -class _DeepMapping: - key_validator = attrib(validator=is_callable()) - value_validator = attrib(validator=is_callable()) - mapping_validator = attrib(default=None, validator=optional(is_callable())) - - def __call__(self, inst, attr, value): - """ - We use a callable class to be able to change the ``__repr__``. - """ - if self.mapping_validator is not None: - self.mapping_validator(inst, attr, value) - - for key in value: - self.key_validator(inst, attr, key) - self.value_validator(inst, attr, value[key]) - - def __repr__(self): - return ( - "" - ).format(key=self.key_validator, value=self.value_validator) - - -def deep_mapping(key_validator, value_validator, mapping_validator=None): - """ - A validator that performs deep validation of a dictionary. - - :param key_validator: Validator to apply to dictionary keys - :param value_validator: Validator to apply to dictionary values - :param mapping_validator: Validator to apply to top-level mapping - attribute (optional) - - .. versionadded:: 19.1.0 - - :raises TypeError: if any sub-validators fail - """ - return _DeepMapping(key_validator, value_validator, mapping_validator) - - -@attrs(repr=False, frozen=True, slots=True) -class _NumberValidator: - bound = attrib() - compare_op = attrib() - compare_func = attrib() - - def __call__(self, inst, attr, value): - """ - We use a callable class to be able to change the ``__repr__``. - """ - if not self.compare_func(value, self.bound): - raise ValueError( - "'{name}' must be {op} {bound}: {value}".format( - name=attr.name, - op=self.compare_op, - bound=self.bound, - value=value, - ) - ) - - def __repr__(self): - return "".format( - op=self.compare_op, bound=self.bound - ) - - -def lt(val): - """ - A validator that raises `ValueError` if the initializer is called - with a number larger or equal to *val*. - - :param val: Exclusive upper bound for values - - .. versionadded:: 21.3.0 - """ - return _NumberValidator(val, "<", operator.lt) - - -def le(val): - """ - A validator that raises `ValueError` if the initializer is called - with a number greater than *val*. - - :param val: Inclusive upper bound for values - - .. versionadded:: 21.3.0 - """ - return _NumberValidator(val, "<=", operator.le) - - -def ge(val): - """ - A validator that raises `ValueError` if the initializer is called - with a number smaller than *val*. - - :param val: Inclusive lower bound for values - - .. versionadded:: 21.3.0 - """ - return _NumberValidator(val, ">=", operator.ge) - - -def gt(val): - """ - A validator that raises `ValueError` if the initializer is called - with a number smaller or equal to *val*. - - :param val: Exclusive lower bound for values - - .. versionadded:: 21.3.0 - """ - return _NumberValidator(val, ">", operator.gt) - - -@attrs(repr=False, frozen=True, slots=True) -class _MaxLengthValidator: - max_length = attrib() - - def __call__(self, inst, attr, value): - """ - We use a callable class to be able to change the ``__repr__``. - """ - if len(value) > self.max_length: - raise ValueError( - "Length of '{name}' must be <= {max}: {len}".format( - name=attr.name, max=self.max_length, len=len(value) - ) - ) - - def __repr__(self): - return "".format(max=self.max_length) - - -def max_len(length): - """ - A validator that raises `ValueError` if the initializer is called - with a string or iterable that is longer than *length*. - - :param int length: Maximum length of the string or iterable - - .. versionadded:: 21.3.0 - """ - return _MaxLengthValidator(length) - - -@attrs(repr=False, frozen=True, slots=True) -class _MinLengthValidator: - min_length = attrib() - - def __call__(self, inst, attr, value): - """ - We use a callable class to be able to change the ``__repr__``. - """ - if len(value) < self.min_length: - raise ValueError( - "Length of '{name}' must be => {min}: {len}".format( - name=attr.name, min=self.min_length, len=len(value) - ) - ) - - def __repr__(self): - return "".format(min=self.min_length) - - -def min_len(length): - """ - A validator that raises `ValueError` if the initializer is called - with a string or iterable that is shorter than *length*. - - :param int length: Minimum length of the string or iterable - - .. versionadded:: 22.1.0 - """ - return _MinLengthValidator(length) diff --git a/.venv/Lib/site-packages/attr/validators.pyi b/.venv/Lib/site-packages/attr/validators.pyi deleted file mode 100644 index 54b9dba..0000000 --- a/.venv/Lib/site-packages/attr/validators.pyi +++ /dev/null @@ -1,80 +0,0 @@ -from typing import ( - Any, - AnyStr, - Callable, - Container, - ContextManager, - Iterable, - List, - Mapping, - Match, - Optional, - Pattern, - Tuple, - Type, - TypeVar, - Union, - overload, -) - -from . import _ValidatorType -from . import _ValidatorArgType - -_T = TypeVar("_T") -_T1 = TypeVar("_T1") -_T2 = TypeVar("_T2") -_T3 = TypeVar("_T3") -_I = TypeVar("_I", bound=Iterable) -_K = TypeVar("_K") -_V = TypeVar("_V") -_M = TypeVar("_M", bound=Mapping) - -def set_disabled(run: bool) -> None: ... -def get_disabled() -> bool: ... -def disabled() -> ContextManager[None]: ... - -# To be more precise on instance_of use some overloads. -# If there are more than 3 items in the tuple then we fall back to Any -@overload -def instance_of(type: Type[_T]) -> _ValidatorType[_T]: ... -@overload -def instance_of(type: Tuple[Type[_T]]) -> _ValidatorType[_T]: ... -@overload -def instance_of( - type: Tuple[Type[_T1], Type[_T2]] -) -> _ValidatorType[Union[_T1, _T2]]: ... -@overload -def instance_of( - type: Tuple[Type[_T1], Type[_T2], Type[_T3]] -) -> _ValidatorType[Union[_T1, _T2, _T3]]: ... -@overload -def instance_of(type: Tuple[type, ...]) -> _ValidatorType[Any]: ... -def provides(interface: Any) -> _ValidatorType[Any]: ... -def optional( - validator: Union[_ValidatorType[_T], List[_ValidatorType[_T]]] -) -> _ValidatorType[Optional[_T]]: ... -def in_(options: Container[_T]) -> _ValidatorType[_T]: ... -def and_(*validators: _ValidatorType[_T]) -> _ValidatorType[_T]: ... -def matches_re( - regex: Union[Pattern[AnyStr], AnyStr], - flags: int = ..., - func: Optional[ - Callable[[AnyStr, AnyStr, int], Optional[Match[AnyStr]]] - ] = ..., -) -> _ValidatorType[AnyStr]: ... -def deep_iterable( - member_validator: _ValidatorArgType[_T], - iterable_validator: Optional[_ValidatorType[_I]] = ..., -) -> _ValidatorType[_I]: ... -def deep_mapping( - key_validator: _ValidatorType[_K], - value_validator: _ValidatorType[_V], - mapping_validator: Optional[_ValidatorType[_M]] = ..., -) -> _ValidatorType[_M]: ... -def is_callable() -> _ValidatorType[_T]: ... -def lt(val: _T) -> _ValidatorType[_T]: ... -def le(val: _T) -> _ValidatorType[_T]: ... -def ge(val: _T) -> _ValidatorType[_T]: ... -def gt(val: _T) -> _ValidatorType[_T]: ... -def max_len(length: int) -> _ValidatorType[_T]: ... -def min_len(length: int) -> _ValidatorType[_T]: ... diff --git a/.venv/Lib/site-packages/attrs-22.1.0.dist-info/AUTHORS.rst b/.venv/Lib/site-packages/attrs-22.1.0.dist-info/AUTHORS.rst deleted file mode 100644 index aa677e8..0000000 --- a/.venv/Lib/site-packages/attrs-22.1.0.dist-info/AUTHORS.rst +++ /dev/null @@ -1,11 +0,0 @@ -Credits -======= - -``attrs`` is written and maintained by `Hynek Schlawack `_. - -The development is kindly supported by `Variomedia AG `_. - -A full list of contributors can be found in `GitHub's overview `_. - -It’s the spiritual successor of `characteristic `_ and aspires to fix some of it clunkiness and unfortunate decisions. -Both were inspired by Twisted’s `FancyEqMixin `_ but both are implemented using class decorators because `subclassing is bad for you `_, m’kay? diff --git a/.venv/Lib/site-packages/attrs-22.1.0.dist-info/INSTALLER b/.venv/Lib/site-packages/attrs-22.1.0.dist-info/INSTALLER deleted file mode 100644 index a1b589e..0000000 --- a/.venv/Lib/site-packages/attrs-22.1.0.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/.venv/Lib/site-packages/attrs-22.1.0.dist-info/LICENSE b/.venv/Lib/site-packages/attrs-22.1.0.dist-info/LICENSE deleted file mode 100644 index 2bd6453..0000000 --- a/.venv/Lib/site-packages/attrs-22.1.0.dist-info/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Hynek Schlawack and the attrs contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/.venv/Lib/site-packages/attrs-22.1.0.dist-info/METADATA b/.venv/Lib/site-packages/attrs-22.1.0.dist-info/METADATA deleted file mode 100644 index 60b6653..0000000 --- a/.venv/Lib/site-packages/attrs-22.1.0.dist-info/METADATA +++ /dev/null @@ -1,240 +0,0 @@ -Metadata-Version: 2.1 -Name: attrs -Version: 22.1.0 -Summary: Classes Without Boilerplate -Home-page: https://www.attrs.org/ -Author: Hynek Schlawack -Author-email: hs@ox.cx -Maintainer: Hynek Schlawack -Maintainer-email: hs@ox.cx -License: MIT -Project-URL: Documentation, https://www.attrs.org/ -Project-URL: Changelog, https://www.attrs.org/en/stable/changelog.html -Project-URL: Bug Tracker, https://github.com/python-attrs/attrs/issues -Project-URL: Source Code, https://github.com/python-attrs/attrs -Project-URL: Funding, https://github.com/sponsors/hynek -Project-URL: Tidelift, https://tidelift.com/subscription/pkg/pypi-attrs?utm_source=pypi-attrs&utm_medium=pypi -Project-URL: Ko-fi, https://ko-fi.com/the_hynek -Keywords: class,attribute,boilerplate -Classifier: Development Status :: 5 - Production/Stable -Classifier: Intended Audience :: Developers -Classifier: Natural Language :: English -Classifier: License :: OSI Approved :: MIT License -Classifier: Operating System :: OS Independent -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.5 -Classifier: Programming Language :: Python :: 3.6 -Classifier: Programming Language :: Python :: 3.7 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Programming Language :: Python :: Implementation :: CPython -Classifier: Programming Language :: Python :: Implementation :: PyPy -Classifier: Topic :: Software Development :: Libraries :: Python Modules -Requires-Python: >=3.5 -Description-Content-Type: text/x-rst -License-File: LICENSE -License-File: AUTHORS.rst -Provides-Extra: dev -Requires-Dist: coverage[toml] (>=5.0.2) ; extra == 'dev' -Requires-Dist: hypothesis ; extra == 'dev' -Requires-Dist: pympler ; extra == 'dev' -Requires-Dist: pytest (>=4.3.0) ; extra == 'dev' -Requires-Dist: mypy (!=0.940,>=0.900) ; extra == 'dev' -Requires-Dist: pytest-mypy-plugins ; extra == 'dev' -Requires-Dist: zope.interface ; extra == 'dev' -Requires-Dist: furo ; extra == 'dev' -Requires-Dist: sphinx ; extra == 'dev' -Requires-Dist: sphinx-notfound-page ; extra == 'dev' -Requires-Dist: pre-commit ; extra == 'dev' -Requires-Dist: cloudpickle ; (platform_python_implementation == "CPython") and extra == 'dev' -Provides-Extra: docs -Requires-Dist: furo ; extra == 'docs' -Requires-Dist: sphinx ; extra == 'docs' -Requires-Dist: zope.interface ; extra == 'docs' -Requires-Dist: sphinx-notfound-page ; extra == 'docs' -Provides-Extra: tests -Requires-Dist: coverage[toml] (>=5.0.2) ; extra == 'tests' -Requires-Dist: hypothesis ; extra == 'tests' -Requires-Dist: pympler ; extra == 'tests' -Requires-Dist: pytest (>=4.3.0) ; extra == 'tests' -Requires-Dist: mypy (!=0.940,>=0.900) ; extra == 'tests' -Requires-Dist: pytest-mypy-plugins ; extra == 'tests' -Requires-Dist: zope.interface ; extra == 'tests' -Requires-Dist: cloudpickle ; (platform_python_implementation == "CPython") and extra == 'tests' -Provides-Extra: tests_no_zope -Requires-Dist: coverage[toml] (>=5.0.2) ; extra == 'tests_no_zope' -Requires-Dist: hypothesis ; extra == 'tests_no_zope' -Requires-Dist: pympler ; extra == 'tests_no_zope' -Requires-Dist: pytest (>=4.3.0) ; extra == 'tests_no_zope' -Requires-Dist: mypy (!=0.940,>=0.900) ; extra == 'tests_no_zope' -Requires-Dist: pytest-mypy-plugins ; extra == 'tests_no_zope' -Requires-Dist: cloudpickle ; (platform_python_implementation == "CPython") and extra == 'tests_no_zope' - - -.. image:: https://www.attrs.org/en/stable/_static/attrs_logo.png - :alt: attrs logo - :align: center - - -``attrs`` is the Python package that will bring back the **joy** of **writing classes** by relieving you from the drudgery of implementing object protocols (aka `dunder methods `_). -`Trusted by NASA `_ for Mars missions since 2020! - -Its main goal is to help you to write **concise** and **correct** software without slowing down your code. - -.. teaser-end - -For that, it gives you a class decorator and a way to declaratively define the attributes on that class: - -.. -code-begin- - -.. code-block:: pycon - - >>> from attrs import asdict, define, make_class, Factory - - >>> @define - ... class SomeClass: - ... a_number: int = 42 - ... list_of_numbers: list[int] = Factory(list) - ... - ... def hard_math(self, another_number): - ... return self.a_number + sum(self.list_of_numbers) * another_number - - - >>> sc = SomeClass(1, [1, 2, 3]) - >>> sc - SomeClass(a_number=1, list_of_numbers=[1, 2, 3]) - - >>> sc.hard_math(3) - 19 - >>> sc == SomeClass(1, [1, 2, 3]) - True - >>> sc != SomeClass(2, [3, 2, 1]) - True - - >>> asdict(sc) - {'a_number': 1, 'list_of_numbers': [1, 2, 3]} - - >>> SomeClass() - SomeClass(a_number=42, list_of_numbers=[]) - - >>> C = make_class("C", ["a", "b"]) - >>> C("foo", "bar") - C(a='foo', b='bar') - - -After *declaring* your attributes, ``attrs`` gives you: - -- a concise and explicit overview of the class's attributes, -- a nice human-readable ``__repr__``, -- equality-checking methods, -- an initializer, -- and much more, - -*without* writing dull boilerplate code again and again and *without* runtime performance penalties. - -**Hate type annotations**!? -No problem! -Types are entirely **optional** with ``attrs``. -Simply assign ``attrs.field()`` to the attributes instead of annotating them with types. - ----- - -This example uses ``attrs``'s modern APIs that have been introduced in version 20.1.0, and the ``attrs`` package import name that has been added in version 21.3.0. -The classic APIs (``@attr.s``, ``attr.ib``, plus their serious-business aliases) and the ``attr`` package import name will remain **indefinitely**. - -Please check out `On The Core API Names `_ for a more in-depth explanation. - - -Data Classes -============ - -On the tin, ``attrs`` might remind you of ``dataclasses`` (and indeed, ``dataclasses`` `are a descendant `_ of ``attrs``). -In practice it does a lot more and is more flexible. -For instance it allows you to define `special handling of NumPy arrays for equality checks `_, or allows more ways to `plug into the initialization process `_. - -For more details, please refer to our `comparison page `_. - -.. -project-information- - -Project Information -=================== - -- **License**: `MIT `_ -- **PyPI**: https://pypi.org/project/attrs/ -- **Source Code**: https://github.com/python-attrs/attrs -- **Documentation**: https://www.attrs.org/ -- **Changelog**: https://www.attrs.org/en/stable/changelog.html -- **Get Help**: please use the ``python-attrs`` tag on `StackOverflow `_ -- **Third-party Extensions**: https://github.com/python-attrs/attrs/wiki/Extensions-to-attrs -- **Supported Python Versions**: 3.5 and later (last 2.7-compatible release is `21.4.0 `_) - -If you'd like to contribute to ``attrs`` you're most welcome and we've written `a little guide `_ to get you started! - - -``attrs`` for Enterprise ------------------------- - -Available as part of the Tidelift Subscription. - -The maintainers of ``attrs`` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source packages you use to build your applications. -Save time, reduce risk, and improve code health, while paying the maintainers of the exact packages you use. -`Learn more. `_ - - -Release Information -=================== - -22.1.0 (2022-07-28) -------------------- - -Backwards-incompatible Changes -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -- Python 2.7 is not supported anymore. - - Dealing with Python 2.7 tooling has become too difficult for a volunteer-run project. - - We have supported Python 2 more than 2 years after it was officially discontinued and feel that we have paid our dues. - All version up to 21.4.0 from December 2021 remain fully functional, of course. - `#936 `_ -- The deprecated ``cmp`` attribute of ``attrs.Attribute`` has been removed. - This does not affect the *cmp* argument to ``attr.s`` that can be used as a shortcut to set *eq* and *order* at the same time. - `#939 `_ - - -Changes -^^^^^^^ - -- Instantiation of frozen slotted classes is now faster. - `#898 `_ -- If an ``eq`` key is defined, it is also used before hashing the attribute. - `#909 `_ -- Added ``attrs.validators.min_len()``. - `#916 `_ -- ``attrs.validators.deep_iterable()``'s *member_validator* argument now also accepts a list of validators and wraps them in an ``attrs.validators.and_()``. - `#925 `_ -- Added missing type stub re-imports for ``attrs.converters`` and ``attrs.filters``. - `#931 `_ -- Added missing stub for ``attr(s).cmp_using()``. - `#949 `_ -- ``attrs.validators._in()``'s ``ValueError`` is not missing the attribute, expected options, and the value it got anymore. - `#951 `_ -- Python 3.11 is now officially supported. - `#969 `_ - -`Full changelog `_. - -Credits -======= - -``attrs`` is written and maintained by `Hynek Schlawack `_. - -The development is kindly supported by `Variomedia AG `_. - -A full list of contributors can be found in `GitHub's overview `_. - -It’s the spiritual successor of `characteristic `_ and aspires to fix some of it clunkiness and unfortunate decisions. -Both were inspired by Twisted’s `FancyEqMixin `_ but both are implemented using class decorators because `subclassing is bad for you `_, m’kay? diff --git a/.venv/Lib/site-packages/attrs-22.1.0.dist-info/RECORD b/.venv/Lib/site-packages/attrs-22.1.0.dist-info/RECORD deleted file mode 100644 index efb514e..0000000 --- a/.venv/Lib/site-packages/attrs-22.1.0.dist-info/RECORD +++ /dev/null @@ -1,56 +0,0 @@ -attr/__init__.py,sha256=KZjj88xCd_tH-W59HR1EvHiYAUi4Zd1dzOxx8P77jeI,1602 -attr/__init__.pyi,sha256=t-1r-I1VnyxFrqic__QxIk1HUc3ag53L2b8lv0xDZTw,15137 -attr/__pycache__/__init__.cpython-38.pyc,, -attr/__pycache__/_cmp.cpython-38.pyc,, -attr/__pycache__/_compat.cpython-38.pyc,, -attr/__pycache__/_config.cpython-38.pyc,, -attr/__pycache__/_funcs.cpython-38.pyc,, -attr/__pycache__/_make.cpython-38.pyc,, -attr/__pycache__/_next_gen.cpython-38.pyc,, -attr/__pycache__/_version_info.cpython-38.pyc,, -attr/__pycache__/converters.cpython-38.pyc,, -attr/__pycache__/exceptions.cpython-38.pyc,, -attr/__pycache__/filters.cpython-38.pyc,, -attr/__pycache__/setters.cpython-38.pyc,, -attr/__pycache__/validators.cpython-38.pyc,, -attr/_cmp.py,sha256=Mmqj-6w71g_vx0TTLLkU4pbmv28qz_FyBGcUb1HX9ZE,4102 -attr/_cmp.pyi,sha256=cSlVvIH4As2NlDIoLglPEbSrBMWVVTpwExVDDBH6pn8,357 -attr/_compat.py,sha256=Qr9kZOu95Og7joPaQiXoPb54epKqxNU39Xu0u4QVGZI,5568 -attr/_config.py,sha256=5W8lgRePuIOWu1ZuqF1899e2CmXGc95-ipwTpF1cEU4,826 -attr/_funcs.py,sha256=XTFKZtd5zxsUvWocBw7VAswTxH-nFHk0H8gJ2JQkxD4,14645 -attr/_make.py,sha256=Srxbhb8kB17T6nP9e_dgcXY72zda9xfL5uJzva6LExY,97569 -attr/_next_gen.py,sha256=N0Gb5WdBHfcfQhcUsLAc_2ZYzl0JtAX1NOHuDgvkecE,5882 -attr/_version_info.py,sha256=exSqb3b5E-fMSsgZAlEw9XcLpEgobPORCZpcaEglAM4,2121 -attr/_version_info.pyi,sha256=x_M3L3WuB7r_ULXAWjx959udKQ4HLB8l-hsc1FDGNvk,209 -attr/converters.py,sha256=TWCfmCAxk8s2tgTSYnyQv9MRDPf1pk8Rj16KO_Xqe1c,3610 -attr/converters.pyi,sha256=MQo7iEzPNVoFpKqD30sVwgVpdNoIeSCF2nsXvoxLZ-Y,416 -attr/exceptions.py,sha256=ZGEMLv0CDY1TOtj49OF84myejOn-LCCXAKGIKalKkVU,1915 -attr/exceptions.pyi,sha256=zZq8bCUnKAy9mDtBEw42ZhPhAUIHoTKedDQInJD883M,539 -attr/filters.py,sha256=aZep54h8-4ZYV5lmZ3Dx2mqeQH4cMx6tuCmCylLNbEU,1038 -attr/filters.pyi,sha256=_Sm80jGySETX_Clzdkon5NHVjQWRl3Y3liQKZX1czXc,215 -attr/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -attr/setters.py,sha256=pbCZQ-pE6ZxjDqZfWWUhUFefXtpekIU4qS_YDMLPQ50,1400 -attr/setters.pyi,sha256=7dM10rqpQVDW0y-iJUnq8rabdO5Wx2Sbo5LwNa0IXl0,573 -attr/validators.py,sha256=cpOHMNSt02ApbTQtQAwBTMeWZqp0u_sx-e3xH-jTyR4,16793 -attr/validators.pyi,sha256=6ngbvnWnFSkbf5J2dK86pq2xpEtrwzWTKfJ4aUvSIlk,2355 -attrs-22.1.0.dist-info/AUTHORS.rst,sha256=jau5p7JMPbBJeCCpGBWsRj8zpxUVAhpyoHFJRfjM888,743 -attrs-22.1.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -attrs-22.1.0.dist-info/LICENSE,sha256=iCEVyV38KvHutnFPjsbVy8q_Znyv-HKfQkINpj9xTp8,1109 -attrs-22.1.0.dist-info/METADATA,sha256=vwSMK_BbEgVHrgFWpj3iW0PISTMPHzi6qham9jg7LtA,11015 -attrs-22.1.0.dist-info/RECORD,, -attrs-22.1.0.dist-info/WHEEL,sha256=z9j0xAa_JmUKMpmz72K0ZGALSM_n-wQVmGbleXx2VHg,110 -attrs-22.1.0.dist-info/top_level.txt,sha256=AGbmKnOtYpdkLRsDRQVSBIwfL32pAQ6BSo1mt-BxI7M,11 -attrs/__init__.py,sha256=CeyxLGVViAEKKsLOLaif8vF3vs1a28vsrRVLv7eMEgM,1109 -attrs/__init__.pyi,sha256=vuFxNbulP9Q7hfpO6Lb5A-_0mbEJOiwYyefjzXMqVfs,2100 -attrs/__pycache__/__init__.cpython-38.pyc,, -attrs/__pycache__/converters.cpython-38.pyc,, -attrs/__pycache__/exceptions.cpython-38.pyc,, -attrs/__pycache__/filters.cpython-38.pyc,, -attrs/__pycache__/setters.cpython-38.pyc,, -attrs/__pycache__/validators.cpython-38.pyc,, -attrs/converters.py,sha256=fCBEdlYWcmI3sCnpUk2pz22GYtXzqTkp6NeOpdI64PY,70 -attrs/exceptions.py,sha256=SlDli6AY77f6ny-H7oy98OkQjsrw-D_supEuErIVYkE,70 -attrs/filters.py,sha256=dc_dNey29kH6KLU1mT2Dakq7tZ3kBfzEGwzOmDzw1F8,67 -attrs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -attrs/setters.py,sha256=oKw51C72Hh45wTwYvDHJP9kbicxiMhMR4Y5GvdpKdHQ,67 -attrs/validators.py,sha256=4ag1SyVD2Hm3PYKiNG_NOtR_e7f81Hr6GiNl4YvXo4Q,70 diff --git a/.venv/Lib/site-packages/attrs-22.1.0.dist-info/WHEEL b/.venv/Lib/site-packages/attrs-22.1.0.dist-info/WHEEL deleted file mode 100644 index 0b18a28..0000000 --- a/.venv/Lib/site-packages/attrs-22.1.0.dist-info/WHEEL +++ /dev/null @@ -1,6 +0,0 @@ -Wheel-Version: 1.0 -Generator: bdist_wheel (0.37.1) -Root-Is-Purelib: true -Tag: py2-none-any -Tag: py3-none-any - diff --git a/.venv/Lib/site-packages/attrs-22.1.0.dist-info/top_level.txt b/.venv/Lib/site-packages/attrs-22.1.0.dist-info/top_level.txt deleted file mode 100644 index eca8ba9..0000000 --- a/.venv/Lib/site-packages/attrs-22.1.0.dist-info/top_level.txt +++ /dev/null @@ -1,2 +0,0 @@ -attr -attrs diff --git a/.venv/Lib/site-packages/attrs/__init__.py b/.venv/Lib/site-packages/attrs/__init__.py deleted file mode 100644 index a704b8b..0000000 --- a/.venv/Lib/site-packages/attrs/__init__.py +++ /dev/null @@ -1,70 +0,0 @@ -# SPDX-License-Identifier: MIT - -from attr import ( - NOTHING, - Attribute, - Factory, - __author__, - __copyright__, - __description__, - __doc__, - __email__, - __license__, - __title__, - __url__, - __version__, - __version_info__, - assoc, - cmp_using, - define, - evolve, - field, - fields, - fields_dict, - frozen, - has, - make_class, - mutable, - resolve_types, - validate, -) -from attr._next_gen import asdict, astuple - -from . import converters, exceptions, filters, setters, validators - - -__all__ = [ - "__author__", - "__copyright__", - "__description__", - "__doc__", - "__email__", - "__license__", - "__title__", - "__url__", - "__version__", - "__version_info__", - "asdict", - "assoc", - "astuple", - "Attribute", - "cmp_using", - "converters", - "define", - "evolve", - "exceptions", - "Factory", - "field", - "fields_dict", - "fields", - "filters", - "frozen", - "has", - "make_class", - "mutable", - "NOTHING", - "resolve_types", - "setters", - "validate", - "validators", -] diff --git a/.venv/Lib/site-packages/attrs/__init__.pyi b/.venv/Lib/site-packages/attrs/__init__.pyi deleted file mode 100644 index fc44de4..0000000 --- a/.venv/Lib/site-packages/attrs/__init__.pyi +++ /dev/null @@ -1,66 +0,0 @@ -from typing import ( - Any, - Callable, - Dict, - Mapping, - Optional, - Sequence, - Tuple, - Type, -) - -# Because we need to type our own stuff, we have to make everything from -# attr explicitly public too. -from attr import __author__ as __author__ -from attr import __copyright__ as __copyright__ -from attr import __description__ as __description__ -from attr import __email__ as __email__ -from attr import __license__ as __license__ -from attr import __title__ as __title__ -from attr import __url__ as __url__ -from attr import __version__ as __version__ -from attr import __version_info__ as __version_info__ -from attr import _FilterType -from attr import assoc as assoc -from attr import Attribute as Attribute -from attr import cmp_using as cmp_using -from attr import converters as converters -from attr import define as define -from attr import evolve as evolve -from attr import exceptions as exceptions -from attr import Factory as Factory -from attr import field as field -from attr import fields as fields -from attr import fields_dict as fields_dict -from attr import filters as filters -from attr import frozen as frozen -from attr import has as has -from attr import make_class as make_class -from attr import mutable as mutable -from attr import NOTHING as NOTHING -from attr import resolve_types as resolve_types -from attr import setters as setters -from attr import validate as validate -from attr import validators as validators - -# TODO: see definition of attr.asdict/astuple -def asdict( - inst: Any, - recurse: bool = ..., - filter: Optional[_FilterType[Any]] = ..., - dict_factory: Type[Mapping[Any, Any]] = ..., - retain_collection_types: bool = ..., - value_serializer: Optional[ - Callable[[type, Attribute[Any], Any], Any] - ] = ..., - tuple_keys: bool = ..., -) -> Dict[str, Any]: ... - -# TODO: add support for returning NamedTuple from the mypy plugin -def astuple( - inst: Any, - recurse: bool = ..., - filter: Optional[_FilterType[Any]] = ..., - tuple_factory: Type[Sequence[Any]] = ..., - retain_collection_types: bool = ..., -) -> Tuple[Any, ...]: ... diff --git a/.venv/Lib/site-packages/attrs/__pycache__/__init__.cpython-38.pyc b/.venv/Lib/site-packages/attrs/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index d45d257..0000000 Binary files a/.venv/Lib/site-packages/attrs/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/attrs/__pycache__/converters.cpython-38.pyc b/.venv/Lib/site-packages/attrs/__pycache__/converters.cpython-38.pyc deleted file mode 100644 index 6a5e171..0000000 Binary files a/.venv/Lib/site-packages/attrs/__pycache__/converters.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/attrs/__pycache__/exceptions.cpython-38.pyc b/.venv/Lib/site-packages/attrs/__pycache__/exceptions.cpython-38.pyc deleted file mode 100644 index f2f0460..0000000 Binary files a/.venv/Lib/site-packages/attrs/__pycache__/exceptions.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/attrs/__pycache__/filters.cpython-38.pyc b/.venv/Lib/site-packages/attrs/__pycache__/filters.cpython-38.pyc deleted file mode 100644 index 1418ef4..0000000 Binary files a/.venv/Lib/site-packages/attrs/__pycache__/filters.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/attrs/__pycache__/setters.cpython-38.pyc b/.venv/Lib/site-packages/attrs/__pycache__/setters.cpython-38.pyc deleted file mode 100644 index 7a8f00d..0000000 Binary files a/.venv/Lib/site-packages/attrs/__pycache__/setters.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/attrs/__pycache__/validators.cpython-38.pyc b/.venv/Lib/site-packages/attrs/__pycache__/validators.cpython-38.pyc deleted file mode 100644 index 101b0d1..0000000 Binary files a/.venv/Lib/site-packages/attrs/__pycache__/validators.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/attrs/converters.py b/.venv/Lib/site-packages/attrs/converters.py deleted file mode 100644 index edfa8d3..0000000 --- a/.venv/Lib/site-packages/attrs/converters.py +++ /dev/null @@ -1,3 +0,0 @@ -# SPDX-License-Identifier: MIT - -from attr.converters import * # noqa diff --git a/.venv/Lib/site-packages/attrs/exceptions.py b/.venv/Lib/site-packages/attrs/exceptions.py deleted file mode 100644 index bd9efed..0000000 --- a/.venv/Lib/site-packages/attrs/exceptions.py +++ /dev/null @@ -1,3 +0,0 @@ -# SPDX-License-Identifier: MIT - -from attr.exceptions import * # noqa diff --git a/.venv/Lib/site-packages/attrs/filters.py b/.venv/Lib/site-packages/attrs/filters.py deleted file mode 100644 index 5295900..0000000 --- a/.venv/Lib/site-packages/attrs/filters.py +++ /dev/null @@ -1,3 +0,0 @@ -# SPDX-License-Identifier: MIT - -from attr.filters import * # noqa diff --git a/.venv/Lib/site-packages/attrs/py.typed b/.venv/Lib/site-packages/attrs/py.typed deleted file mode 100644 index e69de29..0000000 diff --git a/.venv/Lib/site-packages/attrs/setters.py b/.venv/Lib/site-packages/attrs/setters.py deleted file mode 100644 index 9b50770..0000000 --- a/.venv/Lib/site-packages/attrs/setters.py +++ /dev/null @@ -1,3 +0,0 @@ -# SPDX-License-Identifier: MIT - -from attr.setters import * # noqa diff --git a/.venv/Lib/site-packages/attrs/validators.py b/.venv/Lib/site-packages/attrs/validators.py deleted file mode 100644 index ab2c9b3..0000000 --- a/.venv/Lib/site-packages/attrs/validators.py +++ /dev/null @@ -1,3 +0,0 @@ -# SPDX-License-Identifier: MIT - -from attr.validators import * # noqa diff --git a/.venv/Lib/site-packages/charset_normalizer-2.1.1.dist-info/INSTALLER b/.venv/Lib/site-packages/charset_normalizer-2.1.1.dist-info/INSTALLER deleted file mode 100644 index a1b589e..0000000 --- a/.venv/Lib/site-packages/charset_normalizer-2.1.1.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/.venv/Lib/site-packages/charset_normalizer-2.1.1.dist-info/LICENSE b/.venv/Lib/site-packages/charset_normalizer-2.1.1.dist-info/LICENSE deleted file mode 100644 index ad82355..0000000 --- a/.venv/Lib/site-packages/charset_normalizer-2.1.1.dist-info/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019 TAHRI Ahmed R. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/.venv/Lib/site-packages/charset_normalizer-2.1.1.dist-info/METADATA b/.venv/Lib/site-packages/charset_normalizer-2.1.1.dist-info/METADATA deleted file mode 100644 index c6ebd7d..0000000 --- a/.venv/Lib/site-packages/charset_normalizer-2.1.1.dist-info/METADATA +++ /dev/null @@ -1,269 +0,0 @@ -Metadata-Version: 2.1 -Name: charset-normalizer -Version: 2.1.1 -Summary: The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet. -Home-page: https://github.com/ousret/charset_normalizer -Author: Ahmed TAHRI @Ousret -Author-email: ahmed.tahri@cloudnursery.dev -License: MIT -Project-URL: Bug Reports, https://github.com/Ousret/charset_normalizer/issues -Project-URL: Documentation, https://charset-normalizer.readthedocs.io/en/latest -Keywords: encoding,i18n,txt,text,charset,charset-detector,normalization,unicode,chardet -Classifier: Development Status :: 5 - Production/Stable -Classifier: License :: OSI Approved :: MIT License -Classifier: Intended Audience :: Developers -Classifier: Topic :: Software Development :: Libraries :: Python Modules -Classifier: Operating System :: OS Independent -Classifier: Programming Language :: Python -Classifier: Programming Language :: Python :: 3 -Classifier: Programming Language :: Python :: 3.6 -Classifier: Programming Language :: Python :: 3.7 -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Programming Language :: Python :: 3.11 -Classifier: Topic :: Text Processing :: Linguistic -Classifier: Topic :: Utilities -Classifier: Programming Language :: Python :: Implementation :: PyPy -Classifier: Typing :: Typed -Requires-Python: >=3.6.0 -Description-Content-Type: text/markdown -License-File: LICENSE -Provides-Extra: unicode_backport -Requires-Dist: unicodedata2 ; extra == 'unicode_backport' - - -

    Charset Detection, for Everyone 👋

    - -

    - The Real First Universal Charset Detector
    - - - - - - - - Download Count Total - -

    - -> A library that helps you read text from an unknown charset encoding.
    Motivated by `chardet`, -> I'm trying to resolve the issue by taking a new approach. -> All IANA character set names for which the Python core library provides codecs are supported. - -

    - >>>>> 👉 Try Me Online Now, Then Adopt Me 👈 <<<<< -

    - -This project offers you an alternative to **Universal Charset Encoding Detector**, also known as **Chardet**. - -| Feature | [Chardet](https://github.com/chardet/chardet) | Charset Normalizer | [cChardet](https://github.com/PyYoshi/cChardet) | -| ------------- | :-------------: | :------------------: | :------------------: | -| `Fast` | ❌
    | ✅
    | ✅
    | -| `Universal**` | ❌ | ✅ | ❌ | -| `Reliable` **without** distinguishable standards | ❌ | ✅ | ✅ | -| `Reliable` **with** distinguishable standards | ✅ | ✅ | ✅ | -| `License` | LGPL-2.1
    _restrictive_ | MIT | MPL-1.1
    _restrictive_ | -| `Native Python` | ✅ | ✅ | ❌ | -| `Detect spoken language` | ❌ | ✅ | N/A | -| `UnicodeDecodeError Safety` | ❌ | ✅ | ❌ | -| `Whl Size` | 193.6 kB | 39.5 kB | ~200 kB | -| `Supported Encoding` | 33 | :tada: [93](https://charset-normalizer.readthedocs.io/en/latest/user/support.html#supported-encodings) | 40 - -

    -Reading Normalized TextCat Reading Text - -*\*\* : They are clearly using specific code for a specific encoding even if covering most of used one*
    -Did you got there because of the logs? See [https://charset-normalizer.readthedocs.io/en/latest/user/miscellaneous.html](https://charset-normalizer.readthedocs.io/en/latest/user/miscellaneous.html) - -## ⭐ Your support - -*Fork, test-it, star-it, submit your ideas! We do listen.* - -## ⚡ Performance - -This package offer better performance than its counterpart Chardet. Here are some numbers. - -| Package | Accuracy | Mean per file (ms) | File per sec (est) | -| ------------- | :-------------: | :------------------: | :------------------: | -| [chardet](https://github.com/chardet/chardet) | 86 % | 200 ms | 5 file/sec | -| charset-normalizer | **98 %** | **39 ms** | 26 file/sec | - -| Package | 99th percentile | 95th percentile | 50th percentile | -| ------------- | :-------------: | :------------------: | :------------------: | -| [chardet](https://github.com/chardet/chardet) | 1200 ms | 287 ms | 23 ms | -| charset-normalizer | 400 ms | 200 ms | 15 ms | - -Chardet's performance on larger file (1MB+) are very poor. Expect huge difference on large payload. - -> Stats are generated using 400+ files using default parameters. More details on used files, see GHA workflows. -> And yes, these results might change at any time. The dataset can be updated to include more files. -> The actual delays heavily depends on your CPU capabilities. The factors should remain the same. -> Keep in mind that the stats are generous and that Chardet accuracy vs our is measured using Chardet initial capability -> (eg. Supported Encoding) Challenge-them if you want. - -[cchardet](https://github.com/PyYoshi/cChardet) is a non-native (cpp binding) and unmaintained faster alternative with -a better accuracy than chardet but lower than this package. If speed is the most important factor, you should try it. - -## ✨ Installation - -Using PyPi for latest stable -```sh -pip install charset-normalizer -U -``` - -If you want a more up-to-date `unicodedata` than the one available in your Python setup. -```sh -pip install charset-normalizer[unicode_backport] -U -``` - -## 🚀 Basic Usage - -### CLI -This package comes with a CLI. - -``` -usage: normalizer [-h] [-v] [-a] [-n] [-m] [-r] [-f] [-t THRESHOLD] - file [file ...] - -The Real First Universal Charset Detector. Discover originating encoding used -on text file. Normalize text to unicode. - -positional arguments: - files File(s) to be analysed - -optional arguments: - -h, --help show this help message and exit - -v, --verbose Display complementary information about file if any. - Stdout will contain logs about the detection process. - -a, --with-alternative - Output complementary possibilities if any. Top-level - JSON WILL be a list. - -n, --normalize Permit to normalize input file. If not set, program - does not write anything. - -m, --minimal Only output the charset detected to STDOUT. Disabling - JSON output. - -r, --replace Replace file when trying to normalize it instead of - creating a new one. - -f, --force Replace file without asking if you are sure, use this - flag with caution. - -t THRESHOLD, --threshold THRESHOLD - Define a custom maximum amount of chaos allowed in - decoded content. 0. <= chaos <= 1. - --version Show version information and exit. -``` - -```bash -normalizer ./data/sample.1.fr.srt -``` - -:tada: Since version 1.4.0 the CLI produce easily usable stdout result in JSON format. - -```json -{ - "path": "/home/default/projects/charset_normalizer/data/sample.1.fr.srt", - "encoding": "cp1252", - "encoding_aliases": [ - "1252", - "windows_1252" - ], - "alternative_encodings": [ - "cp1254", - "cp1256", - "cp1258", - "iso8859_14", - "iso8859_15", - "iso8859_16", - "iso8859_3", - "iso8859_9", - "latin_1", - "mbcs" - ], - "language": "French", - "alphabets": [ - "Basic Latin", - "Latin-1 Supplement" - ], - "has_sig_or_bom": false, - "chaos": 0.149, - "coherence": 97.152, - "unicode_path": null, - "is_preferred": true -} -``` - -### Python -*Just print out normalized text* -```python -from charset_normalizer import from_path - -results = from_path('./my_subtitle.srt') - -print(str(results.best())) -``` - -*Normalize any text file* -```python -from charset_normalizer import normalize -try: - normalize('./my_subtitle.srt') # should write to disk my_subtitle-***.srt -except IOError as e: - print('Sadly, we are unable to perform charset normalization.', str(e)) -``` - -*Upgrade your code without effort* -```python -from charset_normalizer import detect -``` - -The above code will behave the same as **chardet**. We ensure that we offer the best (reasonable) BC result possible. - -See the docs for advanced usage : [readthedocs.io](https://charset-normalizer.readthedocs.io/en/latest/) - -## 😇 Why - -When I started using Chardet, I noticed that it was not suited to my expectations, and I wanted to propose a -reliable alternative using a completely different method. Also! I never back down on a good challenge! - -I **don't care** about the **originating charset** encoding, because **two different tables** can -produce **two identical rendered string.** -What I want is to get readable text, the best I can. - -In a way, **I'm brute forcing text decoding.** How cool is that ? 😎 - -Don't confuse package **ftfy** with charset-normalizer or chardet. ftfy goal is to repair unicode string whereas charset-normalizer to convert raw file in unknown encoding to unicode. - -## 🍰 How - - - Discard all charset encoding table that could not fit the binary content. - - Measure chaos, or the mess once opened (by chunks) with a corresponding charset encoding. - - Extract matches with the lowest mess detected. - - Additionally, we measure coherence / probe for a language. - -**Wait a minute**, what is chaos/mess and coherence according to **YOU ?** - -*Chaos :* I opened hundred of text files, **written by humans**, with the wrong encoding table. **I observed**, then -**I established** some ground rules about **what is obvious** when **it seems like** a mess. - I know that my interpretation of what is chaotic is very subjective, feel free to contribute in order to - improve or rewrite it. - -*Coherence :* For each language there is on earth, we have computed ranked letter appearance occurrences (the best we can). So I thought -that intel is worth something here. So I use those records against decoded text to check if I can detect intelligent design. - -## ⚡ Known limitations - - - Language detection is unreliable when text contains two or more languages sharing identical letters. (eg. HTML (english tags) + Turkish content (Sharing Latin characters)) - - Every charset detector heavily depends on sufficient content. In common cases, do not bother run detection on very tiny content. - -## 👤 Contributing - -Contributions, issues and feature requests are very much welcome.
    -Feel free to check [issues page](https://github.com/ousret/charset_normalizer/issues) if you want to contribute. - -## 📝 License - -Copyright © 2019 [Ahmed TAHRI @Ousret](https://github.com/Ousret).
    -This project is [MIT](https://github.com/Ousret/charset_normalizer/blob/master/LICENSE) licensed. - -Characters frequencies used in this project © 2012 [Denny Vrandečić](http://simia.net/letters/) diff --git a/.venv/Lib/site-packages/charset_normalizer-2.1.1.dist-info/RECORD b/.venv/Lib/site-packages/charset_normalizer-2.1.1.dist-info/RECORD deleted file mode 100644 index 8d37ffc..0000000 --- a/.venv/Lib/site-packages/charset_normalizer-2.1.1.dist-info/RECORD +++ /dev/null @@ -1,33 +0,0 @@ -../../Scripts/normalizer.exe,sha256=h7vWu9IJkkOAxWsdWIUYJMdwQ7Xb1uP1c7kiOROlGD8,106403 -charset_normalizer-2.1.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -charset_normalizer-2.1.1.dist-info/LICENSE,sha256=6zGgxaT7Cbik4yBV0lweX5w1iidS_vPNcgIT0cz-4kE,1070 -charset_normalizer-2.1.1.dist-info/METADATA,sha256=C99l12g4d1E9_UiW-mqPCWx7v2M_lYGWxy1GTOjXSsA,11942 -charset_normalizer-2.1.1.dist-info/RECORD,, -charset_normalizer-2.1.1.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92 -charset_normalizer-2.1.1.dist-info/entry_points.txt,sha256=uYo8aIGLWv8YgWfSna5HnfY_En4pkF1w4bgawNAXzP0,76 -charset_normalizer-2.1.1.dist-info/top_level.txt,sha256=7ASyzePr8_xuZWJsnqJjIBtyV8vhEo0wBCv1MPRRi3Q,19 -charset_normalizer/__init__.py,sha256=jGhhf1IcOgCpZsr593E9fPvjWKnflVqHe_LwkOJjInU,1790 -charset_normalizer/__pycache__/__init__.cpython-38.pyc,, -charset_normalizer/__pycache__/api.cpython-38.pyc,, -charset_normalizer/__pycache__/cd.cpython-38.pyc,, -charset_normalizer/__pycache__/constant.cpython-38.pyc,, -charset_normalizer/__pycache__/legacy.cpython-38.pyc,, -charset_normalizer/__pycache__/md.cpython-38.pyc,, -charset_normalizer/__pycache__/models.cpython-38.pyc,, -charset_normalizer/__pycache__/utils.cpython-38.pyc,, -charset_normalizer/__pycache__/version.cpython-38.pyc,, -charset_normalizer/api.py,sha256=euVPmjAMbjpqhEHPjfKtyy1mK52U0TOUBUQgM_Qy6eE,19191 -charset_normalizer/assets/__init__.py,sha256=r7aakPaRIc2FFG2mw2V8NOTvkl25_euKZ3wPf5SAVa4,15222 -charset_normalizer/assets/__pycache__/__init__.cpython-38.pyc,, -charset_normalizer/cd.py,sha256=Pxdkbn4cy0iZF42KTb1FiWIqqKobuz_fDjGwc6JMNBc,10811 -charset_normalizer/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -charset_normalizer/cli/__pycache__/__init__.cpython-38.pyc,, -charset_normalizer/cli/__pycache__/normalizer.cpython-38.pyc,, -charset_normalizer/cli/normalizer.py,sha256=FmD1RXeMpRBg_mjR0MaJhNUpM2qZ8wz2neAE7AayBeg,9521 -charset_normalizer/constant.py,sha256=NgU-pY8JH2a9lkVT8oKwAFmIUYNKOuSBwZgF9MrlNCM,19157 -charset_normalizer/legacy.py,sha256=XKeZOts_HdYQU_Jb3C9ZfOjY2CiUL132k9_nXer8gig,3384 -charset_normalizer/md.py,sha256=pZP8IVpSC82D8INA9Tf_y0ijJSRI-UIncZvLdfTWEd4,17642 -charset_normalizer/models.py,sha256=i68YdlSLTEI3EEBVXq8TLNAbyyjrLC2OWszc-OBAk9I,13167 -charset_normalizer/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -charset_normalizer/utils.py,sha256=ykOznhcAeH-ODLBWJuI7t1nbwa1SAfN_bDYTCJGyh4U,11771 -charset_normalizer/version.py,sha256=_eh2MA3qS__IajlePQxKBmlw6zaBDvPYlLdEgxgIojw,79 diff --git a/.venv/Lib/site-packages/charset_normalizer-2.1.1.dist-info/WHEEL b/.venv/Lib/site-packages/charset_normalizer-2.1.1.dist-info/WHEEL deleted file mode 100644 index becc9a6..0000000 --- a/.venv/Lib/site-packages/charset_normalizer-2.1.1.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: bdist_wheel (0.37.1) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/.venv/Lib/site-packages/charset_normalizer-2.1.1.dist-info/entry_points.txt b/.venv/Lib/site-packages/charset_normalizer-2.1.1.dist-info/entry_points.txt deleted file mode 100644 index a06d360..0000000 --- a/.venv/Lib/site-packages/charset_normalizer-2.1.1.dist-info/entry_points.txt +++ /dev/null @@ -1,2 +0,0 @@ -[console_scripts] -normalizer = charset_normalizer.cli.normalizer:cli_detect diff --git a/.venv/Lib/site-packages/charset_normalizer-2.1.1.dist-info/top_level.txt b/.venv/Lib/site-packages/charset_normalizer-2.1.1.dist-info/top_level.txt deleted file mode 100644 index 66958f0..0000000 --- a/.venv/Lib/site-packages/charset_normalizer-2.1.1.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -charset_normalizer diff --git a/.venv/Lib/site-packages/charset_normalizer/__init__.py b/.venv/Lib/site-packages/charset_normalizer/__init__.py deleted file mode 100644 index 2dcaf56..0000000 --- a/.venv/Lib/site-packages/charset_normalizer/__init__.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- -""" -Charset-Normalizer -~~~~~~~~~~~~~~ -The Real First Universal Charset Detector. -A library that helps you read text from an unknown charset encoding. -Motivated by chardet, This package is trying to resolve the issue by taking a new approach. -All IANA character set names for which the Python core library provides codecs are supported. - -Basic usage: - >>> from charset_normalizer import from_bytes - >>> results = from_bytes('Bсеки човек има право на образование. Oбразованието!'.encode('utf_8')) - >>> best_guess = results.best() - >>> str(best_guess) - 'Bсеки човек има право на образование. Oбразованието!' - -Others methods and usages are available - see the full documentation -at . -:copyright: (c) 2021 by Ahmed TAHRI -:license: MIT, see LICENSE for more details. -""" -import logging - -from .api import from_bytes, from_fp, from_path, normalize -from .legacy import ( - CharsetDetector, - CharsetDoctor, - CharsetNormalizerMatch, - CharsetNormalizerMatches, - detect, -) -from .models import CharsetMatch, CharsetMatches -from .utils import set_logging_handler -from .version import VERSION, __version__ - -__all__ = ( - "from_fp", - "from_path", - "from_bytes", - "normalize", - "detect", - "CharsetMatch", - "CharsetMatches", - "CharsetNormalizerMatch", - "CharsetNormalizerMatches", - "CharsetDetector", - "CharsetDoctor", - "__version__", - "VERSION", - "set_logging_handler", -) - -# Attach a NullHandler to the top level logger by default -# https://docs.python.org/3.3/howto/logging.html#configuring-logging-for-a-library - -logging.getLogger("charset_normalizer").addHandler(logging.NullHandler()) diff --git a/.venv/Lib/site-packages/charset_normalizer/__pycache__/__init__.cpython-38.pyc b/.venv/Lib/site-packages/charset_normalizer/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index a839301..0000000 Binary files a/.venv/Lib/site-packages/charset_normalizer/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/charset_normalizer/__pycache__/api.cpython-38.pyc b/.venv/Lib/site-packages/charset_normalizer/__pycache__/api.cpython-38.pyc deleted file mode 100644 index f942363..0000000 Binary files a/.venv/Lib/site-packages/charset_normalizer/__pycache__/api.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/charset_normalizer/__pycache__/cd.cpython-38.pyc b/.venv/Lib/site-packages/charset_normalizer/__pycache__/cd.cpython-38.pyc deleted file mode 100644 index 50f538c..0000000 Binary files a/.venv/Lib/site-packages/charset_normalizer/__pycache__/cd.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/charset_normalizer/__pycache__/constant.cpython-38.pyc b/.venv/Lib/site-packages/charset_normalizer/__pycache__/constant.cpython-38.pyc deleted file mode 100644 index a8cfadb..0000000 Binary files a/.venv/Lib/site-packages/charset_normalizer/__pycache__/constant.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/charset_normalizer/__pycache__/legacy.cpython-38.pyc b/.venv/Lib/site-packages/charset_normalizer/__pycache__/legacy.cpython-38.pyc deleted file mode 100644 index 0a87744..0000000 Binary files a/.venv/Lib/site-packages/charset_normalizer/__pycache__/legacy.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/charset_normalizer/__pycache__/md.cpython-38.pyc b/.venv/Lib/site-packages/charset_normalizer/__pycache__/md.cpython-38.pyc deleted file mode 100644 index c0b36ab..0000000 Binary files a/.venv/Lib/site-packages/charset_normalizer/__pycache__/md.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/charset_normalizer/__pycache__/models.cpython-38.pyc b/.venv/Lib/site-packages/charset_normalizer/__pycache__/models.cpython-38.pyc deleted file mode 100644 index 939d5f2..0000000 Binary files a/.venv/Lib/site-packages/charset_normalizer/__pycache__/models.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/charset_normalizer/__pycache__/utils.cpython-38.pyc b/.venv/Lib/site-packages/charset_normalizer/__pycache__/utils.cpython-38.pyc deleted file mode 100644 index a755d22..0000000 Binary files a/.venv/Lib/site-packages/charset_normalizer/__pycache__/utils.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/charset_normalizer/__pycache__/version.cpython-38.pyc b/.venv/Lib/site-packages/charset_normalizer/__pycache__/version.cpython-38.pyc deleted file mode 100644 index 32a66a5..0000000 Binary files a/.venv/Lib/site-packages/charset_normalizer/__pycache__/version.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/charset_normalizer/api.py b/.venv/Lib/site-packages/charset_normalizer/api.py deleted file mode 100644 index 72907f9..0000000 --- a/.venv/Lib/site-packages/charset_normalizer/api.py +++ /dev/null @@ -1,584 +0,0 @@ -import logging -import warnings -from os import PathLike -from os.path import basename, splitext -from typing import Any, BinaryIO, List, Optional, Set - -from .cd import ( - coherence_ratio, - encoding_languages, - mb_encoding_languages, - merge_coherence_ratios, -) -from .constant import IANA_SUPPORTED, TOO_BIG_SEQUENCE, TOO_SMALL_SEQUENCE, TRACE -from .md import mess_ratio -from .models import CharsetMatch, CharsetMatches -from .utils import ( - any_specified_encoding, - cut_sequence_chunks, - iana_name, - identify_sig_or_bom, - is_cp_similar, - is_multi_byte_encoding, - should_strip_sig_or_bom, -) - -# Will most likely be controversial -# logging.addLevelName(TRACE, "TRACE") -logger = logging.getLogger("charset_normalizer") -explain_handler = logging.StreamHandler() -explain_handler.setFormatter( - logging.Formatter("%(asctime)s | %(levelname)s | %(message)s") -) - - -def from_bytes( - sequences: bytes, - steps: int = 5, - chunk_size: int = 512, - threshold: float = 0.2, - cp_isolation: Optional[List[str]] = None, - cp_exclusion: Optional[List[str]] = None, - preemptive_behaviour: bool = True, - explain: bool = False, -) -> CharsetMatches: - """ - Given a raw bytes sequence, return the best possibles charset usable to render str objects. - If there is no results, it is a strong indicator that the source is binary/not text. - By default, the process will extract 5 blocs of 512o each to assess the mess and coherence of a given sequence. - And will give up a particular code page after 20% of measured mess. Those criteria are customizable at will. - - The preemptive behavior DOES NOT replace the traditional detection workflow, it prioritize a particular code page - but never take it for granted. Can improve the performance. - - You may want to focus your attention to some code page or/and not others, use cp_isolation and cp_exclusion for that - purpose. - - This function will strip the SIG in the payload/sequence every time except on UTF-16, UTF-32. - By default the library does not setup any handler other than the NullHandler, if you choose to set the 'explain' - toggle to True it will alter the logger configuration to add a StreamHandler that is suitable for debugging. - Custom logging format and handler can be set manually. - """ - - if not isinstance(sequences, (bytearray, bytes)): - raise TypeError( - "Expected object of type bytes or bytearray, got: {0}".format( - type(sequences) - ) - ) - - if explain: - previous_logger_level: int = logger.level - logger.addHandler(explain_handler) - logger.setLevel(TRACE) - - length: int = len(sequences) - - if length == 0: - logger.debug("Encoding detection on empty bytes, assuming utf_8 intention.") - if explain: - logger.removeHandler(explain_handler) - logger.setLevel(previous_logger_level or logging.WARNING) - return CharsetMatches([CharsetMatch(sequences, "utf_8", 0.0, False, [], "")]) - - if cp_isolation is not None: - logger.log( - TRACE, - "cp_isolation is set. use this flag for debugging purpose. " - "limited list of encoding allowed : %s.", - ", ".join(cp_isolation), - ) - cp_isolation = [iana_name(cp, False) for cp in cp_isolation] - else: - cp_isolation = [] - - if cp_exclusion is not None: - logger.log( - TRACE, - "cp_exclusion is set. use this flag for debugging purpose. " - "limited list of encoding excluded : %s.", - ", ".join(cp_exclusion), - ) - cp_exclusion = [iana_name(cp, False) for cp in cp_exclusion] - else: - cp_exclusion = [] - - if length <= (chunk_size * steps): - logger.log( - TRACE, - "override steps (%i) and chunk_size (%i) as content does not fit (%i byte(s) given) parameters.", - steps, - chunk_size, - length, - ) - steps = 1 - chunk_size = length - - if steps > 1 and length / steps < chunk_size: - chunk_size = int(length / steps) - - is_too_small_sequence: bool = len(sequences) < TOO_SMALL_SEQUENCE - is_too_large_sequence: bool = len(sequences) >= TOO_BIG_SEQUENCE - - if is_too_small_sequence: - logger.log( - TRACE, - "Trying to detect encoding from a tiny portion of ({}) byte(s).".format( - length - ), - ) - elif is_too_large_sequence: - logger.log( - TRACE, - "Using lazy str decoding because the payload is quite large, ({}) byte(s).".format( - length - ), - ) - - prioritized_encodings: List[str] = [] - - specified_encoding: Optional[str] = ( - any_specified_encoding(sequences) if preemptive_behaviour else None - ) - - if specified_encoding is not None: - prioritized_encodings.append(specified_encoding) - logger.log( - TRACE, - "Detected declarative mark in sequence. Priority +1 given for %s.", - specified_encoding, - ) - - tested: Set[str] = set() - tested_but_hard_failure: List[str] = [] - tested_but_soft_failure: List[str] = [] - - fallback_ascii: Optional[CharsetMatch] = None - fallback_u8: Optional[CharsetMatch] = None - fallback_specified: Optional[CharsetMatch] = None - - results: CharsetMatches = CharsetMatches() - - sig_encoding, sig_payload = identify_sig_or_bom(sequences) - - if sig_encoding is not None: - prioritized_encodings.append(sig_encoding) - logger.log( - TRACE, - "Detected a SIG or BOM mark on first %i byte(s). Priority +1 given for %s.", - len(sig_payload), - sig_encoding, - ) - - prioritized_encodings.append("ascii") - - if "utf_8" not in prioritized_encodings: - prioritized_encodings.append("utf_8") - - for encoding_iana in prioritized_encodings + IANA_SUPPORTED: - - if cp_isolation and encoding_iana not in cp_isolation: - continue - - if cp_exclusion and encoding_iana in cp_exclusion: - continue - - if encoding_iana in tested: - continue - - tested.add(encoding_iana) - - decoded_payload: Optional[str] = None - bom_or_sig_available: bool = sig_encoding == encoding_iana - strip_sig_or_bom: bool = bom_or_sig_available and should_strip_sig_or_bom( - encoding_iana - ) - - if encoding_iana in {"utf_16", "utf_32"} and not bom_or_sig_available: - logger.log( - TRACE, - "Encoding %s wont be tested as-is because it require a BOM. Will try some sub-encoder LE/BE.", - encoding_iana, - ) - continue - - try: - is_multi_byte_decoder: bool = is_multi_byte_encoding(encoding_iana) - except (ModuleNotFoundError, ImportError): - logger.log( - TRACE, - "Encoding %s does not provide an IncrementalDecoder", - encoding_iana, - ) - continue - - try: - if is_too_large_sequence and is_multi_byte_decoder is False: - str( - sequences[: int(50e4)] - if strip_sig_or_bom is False - else sequences[len(sig_payload) : int(50e4)], - encoding=encoding_iana, - ) - else: - decoded_payload = str( - sequences - if strip_sig_or_bom is False - else sequences[len(sig_payload) :], - encoding=encoding_iana, - ) - except (UnicodeDecodeError, LookupError) as e: - if not isinstance(e, LookupError): - logger.log( - TRACE, - "Code page %s does not fit given bytes sequence at ALL. %s", - encoding_iana, - str(e), - ) - tested_but_hard_failure.append(encoding_iana) - continue - - similar_soft_failure_test: bool = False - - for encoding_soft_failed in tested_but_soft_failure: - if is_cp_similar(encoding_iana, encoding_soft_failed): - similar_soft_failure_test = True - break - - if similar_soft_failure_test: - logger.log( - TRACE, - "%s is deemed too similar to code page %s and was consider unsuited already. Continuing!", - encoding_iana, - encoding_soft_failed, - ) - continue - - r_ = range( - 0 if not bom_or_sig_available else len(sig_payload), - length, - int(length / steps), - ) - - multi_byte_bonus: bool = ( - is_multi_byte_decoder - and decoded_payload is not None - and len(decoded_payload) < length - ) - - if multi_byte_bonus: - logger.log( - TRACE, - "Code page %s is a multi byte encoding table and it appear that at least one character " - "was encoded using n-bytes.", - encoding_iana, - ) - - max_chunk_gave_up: int = int(len(r_) / 4) - - max_chunk_gave_up = max(max_chunk_gave_up, 2) - early_stop_count: int = 0 - lazy_str_hard_failure = False - - md_chunks: List[str] = [] - md_ratios = [] - - try: - for chunk in cut_sequence_chunks( - sequences, - encoding_iana, - r_, - chunk_size, - bom_or_sig_available, - strip_sig_or_bom, - sig_payload, - is_multi_byte_decoder, - decoded_payload, - ): - md_chunks.append(chunk) - - md_ratios.append(mess_ratio(chunk, threshold)) - - if md_ratios[-1] >= threshold: - early_stop_count += 1 - - if (early_stop_count >= max_chunk_gave_up) or ( - bom_or_sig_available and strip_sig_or_bom is False - ): - break - except UnicodeDecodeError as e: # Lazy str loading may have missed something there - logger.log( - TRACE, - "LazyStr Loading: After MD chunk decode, code page %s does not fit given bytes sequence at ALL. %s", - encoding_iana, - str(e), - ) - early_stop_count = max_chunk_gave_up - lazy_str_hard_failure = True - - # We might want to check the sequence again with the whole content - # Only if initial MD tests passes - if ( - not lazy_str_hard_failure - and is_too_large_sequence - and not is_multi_byte_decoder - ): - try: - sequences[int(50e3) :].decode(encoding_iana, errors="strict") - except UnicodeDecodeError as e: - logger.log( - TRACE, - "LazyStr Loading: After final lookup, code page %s does not fit given bytes sequence at ALL. %s", - encoding_iana, - str(e), - ) - tested_but_hard_failure.append(encoding_iana) - continue - - mean_mess_ratio: float = sum(md_ratios) / len(md_ratios) if md_ratios else 0.0 - if mean_mess_ratio >= threshold or early_stop_count >= max_chunk_gave_up: - tested_but_soft_failure.append(encoding_iana) - logger.log( - TRACE, - "%s was excluded because of initial chaos probing. Gave up %i time(s). " - "Computed mean chaos is %f %%.", - encoding_iana, - early_stop_count, - round(mean_mess_ratio * 100, ndigits=3), - ) - # Preparing those fallbacks in case we got nothing. - if ( - encoding_iana in ["ascii", "utf_8", specified_encoding] - and not lazy_str_hard_failure - ): - fallback_entry = CharsetMatch( - sequences, encoding_iana, threshold, False, [], decoded_payload - ) - if encoding_iana == specified_encoding: - fallback_specified = fallback_entry - elif encoding_iana == "ascii": - fallback_ascii = fallback_entry - else: - fallback_u8 = fallback_entry - continue - - logger.log( - TRACE, - "%s passed initial chaos probing. Mean measured chaos is %f %%", - encoding_iana, - round(mean_mess_ratio * 100, ndigits=3), - ) - - if not is_multi_byte_decoder: - target_languages: List[str] = encoding_languages(encoding_iana) - else: - target_languages = mb_encoding_languages(encoding_iana) - - if target_languages: - logger.log( - TRACE, - "{} should target any language(s) of {}".format( - encoding_iana, str(target_languages) - ), - ) - - cd_ratios = [] - - # We shall skip the CD when its about ASCII - # Most of the time its not relevant to run "language-detection" on it. - if encoding_iana != "ascii": - for chunk in md_chunks: - chunk_languages = coherence_ratio( - chunk, 0.1, ",".join(target_languages) if target_languages else None - ) - - cd_ratios.append(chunk_languages) - - cd_ratios_merged = merge_coherence_ratios(cd_ratios) - - if cd_ratios_merged: - logger.log( - TRACE, - "We detected language {} using {}".format( - cd_ratios_merged, encoding_iana - ), - ) - - results.append( - CharsetMatch( - sequences, - encoding_iana, - mean_mess_ratio, - bom_or_sig_available, - cd_ratios_merged, - decoded_payload, - ) - ) - - if ( - encoding_iana in [specified_encoding, "ascii", "utf_8"] - and mean_mess_ratio < 0.1 - ): - logger.debug( - "Encoding detection: %s is most likely the one.", encoding_iana - ) - if explain: - logger.removeHandler(explain_handler) - logger.setLevel(previous_logger_level) - return CharsetMatches([results[encoding_iana]]) - - if encoding_iana == sig_encoding: - logger.debug( - "Encoding detection: %s is most likely the one as we detected a BOM or SIG within " - "the beginning of the sequence.", - encoding_iana, - ) - if explain: - logger.removeHandler(explain_handler) - logger.setLevel(previous_logger_level) - return CharsetMatches([results[encoding_iana]]) - - if len(results) == 0: - if fallback_u8 or fallback_ascii or fallback_specified: - logger.log( - TRACE, - "Nothing got out of the detection process. Using ASCII/UTF-8/Specified fallback.", - ) - - if fallback_specified: - logger.debug( - "Encoding detection: %s will be used as a fallback match", - fallback_specified.encoding, - ) - results.append(fallback_specified) - elif ( - (fallback_u8 and fallback_ascii is None) - or ( - fallback_u8 - and fallback_ascii - and fallback_u8.fingerprint != fallback_ascii.fingerprint - ) - or (fallback_u8 is not None) - ): - logger.debug("Encoding detection: utf_8 will be used as a fallback match") - results.append(fallback_u8) - elif fallback_ascii: - logger.debug("Encoding detection: ascii will be used as a fallback match") - results.append(fallback_ascii) - - if results: - logger.debug( - "Encoding detection: Found %s as plausible (best-candidate) for content. With %i alternatives.", - results.best().encoding, # type: ignore - len(results) - 1, - ) - else: - logger.debug("Encoding detection: Unable to determine any suitable charset.") - - if explain: - logger.removeHandler(explain_handler) - logger.setLevel(previous_logger_level) - - return results - - -def from_fp( - fp: BinaryIO, - steps: int = 5, - chunk_size: int = 512, - threshold: float = 0.20, - cp_isolation: Optional[List[str]] = None, - cp_exclusion: Optional[List[str]] = None, - preemptive_behaviour: bool = True, - explain: bool = False, -) -> CharsetMatches: - """ - Same thing than the function from_bytes but using a file pointer that is already ready. - Will not close the file pointer. - """ - return from_bytes( - fp.read(), - steps, - chunk_size, - threshold, - cp_isolation, - cp_exclusion, - preemptive_behaviour, - explain, - ) - - -def from_path( - path: "PathLike[Any]", - steps: int = 5, - chunk_size: int = 512, - threshold: float = 0.20, - cp_isolation: Optional[List[str]] = None, - cp_exclusion: Optional[List[str]] = None, - preemptive_behaviour: bool = True, - explain: bool = False, -) -> CharsetMatches: - """ - Same thing than the function from_bytes but with one extra step. Opening and reading given file path in binary mode. - Can raise IOError. - """ - with open(path, "rb") as fp: - return from_fp( - fp, - steps, - chunk_size, - threshold, - cp_isolation, - cp_exclusion, - preemptive_behaviour, - explain, - ) - - -def normalize( - path: "PathLike[Any]", - steps: int = 5, - chunk_size: int = 512, - threshold: float = 0.20, - cp_isolation: Optional[List[str]] = None, - cp_exclusion: Optional[List[str]] = None, - preemptive_behaviour: bool = True, -) -> CharsetMatch: - """ - Take a (text-based) file path and try to create another file next to it, this time using UTF-8. - """ - warnings.warn( - "normalize is deprecated and will be removed in 3.0", - DeprecationWarning, - ) - - results = from_path( - path, - steps, - chunk_size, - threshold, - cp_isolation, - cp_exclusion, - preemptive_behaviour, - ) - - filename = basename(path) - target_extensions = list(splitext(filename)) - - if len(results) == 0: - raise IOError( - 'Unable to normalize "{}", no encoding charset seems to fit.'.format( - filename - ) - ) - - result = results.best() - - target_extensions[0] += "-" + result.encoding # type: ignore - - with open( - "{}".format(str(path).replace(filename, "".join(target_extensions))), "wb" - ) as fp: - fp.write(result.output()) # type: ignore - - return result # type: ignore diff --git a/.venv/Lib/site-packages/charset_normalizer/assets/__init__.py b/.venv/Lib/site-packages/charset_normalizer/assets/__init__.py deleted file mode 100644 index 3c33ba3..0000000 --- a/.venv/Lib/site-packages/charset_normalizer/assets/__init__.py +++ /dev/null @@ -1,1122 +0,0 @@ -# -*- coding: utf-8 -*- -from typing import Dict, List - -FREQUENCIES: Dict[str, List[str]] = { - "English": [ - "e", - "a", - "t", - "i", - "o", - "n", - "s", - "r", - "h", - "l", - "d", - "c", - "u", - "m", - "f", - "p", - "g", - "w", - "y", - "b", - "v", - "k", - "x", - "j", - "z", - "q", - ], - "German": [ - "e", - "n", - "i", - "r", - "s", - "t", - "a", - "d", - "h", - "u", - "l", - "g", - "o", - "c", - "m", - "b", - "f", - "k", - "w", - "z", - "p", - "v", - "ü", - "ä", - "ö", - "j", - ], - "French": [ - "e", - "a", - "s", - "n", - "i", - "t", - "r", - "l", - "u", - "o", - "d", - "c", - "p", - "m", - "é", - "v", - "g", - "f", - "b", - "h", - "q", - "à", - "x", - "è", - "y", - "j", - ], - "Dutch": [ - "e", - "n", - "a", - "i", - "r", - "t", - "o", - "d", - "s", - "l", - "g", - "h", - "v", - "m", - "u", - "k", - "c", - "p", - "b", - "w", - "j", - "z", - "f", - "y", - "x", - "ë", - ], - "Italian": [ - "e", - "i", - "a", - "o", - "n", - "l", - "t", - "r", - "s", - "c", - "d", - "u", - "p", - "m", - "g", - "v", - "f", - "b", - "z", - "h", - "q", - "è", - "à", - "k", - "y", - "ò", - ], - "Polish": [ - "a", - "i", - "o", - "e", - "n", - "r", - "z", - "w", - "s", - "c", - "t", - "k", - "y", - "d", - "p", - "m", - "u", - "l", - "j", - "ł", - "g", - "b", - "h", - "ą", - "ę", - "ó", - ], - "Spanish": [ - "e", - "a", - "o", - "n", - "s", - "r", - "i", - "l", - "d", - "t", - "c", - "u", - "m", - "p", - "b", - "g", - "v", - "f", - "y", - "ó", - "h", - "q", - "í", - "j", - "z", - "á", - ], - "Russian": [ - "о", - "а", - "е", - "и", - "н", - "с", - "т", - "р", - "в", - "л", - "к", - "м", - "д", - "п", - "у", - "г", - "я", - "ы", - "з", - "б", - "й", - "ь", - "ч", - "х", - "ж", - "ц", - ], - "Japanese": [ - "の", - "に", - "る", - "た", - "は", - "ー", - "と", - "し", - "を", - "で", - "て", - "が", - "い", - "ン", - "れ", - "な", - "年", - "ス", - "っ", - "ル", - "か", - "ら", - "あ", - "さ", - "も", - "り", - ], - "Portuguese": [ - "a", - "e", - "o", - "s", - "i", - "r", - "d", - "n", - "t", - "m", - "u", - "c", - "l", - "p", - "g", - "v", - "b", - "f", - "h", - "ã", - "q", - "é", - "ç", - "á", - "z", - "í", - ], - "Swedish": [ - "e", - "a", - "n", - "r", - "t", - "s", - "i", - "l", - "d", - "o", - "m", - "k", - "g", - "v", - "h", - "f", - "u", - "p", - "ä", - "c", - "b", - "ö", - "å", - "y", - "j", - "x", - ], - "Chinese": [ - "的", - "一", - "是", - "不", - "了", - "在", - "人", - "有", - "我", - "他", - "这", - "个", - "们", - "中", - "来", - "上", - "大", - "为", - "和", - "国", - "地", - "到", - "以", - "说", - "时", - "要", - "就", - "出", - "会", - ], - "Ukrainian": [ - "о", - "а", - "н", - "і", - "и", - "р", - "в", - "т", - "е", - "с", - "к", - "л", - "у", - "д", - "м", - "п", - "з", - "я", - "ь", - "б", - "г", - "й", - "ч", - "х", - "ц", - "ї", - ], - "Norwegian": [ - "e", - "r", - "n", - "t", - "a", - "s", - "i", - "o", - "l", - "d", - "g", - "k", - "m", - "v", - "f", - "p", - "u", - "b", - "h", - "å", - "y", - "j", - "ø", - "c", - "æ", - "w", - ], - "Finnish": [ - "a", - "i", - "n", - "t", - "e", - "s", - "l", - "o", - "u", - "k", - "ä", - "m", - "r", - "v", - "j", - "h", - "p", - "y", - "d", - "ö", - "g", - "c", - "b", - "f", - "w", - "z", - ], - "Vietnamese": [ - "n", - "h", - "t", - "i", - "c", - "g", - "a", - "o", - "u", - "m", - "l", - "r", - "à", - "đ", - "s", - "e", - "v", - "p", - "b", - "y", - "ư", - "d", - "á", - "k", - "ộ", - "ế", - ], - "Czech": [ - "o", - "e", - "a", - "n", - "t", - "s", - "i", - "l", - "v", - "r", - "k", - "d", - "u", - "m", - "p", - "í", - "c", - "h", - "z", - "á", - "y", - "j", - "b", - "ě", - "é", - "ř", - ], - "Hungarian": [ - "e", - "a", - "t", - "l", - "s", - "n", - "k", - "r", - "i", - "o", - "z", - "á", - "é", - "g", - "m", - "b", - "y", - "v", - "d", - "h", - "u", - "p", - "j", - "ö", - "f", - "c", - ], - "Korean": [ - "이", - "다", - "에", - "의", - "는", - "로", - "하", - "을", - "가", - "고", - "지", - "서", - "한", - "은", - "기", - "으", - "년", - "대", - "사", - "시", - "를", - "리", - "도", - "인", - "스", - "일", - ], - "Indonesian": [ - "a", - "n", - "e", - "i", - "r", - "t", - "u", - "s", - "d", - "k", - "m", - "l", - "g", - "p", - "b", - "o", - "h", - "y", - "j", - "c", - "w", - "f", - "v", - "z", - "x", - "q", - ], - "Turkish": [ - "a", - "e", - "i", - "n", - "r", - "l", - "ı", - "k", - "d", - "t", - "s", - "m", - "y", - "u", - "o", - "b", - "ü", - "ş", - "v", - "g", - "z", - "h", - "c", - "p", - "ç", - "ğ", - ], - "Romanian": [ - "e", - "i", - "a", - "r", - "n", - "t", - "u", - "l", - "o", - "c", - "s", - "d", - "p", - "m", - "ă", - "f", - "v", - "î", - "g", - "b", - "ș", - "ț", - "z", - "h", - "â", - "j", - ], - "Farsi": [ - "ا", - "ی", - "ر", - "د", - "ن", - "ه", - "و", - "م", - "ت", - "ب", - "س", - "ل", - "ک", - "ش", - "ز", - "ف", - "گ", - "ع", - "خ", - "ق", - "ج", - "آ", - "پ", - "ح", - "ط", - "ص", - ], - "Arabic": [ - "ا", - "ل", - "ي", - "م", - "و", - "ن", - "ر", - "ت", - "ب", - "ة", - "ع", - "د", - "س", - "ف", - "ه", - "ك", - "ق", - "أ", - "ح", - "ج", - "ش", - "ط", - "ص", - "ى", - "خ", - "إ", - ], - "Danish": [ - "e", - "r", - "n", - "t", - "a", - "i", - "s", - "d", - "l", - "o", - "g", - "m", - "k", - "f", - "v", - "u", - "b", - "h", - "p", - "å", - "y", - "ø", - "æ", - "c", - "j", - "w", - ], - "Serbian": [ - "а", - "и", - "о", - "е", - "н", - "р", - "с", - "у", - "т", - "к", - "ј", - "в", - "д", - "м", - "п", - "л", - "г", - "з", - "б", - "a", - "i", - "e", - "o", - "n", - "ц", - "ш", - ], - "Lithuanian": [ - "i", - "a", - "s", - "o", - "r", - "e", - "t", - "n", - "u", - "k", - "m", - "l", - "p", - "v", - "d", - "j", - "g", - "ė", - "b", - "y", - "ų", - "š", - "ž", - "c", - "ą", - "į", - ], - "Slovene": [ - "e", - "a", - "i", - "o", - "n", - "r", - "s", - "l", - "t", - "j", - "v", - "k", - "d", - "p", - "m", - "u", - "z", - "b", - "g", - "h", - "č", - "c", - "š", - "ž", - "f", - "y", - ], - "Slovak": [ - "o", - "a", - "e", - "n", - "i", - "r", - "v", - "t", - "s", - "l", - "k", - "d", - "m", - "p", - "u", - "c", - "h", - "j", - "b", - "z", - "á", - "y", - "ý", - "í", - "č", - "é", - ], - "Hebrew": [ - "י", - "ו", - "ה", - "ל", - "ר", - "ב", - "ת", - "מ", - "א", - "ש", - "נ", - "ע", - "ם", - "ד", - "ק", - "ח", - "פ", - "ס", - "כ", - "ג", - "ט", - "צ", - "ן", - "ז", - "ך", - ], - "Bulgarian": [ - "а", - "и", - "о", - "е", - "н", - "т", - "р", - "с", - "в", - "л", - "к", - "д", - "п", - "м", - "з", - "г", - "я", - "ъ", - "у", - "б", - "ч", - "ц", - "й", - "ж", - "щ", - "х", - ], - "Croatian": [ - "a", - "i", - "o", - "e", - "n", - "r", - "j", - "s", - "t", - "u", - "k", - "l", - "v", - "d", - "m", - "p", - "g", - "z", - "b", - "c", - "č", - "h", - "š", - "ž", - "ć", - "f", - ], - "Hindi": [ - "क", - "र", - "स", - "न", - "त", - "म", - "ह", - "प", - "य", - "ल", - "व", - "ज", - "द", - "ग", - "ब", - "श", - "ट", - "अ", - "ए", - "थ", - "भ", - "ड", - "च", - "ध", - "ष", - "इ", - ], - "Estonian": [ - "a", - "i", - "e", - "s", - "t", - "l", - "u", - "n", - "o", - "k", - "r", - "d", - "m", - "v", - "g", - "p", - "j", - "h", - "ä", - "b", - "õ", - "ü", - "f", - "c", - "ö", - "y", - ], - "Simple English": [ - "e", - "a", - "t", - "i", - "o", - "n", - "s", - "r", - "h", - "l", - "d", - "c", - "m", - "u", - "f", - "p", - "g", - "w", - "b", - "y", - "v", - "k", - "j", - "x", - "z", - "q", - ], - "Thai": [ - "า", - "น", - "ร", - "อ", - "ก", - "เ", - "ง", - "ม", - "ย", - "ล", - "ว", - "ด", - "ท", - "ส", - "ต", - "ะ", - "ป", - "บ", - "ค", - "ห", - "แ", - "จ", - "พ", - "ช", - "ข", - "ใ", - ], - "Greek": [ - "α", - "τ", - "ο", - "ι", - "ε", - "ν", - "ρ", - "σ", - "κ", - "η", - "π", - "ς", - "υ", - "μ", - "λ", - "ί", - "ό", - "ά", - "γ", - "έ", - "δ", - "ή", - "ω", - "χ", - "θ", - "ύ", - ], - "Tamil": [ - "க", - "த", - "ப", - "ட", - "ர", - "ம", - "ல", - "ன", - "வ", - "ற", - "ய", - "ள", - "ச", - "ந", - "இ", - "ண", - "அ", - "ஆ", - "ழ", - "ங", - "எ", - "உ", - "ஒ", - "ஸ", - ], - "Classical Chinese": [ - "之", - "年", - "為", - "也", - "以", - "一", - "人", - "其", - "者", - "國", - "有", - "二", - "十", - "於", - "曰", - "三", - "不", - "大", - "而", - "子", - "中", - "五", - "四", - ], - "Kazakh": [ - "а", - "ы", - "е", - "н", - "т", - "р", - "л", - "і", - "д", - "с", - "м", - "қ", - "к", - "о", - "б", - "и", - "у", - "ғ", - "ж", - "ң", - "з", - "ш", - "й", - "п", - "г", - "ө", - ], -} diff --git a/.venv/Lib/site-packages/charset_normalizer/assets/__pycache__/__init__.cpython-38.pyc b/.venv/Lib/site-packages/charset_normalizer/assets/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index 422411e..0000000 Binary files a/.venv/Lib/site-packages/charset_normalizer/assets/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/charset_normalizer/cd.py b/.venv/Lib/site-packages/charset_normalizer/cd.py deleted file mode 100644 index ee4b742..0000000 --- a/.venv/Lib/site-packages/charset_normalizer/cd.py +++ /dev/null @@ -1,339 +0,0 @@ -import importlib -from codecs import IncrementalDecoder -from collections import Counter -from functools import lru_cache -from typing import Counter as TypeCounter, Dict, List, Optional, Tuple - -from .assets import FREQUENCIES -from .constant import KO_NAMES, LANGUAGE_SUPPORTED_COUNT, TOO_SMALL_SEQUENCE, ZH_NAMES -from .md import is_suspiciously_successive_range -from .models import CoherenceMatches -from .utils import ( - is_accentuated, - is_latin, - is_multi_byte_encoding, - is_unicode_range_secondary, - unicode_range, -) - - -def encoding_unicode_range(iana_name: str) -> List[str]: - """ - Return associated unicode ranges in a single byte code page. - """ - if is_multi_byte_encoding(iana_name): - raise IOError("Function not supported on multi-byte code page") - - decoder = importlib.import_module( - "encodings.{}".format(iana_name) - ).IncrementalDecoder - - p: IncrementalDecoder = decoder(errors="ignore") - seen_ranges: Dict[str, int] = {} - character_count: int = 0 - - for i in range(0x40, 0xFF): - chunk: str = p.decode(bytes([i])) - - if chunk: - character_range: Optional[str] = unicode_range(chunk) - - if character_range is None: - continue - - if is_unicode_range_secondary(character_range) is False: - if character_range not in seen_ranges: - seen_ranges[character_range] = 0 - seen_ranges[character_range] += 1 - character_count += 1 - - return sorted( - [ - character_range - for character_range in seen_ranges - if seen_ranges[character_range] / character_count >= 0.15 - ] - ) - - -def unicode_range_languages(primary_range: str) -> List[str]: - """ - Return inferred languages used with a unicode range. - """ - languages: List[str] = [] - - for language, characters in FREQUENCIES.items(): - for character in characters: - if unicode_range(character) == primary_range: - languages.append(language) - break - - return languages - - -@lru_cache() -def encoding_languages(iana_name: str) -> List[str]: - """ - Single-byte encoding language association. Some code page are heavily linked to particular language(s). - This function does the correspondence. - """ - unicode_ranges: List[str] = encoding_unicode_range(iana_name) - primary_range: Optional[str] = None - - for specified_range in unicode_ranges: - if "Latin" not in specified_range: - primary_range = specified_range - break - - if primary_range is None: - return ["Latin Based"] - - return unicode_range_languages(primary_range) - - -@lru_cache() -def mb_encoding_languages(iana_name: str) -> List[str]: - """ - Multi-byte encoding language association. Some code page are heavily linked to particular language(s). - This function does the correspondence. - """ - if ( - iana_name.startswith("shift_") - or iana_name.startswith("iso2022_jp") - or iana_name.startswith("euc_j") - or iana_name == "cp932" - ): - return ["Japanese"] - if iana_name.startswith("gb") or iana_name in ZH_NAMES: - return ["Chinese", "Classical Chinese"] - if iana_name.startswith("iso2022_kr") or iana_name in KO_NAMES: - return ["Korean"] - - return [] - - -@lru_cache(maxsize=LANGUAGE_SUPPORTED_COUNT) -def get_target_features(language: str) -> Tuple[bool, bool]: - """ - Determine main aspects from a supported language if it contains accents and if is pure Latin. - """ - target_have_accents: bool = False - target_pure_latin: bool = True - - for character in FREQUENCIES[language]: - if not target_have_accents and is_accentuated(character): - target_have_accents = True - if target_pure_latin and is_latin(character) is False: - target_pure_latin = False - - return target_have_accents, target_pure_latin - - -def alphabet_languages( - characters: List[str], ignore_non_latin: bool = False -) -> List[str]: - """ - Return associated languages associated to given characters. - """ - languages: List[Tuple[str, float]] = [] - - source_have_accents = any(is_accentuated(character) for character in characters) - - for language, language_characters in FREQUENCIES.items(): - - target_have_accents, target_pure_latin = get_target_features(language) - - if ignore_non_latin and target_pure_latin is False: - continue - - if target_have_accents is False and source_have_accents: - continue - - character_count: int = len(language_characters) - - character_match_count: int = len( - [c for c in language_characters if c in characters] - ) - - ratio: float = character_match_count / character_count - - if ratio >= 0.2: - languages.append((language, ratio)) - - languages = sorted(languages, key=lambda x: x[1], reverse=True) - - return [compatible_language[0] for compatible_language in languages] - - -def characters_popularity_compare( - language: str, ordered_characters: List[str] -) -> float: - """ - Determine if a ordered characters list (by occurrence from most appearance to rarest) match a particular language. - The result is a ratio between 0. (absolutely no correspondence) and 1. (near perfect fit). - Beware that is function is not strict on the match in order to ease the detection. (Meaning close match is 1.) - """ - if language not in FREQUENCIES: - raise ValueError("{} not available".format(language)) - - character_approved_count: int = 0 - FREQUENCIES_language_set = set(FREQUENCIES[language]) - - for character in ordered_characters: - if character not in FREQUENCIES_language_set: - continue - - characters_before_source: List[str] = FREQUENCIES[language][ - 0 : FREQUENCIES[language].index(character) - ] - characters_after_source: List[str] = FREQUENCIES[language][ - FREQUENCIES[language].index(character) : - ] - characters_before: List[str] = ordered_characters[ - 0 : ordered_characters.index(character) - ] - characters_after: List[str] = ordered_characters[ - ordered_characters.index(character) : - ] - - before_match_count: int = len( - set(characters_before) & set(characters_before_source) - ) - - after_match_count: int = len( - set(characters_after) & set(characters_after_source) - ) - - if len(characters_before_source) == 0 and before_match_count <= 4: - character_approved_count += 1 - continue - - if len(characters_after_source) == 0 and after_match_count <= 4: - character_approved_count += 1 - continue - - if ( - before_match_count / len(characters_before_source) >= 0.4 - or after_match_count / len(characters_after_source) >= 0.4 - ): - character_approved_count += 1 - continue - - return character_approved_count / len(ordered_characters) - - -def alpha_unicode_split(decoded_sequence: str) -> List[str]: - """ - Given a decoded text sequence, return a list of str. Unicode range / alphabet separation. - Ex. a text containing English/Latin with a bit a Hebrew will return two items in the resulting list; - One containing the latin letters and the other hebrew. - """ - layers: Dict[str, str] = {} - - for character in decoded_sequence: - if character.isalpha() is False: - continue - - character_range: Optional[str] = unicode_range(character) - - if character_range is None: - continue - - layer_target_range: Optional[str] = None - - for discovered_range in layers: - if ( - is_suspiciously_successive_range(discovered_range, character_range) - is False - ): - layer_target_range = discovered_range - break - - if layer_target_range is None: - layer_target_range = character_range - - if layer_target_range not in layers: - layers[layer_target_range] = character.lower() - continue - - layers[layer_target_range] += character.lower() - - return list(layers.values()) - - -def merge_coherence_ratios(results: List[CoherenceMatches]) -> CoherenceMatches: - """ - This function merge results previously given by the function coherence_ratio. - The return type is the same as coherence_ratio. - """ - per_language_ratios: Dict[str, List[float]] = {} - for result in results: - for sub_result in result: - language, ratio = sub_result - if language not in per_language_ratios: - per_language_ratios[language] = [ratio] - continue - per_language_ratios[language].append(ratio) - - merge = [ - ( - language, - round( - sum(per_language_ratios[language]) / len(per_language_ratios[language]), - 4, - ), - ) - for language in per_language_ratios - ] - - return sorted(merge, key=lambda x: x[1], reverse=True) - - -@lru_cache(maxsize=2048) -def coherence_ratio( - decoded_sequence: str, threshold: float = 0.1, lg_inclusion: Optional[str] = None -) -> CoherenceMatches: - """ - Detect ANY language that can be identified in given sequence. The sequence will be analysed by layers. - A layer = Character extraction by alphabets/ranges. - """ - - results: List[Tuple[str, float]] = [] - ignore_non_latin: bool = False - - sufficient_match_count: int = 0 - - lg_inclusion_list = lg_inclusion.split(",") if lg_inclusion is not None else [] - if "Latin Based" in lg_inclusion_list: - ignore_non_latin = True - lg_inclusion_list.remove("Latin Based") - - for layer in alpha_unicode_split(decoded_sequence): - sequence_frequencies: TypeCounter[str] = Counter(layer) - most_common = sequence_frequencies.most_common() - - character_count: int = sum(o for c, o in most_common) - - if character_count <= TOO_SMALL_SEQUENCE: - continue - - popular_character_ordered: List[str] = [c for c, o in most_common] - - for language in lg_inclusion_list or alphabet_languages( - popular_character_ordered, ignore_non_latin - ): - ratio: float = characters_popularity_compare( - language, popular_character_ordered - ) - - if ratio < threshold: - continue - elif ratio >= 0.8: - sufficient_match_count += 1 - - results.append((language, round(ratio, 4))) - - if sufficient_match_count >= 3: - break - - return sorted(results, key=lambda x: x[1], reverse=True) diff --git a/.venv/Lib/site-packages/charset_normalizer/cli/__init__.py b/.venv/Lib/site-packages/charset_normalizer/cli/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/.venv/Lib/site-packages/charset_normalizer/cli/__pycache__/__init__.cpython-38.pyc b/.venv/Lib/site-packages/charset_normalizer/cli/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index 29e3c55..0000000 Binary files a/.venv/Lib/site-packages/charset_normalizer/cli/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/charset_normalizer/cli/__pycache__/normalizer.cpython-38.pyc b/.venv/Lib/site-packages/charset_normalizer/cli/__pycache__/normalizer.cpython-38.pyc deleted file mode 100644 index b7b5fe8..0000000 Binary files a/.venv/Lib/site-packages/charset_normalizer/cli/__pycache__/normalizer.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/charset_normalizer/cli/normalizer.py b/.venv/Lib/site-packages/charset_normalizer/cli/normalizer.py deleted file mode 100644 index b8b652a..0000000 --- a/.venv/Lib/site-packages/charset_normalizer/cli/normalizer.py +++ /dev/null @@ -1,295 +0,0 @@ -import argparse -import sys -from json import dumps -from os.path import abspath -from platform import python_version -from typing import List, Optional - -try: - from unicodedata2 import unidata_version -except ImportError: - from unicodedata import unidata_version - -from charset_normalizer import from_fp -from charset_normalizer.models import CliDetectionResult -from charset_normalizer.version import __version__ - - -def query_yes_no(question: str, default: str = "yes") -> bool: - """Ask a yes/no question via input() and return their answer. - - "question" is a string that is presented to the user. - "default" is the presumed answer if the user just hits . - It must be "yes" (the default), "no" or None (meaning - an answer is required of the user). - - The "answer" return value is True for "yes" or False for "no". - - Credit goes to (c) https://stackoverflow.com/questions/3041986/apt-command-line-interface-like-yes-no-input - """ - valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} - if default is None: - prompt = " [y/n] " - elif default == "yes": - prompt = " [Y/n] " - elif default == "no": - prompt = " [y/N] " - else: - raise ValueError("invalid default answer: '%s'" % default) - - while True: - sys.stdout.write(question + prompt) - choice = input().lower() - if default is not None and choice == "": - return valid[default] - elif choice in valid: - return valid[choice] - else: - sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n") - - -def cli_detect(argv: Optional[List[str]] = None) -> int: - """ - CLI assistant using ARGV and ArgumentParser - :param argv: - :return: 0 if everything is fine, anything else equal trouble - """ - parser = argparse.ArgumentParser( - description="The Real First Universal Charset Detector. " - "Discover originating encoding used on text file. " - "Normalize text to unicode." - ) - - parser.add_argument( - "files", type=argparse.FileType("rb"), nargs="+", help="File(s) to be analysed" - ) - parser.add_argument( - "-v", - "--verbose", - action="store_true", - default=False, - dest="verbose", - help="Display complementary information about file if any. " - "Stdout will contain logs about the detection process.", - ) - parser.add_argument( - "-a", - "--with-alternative", - action="store_true", - default=False, - dest="alternatives", - help="Output complementary possibilities if any. Top-level JSON WILL be a list.", - ) - parser.add_argument( - "-n", - "--normalize", - action="store_true", - default=False, - dest="normalize", - help="Permit to normalize input file. If not set, program does not write anything.", - ) - parser.add_argument( - "-m", - "--minimal", - action="store_true", - default=False, - dest="minimal", - help="Only output the charset detected to STDOUT. Disabling JSON output.", - ) - parser.add_argument( - "-r", - "--replace", - action="store_true", - default=False, - dest="replace", - help="Replace file when trying to normalize it instead of creating a new one.", - ) - parser.add_argument( - "-f", - "--force", - action="store_true", - default=False, - dest="force", - help="Replace file without asking if you are sure, use this flag with caution.", - ) - parser.add_argument( - "-t", - "--threshold", - action="store", - default=0.2, - type=float, - dest="threshold", - help="Define a custom maximum amount of chaos allowed in decoded content. 0. <= chaos <= 1.", - ) - parser.add_argument( - "--version", - action="version", - version="Charset-Normalizer {} - Python {} - Unicode {}".format( - __version__, python_version(), unidata_version - ), - help="Show version information and exit.", - ) - - args = parser.parse_args(argv) - - if args.replace is True and args.normalize is False: - print("Use --replace in addition of --normalize only.", file=sys.stderr) - return 1 - - if args.force is True and args.replace is False: - print("Use --force in addition of --replace only.", file=sys.stderr) - return 1 - - if args.threshold < 0.0 or args.threshold > 1.0: - print("--threshold VALUE should be between 0. AND 1.", file=sys.stderr) - return 1 - - x_ = [] - - for my_file in args.files: - - matches = from_fp(my_file, threshold=args.threshold, explain=args.verbose) - - best_guess = matches.best() - - if best_guess is None: - print( - 'Unable to identify originating encoding for "{}". {}'.format( - my_file.name, - "Maybe try increasing maximum amount of chaos." - if args.threshold < 1.0 - else "", - ), - file=sys.stderr, - ) - x_.append( - CliDetectionResult( - abspath(my_file.name), - None, - [], - [], - "Unknown", - [], - False, - 1.0, - 0.0, - None, - True, - ) - ) - else: - x_.append( - CliDetectionResult( - abspath(my_file.name), - best_guess.encoding, - best_guess.encoding_aliases, - [ - cp - for cp in best_guess.could_be_from_charset - if cp != best_guess.encoding - ], - best_guess.language, - best_guess.alphabets, - best_guess.bom, - best_guess.percent_chaos, - best_guess.percent_coherence, - None, - True, - ) - ) - - if len(matches) > 1 and args.alternatives: - for el in matches: - if el != best_guess: - x_.append( - CliDetectionResult( - abspath(my_file.name), - el.encoding, - el.encoding_aliases, - [ - cp - for cp in el.could_be_from_charset - if cp != el.encoding - ], - el.language, - el.alphabets, - el.bom, - el.percent_chaos, - el.percent_coherence, - None, - False, - ) - ) - - if args.normalize is True: - - if best_guess.encoding.startswith("utf") is True: - print( - '"{}" file does not need to be normalized, as it already came from unicode.'.format( - my_file.name - ), - file=sys.stderr, - ) - if my_file.closed is False: - my_file.close() - continue - - o_: List[str] = my_file.name.split(".") - - if args.replace is False: - o_.insert(-1, best_guess.encoding) - if my_file.closed is False: - my_file.close() - elif ( - args.force is False - and query_yes_no( - 'Are you sure to normalize "{}" by replacing it ?'.format( - my_file.name - ), - "no", - ) - is False - ): - if my_file.closed is False: - my_file.close() - continue - - try: - x_[0].unicode_path = abspath("./{}".format(".".join(o_))) - - with open(x_[0].unicode_path, "w", encoding="utf-8") as fp: - fp.write(str(best_guess)) - except IOError as e: - print(str(e), file=sys.stderr) - if my_file.closed is False: - my_file.close() - return 2 - - if my_file.closed is False: - my_file.close() - - if args.minimal is False: - print( - dumps( - [el.__dict__ for el in x_] if len(x_) > 1 else x_[0].__dict__, - ensure_ascii=True, - indent=4, - ) - ) - else: - for my_file in args.files: - print( - ", ".join( - [ - el.encoding or "undefined" - for el in x_ - if el.path == abspath(my_file.name) - ] - ) - ) - - return 0 - - -if __name__ == "__main__": - cli_detect() diff --git a/.venv/Lib/site-packages/charset_normalizer/constant.py b/.venv/Lib/site-packages/charset_normalizer/constant.py deleted file mode 100644 index ac840c4..0000000 --- a/.venv/Lib/site-packages/charset_normalizer/constant.py +++ /dev/null @@ -1,497 +0,0 @@ -from codecs import BOM_UTF8, BOM_UTF16_BE, BOM_UTF16_LE, BOM_UTF32_BE, BOM_UTF32_LE -from encodings.aliases import aliases -from re import IGNORECASE, compile as re_compile -from typing import Dict, List, Set, Union - -from .assets import FREQUENCIES - -# Contain for each eligible encoding a list of/item bytes SIG/BOM -ENCODING_MARKS: Dict[str, Union[bytes, List[bytes]]] = { - "utf_8": BOM_UTF8, - "utf_7": [ - b"\x2b\x2f\x76\x38", - b"\x2b\x2f\x76\x39", - b"\x2b\x2f\x76\x2b", - b"\x2b\x2f\x76\x2f", - b"\x2b\x2f\x76\x38\x2d", - ], - "gb18030": b"\x84\x31\x95\x33", - "utf_32": [BOM_UTF32_BE, BOM_UTF32_LE], - "utf_16": [BOM_UTF16_BE, BOM_UTF16_LE], -} - -TOO_SMALL_SEQUENCE: int = 32 -TOO_BIG_SEQUENCE: int = int(10e6) - -UTF8_MAXIMAL_ALLOCATION: int = 1112064 - -UNICODE_RANGES_COMBINED: Dict[str, range] = { - "Control character": range(31 + 1), - "Basic Latin": range(32, 127 + 1), - "Latin-1 Supplement": range(128, 255 + 1), - "Latin Extended-A": range(256, 383 + 1), - "Latin Extended-B": range(384, 591 + 1), - "IPA Extensions": range(592, 687 + 1), - "Spacing Modifier Letters": range(688, 767 + 1), - "Combining Diacritical Marks": range(768, 879 + 1), - "Greek and Coptic": range(880, 1023 + 1), - "Cyrillic": range(1024, 1279 + 1), - "Cyrillic Supplement": range(1280, 1327 + 1), - "Armenian": range(1328, 1423 + 1), - "Hebrew": range(1424, 1535 + 1), - "Arabic": range(1536, 1791 + 1), - "Syriac": range(1792, 1871 + 1), - "Arabic Supplement": range(1872, 1919 + 1), - "Thaana": range(1920, 1983 + 1), - "NKo": range(1984, 2047 + 1), - "Samaritan": range(2048, 2111 + 1), - "Mandaic": range(2112, 2143 + 1), - "Syriac Supplement": range(2144, 2159 + 1), - "Arabic Extended-A": range(2208, 2303 + 1), - "Devanagari": range(2304, 2431 + 1), - "Bengali": range(2432, 2559 + 1), - "Gurmukhi": range(2560, 2687 + 1), - "Gujarati": range(2688, 2815 + 1), - "Oriya": range(2816, 2943 + 1), - "Tamil": range(2944, 3071 + 1), - "Telugu": range(3072, 3199 + 1), - "Kannada": range(3200, 3327 + 1), - "Malayalam": range(3328, 3455 + 1), - "Sinhala": range(3456, 3583 + 1), - "Thai": range(3584, 3711 + 1), - "Lao": range(3712, 3839 + 1), - "Tibetan": range(3840, 4095 + 1), - "Myanmar": range(4096, 4255 + 1), - "Georgian": range(4256, 4351 + 1), - "Hangul Jamo": range(4352, 4607 + 1), - "Ethiopic": range(4608, 4991 + 1), - "Ethiopic Supplement": range(4992, 5023 + 1), - "Cherokee": range(5024, 5119 + 1), - "Unified Canadian Aboriginal Syllabics": range(5120, 5759 + 1), - "Ogham": range(5760, 5791 + 1), - "Runic": range(5792, 5887 + 1), - "Tagalog": range(5888, 5919 + 1), - "Hanunoo": range(5920, 5951 + 1), - "Buhid": range(5952, 5983 + 1), - "Tagbanwa": range(5984, 6015 + 1), - "Khmer": range(6016, 6143 + 1), - "Mongolian": range(6144, 6319 + 1), - "Unified Canadian Aboriginal Syllabics Extended": range(6320, 6399 + 1), - "Limbu": range(6400, 6479 + 1), - "Tai Le": range(6480, 6527 + 1), - "New Tai Lue": range(6528, 6623 + 1), - "Khmer Symbols": range(6624, 6655 + 1), - "Buginese": range(6656, 6687 + 1), - "Tai Tham": range(6688, 6831 + 1), - "Combining Diacritical Marks Extended": range(6832, 6911 + 1), - "Balinese": range(6912, 7039 + 1), - "Sundanese": range(7040, 7103 + 1), - "Batak": range(7104, 7167 + 1), - "Lepcha": range(7168, 7247 + 1), - "Ol Chiki": range(7248, 7295 + 1), - "Cyrillic Extended C": range(7296, 7311 + 1), - "Sundanese Supplement": range(7360, 7375 + 1), - "Vedic Extensions": range(7376, 7423 + 1), - "Phonetic Extensions": range(7424, 7551 + 1), - "Phonetic Extensions Supplement": range(7552, 7615 + 1), - "Combining Diacritical Marks Supplement": range(7616, 7679 + 1), - "Latin Extended Additional": range(7680, 7935 + 1), - "Greek Extended": range(7936, 8191 + 1), - "General Punctuation": range(8192, 8303 + 1), - "Superscripts and Subscripts": range(8304, 8351 + 1), - "Currency Symbols": range(8352, 8399 + 1), - "Combining Diacritical Marks for Symbols": range(8400, 8447 + 1), - "Letterlike Symbols": range(8448, 8527 + 1), - "Number Forms": range(8528, 8591 + 1), - "Arrows": range(8592, 8703 + 1), - "Mathematical Operators": range(8704, 8959 + 1), - "Miscellaneous Technical": range(8960, 9215 + 1), - "Control Pictures": range(9216, 9279 + 1), - "Optical Character Recognition": range(9280, 9311 + 1), - "Enclosed Alphanumerics": range(9312, 9471 + 1), - "Box Drawing": range(9472, 9599 + 1), - "Block Elements": range(9600, 9631 + 1), - "Geometric Shapes": range(9632, 9727 + 1), - "Miscellaneous Symbols": range(9728, 9983 + 1), - "Dingbats": range(9984, 10175 + 1), - "Miscellaneous Mathematical Symbols-A": range(10176, 10223 + 1), - "Supplemental Arrows-A": range(10224, 10239 + 1), - "Braille Patterns": range(10240, 10495 + 1), - "Supplemental Arrows-B": range(10496, 10623 + 1), - "Miscellaneous Mathematical Symbols-B": range(10624, 10751 + 1), - "Supplemental Mathematical Operators": range(10752, 11007 + 1), - "Miscellaneous Symbols and Arrows": range(11008, 11263 + 1), - "Glagolitic": range(11264, 11359 + 1), - "Latin Extended-C": range(11360, 11391 + 1), - "Coptic": range(11392, 11519 + 1), - "Georgian Supplement": range(11520, 11567 + 1), - "Tifinagh": range(11568, 11647 + 1), - "Ethiopic Extended": range(11648, 11743 + 1), - "Cyrillic Extended-A": range(11744, 11775 + 1), - "Supplemental Punctuation": range(11776, 11903 + 1), - "CJK Radicals Supplement": range(11904, 12031 + 1), - "Kangxi Radicals": range(12032, 12255 + 1), - "Ideographic Description Characters": range(12272, 12287 + 1), - "CJK Symbols and Punctuation": range(12288, 12351 + 1), - "Hiragana": range(12352, 12447 + 1), - "Katakana": range(12448, 12543 + 1), - "Bopomofo": range(12544, 12591 + 1), - "Hangul Compatibility Jamo": range(12592, 12687 + 1), - "Kanbun": range(12688, 12703 + 1), - "Bopomofo Extended": range(12704, 12735 + 1), - "CJK Strokes": range(12736, 12783 + 1), - "Katakana Phonetic Extensions": range(12784, 12799 + 1), - "Enclosed CJK Letters and Months": range(12800, 13055 + 1), - "CJK Compatibility": range(13056, 13311 + 1), - "CJK Unified Ideographs Extension A": range(13312, 19903 + 1), - "Yijing Hexagram Symbols": range(19904, 19967 + 1), - "CJK Unified Ideographs": range(19968, 40959 + 1), - "Yi Syllables": range(40960, 42127 + 1), - "Yi Radicals": range(42128, 42191 + 1), - "Lisu": range(42192, 42239 + 1), - "Vai": range(42240, 42559 + 1), - "Cyrillic Extended-B": range(42560, 42655 + 1), - "Bamum": range(42656, 42751 + 1), - "Modifier Tone Letters": range(42752, 42783 + 1), - "Latin Extended-D": range(42784, 43007 + 1), - "Syloti Nagri": range(43008, 43055 + 1), - "Common Indic Number Forms": range(43056, 43071 + 1), - "Phags-pa": range(43072, 43135 + 1), - "Saurashtra": range(43136, 43231 + 1), - "Devanagari Extended": range(43232, 43263 + 1), - "Kayah Li": range(43264, 43311 + 1), - "Rejang": range(43312, 43359 + 1), - "Hangul Jamo Extended-A": range(43360, 43391 + 1), - "Javanese": range(43392, 43487 + 1), - "Myanmar Extended-B": range(43488, 43519 + 1), - "Cham": range(43520, 43615 + 1), - "Myanmar Extended-A": range(43616, 43647 + 1), - "Tai Viet": range(43648, 43743 + 1), - "Meetei Mayek Extensions": range(43744, 43775 + 1), - "Ethiopic Extended-A": range(43776, 43823 + 1), - "Latin Extended-E": range(43824, 43887 + 1), - "Cherokee Supplement": range(43888, 43967 + 1), - "Meetei Mayek": range(43968, 44031 + 1), - "Hangul Syllables": range(44032, 55215 + 1), - "Hangul Jamo Extended-B": range(55216, 55295 + 1), - "High Surrogates": range(55296, 56191 + 1), - "High Private Use Surrogates": range(56192, 56319 + 1), - "Low Surrogates": range(56320, 57343 + 1), - "Private Use Area": range(57344, 63743 + 1), - "CJK Compatibility Ideographs": range(63744, 64255 + 1), - "Alphabetic Presentation Forms": range(64256, 64335 + 1), - "Arabic Presentation Forms-A": range(64336, 65023 + 1), - "Variation Selectors": range(65024, 65039 + 1), - "Vertical Forms": range(65040, 65055 + 1), - "Combining Half Marks": range(65056, 65071 + 1), - "CJK Compatibility Forms": range(65072, 65103 + 1), - "Small Form Variants": range(65104, 65135 + 1), - "Arabic Presentation Forms-B": range(65136, 65279 + 1), - "Halfwidth and Fullwidth Forms": range(65280, 65519 + 1), - "Specials": range(65520, 65535 + 1), - "Linear B Syllabary": range(65536, 65663 + 1), - "Linear B Ideograms": range(65664, 65791 + 1), - "Aegean Numbers": range(65792, 65855 + 1), - "Ancient Greek Numbers": range(65856, 65935 + 1), - "Ancient Symbols": range(65936, 65999 + 1), - "Phaistos Disc": range(66000, 66047 + 1), - "Lycian": range(66176, 66207 + 1), - "Carian": range(66208, 66271 + 1), - "Coptic Epact Numbers": range(66272, 66303 + 1), - "Old Italic": range(66304, 66351 + 1), - "Gothic": range(66352, 66383 + 1), - "Old Permic": range(66384, 66431 + 1), - "Ugaritic": range(66432, 66463 + 1), - "Old Persian": range(66464, 66527 + 1), - "Deseret": range(66560, 66639 + 1), - "Shavian": range(66640, 66687 + 1), - "Osmanya": range(66688, 66735 + 1), - "Osage": range(66736, 66815 + 1), - "Elbasan": range(66816, 66863 + 1), - "Caucasian Albanian": range(66864, 66927 + 1), - "Linear A": range(67072, 67455 + 1), - "Cypriot Syllabary": range(67584, 67647 + 1), - "Imperial Aramaic": range(67648, 67679 + 1), - "Palmyrene": range(67680, 67711 + 1), - "Nabataean": range(67712, 67759 + 1), - "Hatran": range(67808, 67839 + 1), - "Phoenician": range(67840, 67871 + 1), - "Lydian": range(67872, 67903 + 1), - "Meroitic Hieroglyphs": range(67968, 67999 + 1), - "Meroitic Cursive": range(68000, 68095 + 1), - "Kharoshthi": range(68096, 68191 + 1), - "Old South Arabian": range(68192, 68223 + 1), - "Old North Arabian": range(68224, 68255 + 1), - "Manichaean": range(68288, 68351 + 1), - "Avestan": range(68352, 68415 + 1), - "Inscriptional Parthian": range(68416, 68447 + 1), - "Inscriptional Pahlavi": range(68448, 68479 + 1), - "Psalter Pahlavi": range(68480, 68527 + 1), - "Old Turkic": range(68608, 68687 + 1), - "Old Hungarian": range(68736, 68863 + 1), - "Rumi Numeral Symbols": range(69216, 69247 + 1), - "Brahmi": range(69632, 69759 + 1), - "Kaithi": range(69760, 69839 + 1), - "Sora Sompeng": range(69840, 69887 + 1), - "Chakma": range(69888, 69967 + 1), - "Mahajani": range(69968, 70015 + 1), - "Sharada": range(70016, 70111 + 1), - "Sinhala Archaic Numbers": range(70112, 70143 + 1), - "Khojki": range(70144, 70223 + 1), - "Multani": range(70272, 70319 + 1), - "Khudawadi": range(70320, 70399 + 1), - "Grantha": range(70400, 70527 + 1), - "Newa": range(70656, 70783 + 1), - "Tirhuta": range(70784, 70879 + 1), - "Siddham": range(71040, 71167 + 1), - "Modi": range(71168, 71263 + 1), - "Mongolian Supplement": range(71264, 71295 + 1), - "Takri": range(71296, 71375 + 1), - "Ahom": range(71424, 71487 + 1), - "Warang Citi": range(71840, 71935 + 1), - "Zanabazar Square": range(72192, 72271 + 1), - "Soyombo": range(72272, 72367 + 1), - "Pau Cin Hau": range(72384, 72447 + 1), - "Bhaiksuki": range(72704, 72815 + 1), - "Marchen": range(72816, 72895 + 1), - "Masaram Gondi": range(72960, 73055 + 1), - "Cuneiform": range(73728, 74751 + 1), - "Cuneiform Numbers and Punctuation": range(74752, 74879 + 1), - "Early Dynastic Cuneiform": range(74880, 75087 + 1), - "Egyptian Hieroglyphs": range(77824, 78895 + 1), - "Anatolian Hieroglyphs": range(82944, 83583 + 1), - "Bamum Supplement": range(92160, 92735 + 1), - "Mro": range(92736, 92783 + 1), - "Bassa Vah": range(92880, 92927 + 1), - "Pahawh Hmong": range(92928, 93071 + 1), - "Miao": range(93952, 94111 + 1), - "Ideographic Symbols and Punctuation": range(94176, 94207 + 1), - "Tangut": range(94208, 100351 + 1), - "Tangut Components": range(100352, 101119 + 1), - "Kana Supplement": range(110592, 110847 + 1), - "Kana Extended-A": range(110848, 110895 + 1), - "Nushu": range(110960, 111359 + 1), - "Duployan": range(113664, 113823 + 1), - "Shorthand Format Controls": range(113824, 113839 + 1), - "Byzantine Musical Symbols": range(118784, 119039 + 1), - "Musical Symbols": range(119040, 119295 + 1), - "Ancient Greek Musical Notation": range(119296, 119375 + 1), - "Tai Xuan Jing Symbols": range(119552, 119647 + 1), - "Counting Rod Numerals": range(119648, 119679 + 1), - "Mathematical Alphanumeric Symbols": range(119808, 120831 + 1), - "Sutton SignWriting": range(120832, 121519 + 1), - "Glagolitic Supplement": range(122880, 122927 + 1), - "Mende Kikakui": range(124928, 125151 + 1), - "Adlam": range(125184, 125279 + 1), - "Arabic Mathematical Alphabetic Symbols": range(126464, 126719 + 1), - "Mahjong Tiles": range(126976, 127023 + 1), - "Domino Tiles": range(127024, 127135 + 1), - "Playing Cards": range(127136, 127231 + 1), - "Enclosed Alphanumeric Supplement": range(127232, 127487 + 1), - "Enclosed Ideographic Supplement": range(127488, 127743 + 1), - "Miscellaneous Symbols and Pictographs": range(127744, 128511 + 1), - "Emoticons range(Emoji)": range(128512, 128591 + 1), - "Ornamental Dingbats": range(128592, 128639 + 1), - "Transport and Map Symbols": range(128640, 128767 + 1), - "Alchemical Symbols": range(128768, 128895 + 1), - "Geometric Shapes Extended": range(128896, 129023 + 1), - "Supplemental Arrows-C": range(129024, 129279 + 1), - "Supplemental Symbols and Pictographs": range(129280, 129535 + 1), - "CJK Unified Ideographs Extension B": range(131072, 173791 + 1), - "CJK Unified Ideographs Extension C": range(173824, 177983 + 1), - "CJK Unified Ideographs Extension D": range(177984, 178207 + 1), - "CJK Unified Ideographs Extension E": range(178208, 183983 + 1), - "CJK Unified Ideographs Extension F": range(183984, 191471 + 1), - "CJK Compatibility Ideographs Supplement": range(194560, 195103 + 1), - "Tags": range(917504, 917631 + 1), - "Variation Selectors Supplement": range(917760, 917999 + 1), -} - - -UNICODE_SECONDARY_RANGE_KEYWORD: List[str] = [ - "Supplement", - "Extended", - "Extensions", - "Modifier", - "Marks", - "Punctuation", - "Symbols", - "Forms", - "Operators", - "Miscellaneous", - "Drawing", - "Block", - "Shapes", - "Supplemental", - "Tags", -] - -RE_POSSIBLE_ENCODING_INDICATION = re_compile( - r"(?:(?:encoding)|(?:charset)|(?:coding))(?:[\:= ]{1,10})(?:[\"\']?)([a-zA-Z0-9\-_]+)(?:[\"\']?)", - IGNORECASE, -) - -IANA_SUPPORTED: List[str] = sorted( - filter( - lambda x: x.endswith("_codec") is False - and x not in {"rot_13", "tactis", "mbcs"}, - list(set(aliases.values())), - ) -) - -IANA_SUPPORTED_COUNT: int = len(IANA_SUPPORTED) - -# pre-computed code page that are similar using the function cp_similarity. -IANA_SUPPORTED_SIMILAR: Dict[str, List[str]] = { - "cp037": ["cp1026", "cp1140", "cp273", "cp500"], - "cp1026": ["cp037", "cp1140", "cp273", "cp500"], - "cp1125": ["cp866"], - "cp1140": ["cp037", "cp1026", "cp273", "cp500"], - "cp1250": ["iso8859_2"], - "cp1251": ["kz1048", "ptcp154"], - "cp1252": ["iso8859_15", "iso8859_9", "latin_1"], - "cp1253": ["iso8859_7"], - "cp1254": ["iso8859_15", "iso8859_9", "latin_1"], - "cp1257": ["iso8859_13"], - "cp273": ["cp037", "cp1026", "cp1140", "cp500"], - "cp437": ["cp850", "cp858", "cp860", "cp861", "cp862", "cp863", "cp865"], - "cp500": ["cp037", "cp1026", "cp1140", "cp273"], - "cp850": ["cp437", "cp857", "cp858", "cp865"], - "cp857": ["cp850", "cp858", "cp865"], - "cp858": ["cp437", "cp850", "cp857", "cp865"], - "cp860": ["cp437", "cp861", "cp862", "cp863", "cp865"], - "cp861": ["cp437", "cp860", "cp862", "cp863", "cp865"], - "cp862": ["cp437", "cp860", "cp861", "cp863", "cp865"], - "cp863": ["cp437", "cp860", "cp861", "cp862", "cp865"], - "cp865": ["cp437", "cp850", "cp857", "cp858", "cp860", "cp861", "cp862", "cp863"], - "cp866": ["cp1125"], - "iso8859_10": ["iso8859_14", "iso8859_15", "iso8859_4", "iso8859_9", "latin_1"], - "iso8859_11": ["tis_620"], - "iso8859_13": ["cp1257"], - "iso8859_14": [ - "iso8859_10", - "iso8859_15", - "iso8859_16", - "iso8859_3", - "iso8859_9", - "latin_1", - ], - "iso8859_15": [ - "cp1252", - "cp1254", - "iso8859_10", - "iso8859_14", - "iso8859_16", - "iso8859_3", - "iso8859_9", - "latin_1", - ], - "iso8859_16": [ - "iso8859_14", - "iso8859_15", - "iso8859_2", - "iso8859_3", - "iso8859_9", - "latin_1", - ], - "iso8859_2": ["cp1250", "iso8859_16", "iso8859_4"], - "iso8859_3": ["iso8859_14", "iso8859_15", "iso8859_16", "iso8859_9", "latin_1"], - "iso8859_4": ["iso8859_10", "iso8859_2", "iso8859_9", "latin_1"], - "iso8859_7": ["cp1253"], - "iso8859_9": [ - "cp1252", - "cp1254", - "cp1258", - "iso8859_10", - "iso8859_14", - "iso8859_15", - "iso8859_16", - "iso8859_3", - "iso8859_4", - "latin_1", - ], - "kz1048": ["cp1251", "ptcp154"], - "latin_1": [ - "cp1252", - "cp1254", - "cp1258", - "iso8859_10", - "iso8859_14", - "iso8859_15", - "iso8859_16", - "iso8859_3", - "iso8859_4", - "iso8859_9", - ], - "mac_iceland": ["mac_roman", "mac_turkish"], - "mac_roman": ["mac_iceland", "mac_turkish"], - "mac_turkish": ["mac_iceland", "mac_roman"], - "ptcp154": ["cp1251", "kz1048"], - "tis_620": ["iso8859_11"], -} - - -CHARDET_CORRESPONDENCE: Dict[str, str] = { - "iso2022_kr": "ISO-2022-KR", - "iso2022_jp": "ISO-2022-JP", - "euc_kr": "EUC-KR", - "tis_620": "TIS-620", - "utf_32": "UTF-32", - "euc_jp": "EUC-JP", - "koi8_r": "KOI8-R", - "iso8859_1": "ISO-8859-1", - "iso8859_2": "ISO-8859-2", - "iso8859_5": "ISO-8859-5", - "iso8859_6": "ISO-8859-6", - "iso8859_7": "ISO-8859-7", - "iso8859_8": "ISO-8859-8", - "utf_16": "UTF-16", - "cp855": "IBM855", - "mac_cyrillic": "MacCyrillic", - "gb2312": "GB2312", - "gb18030": "GB18030", - "cp932": "CP932", - "cp866": "IBM866", - "utf_8": "utf-8", - "utf_8_sig": "UTF-8-SIG", - "shift_jis": "SHIFT_JIS", - "big5": "Big5", - "cp1250": "windows-1250", - "cp1251": "windows-1251", - "cp1252": "Windows-1252", - "cp1253": "windows-1253", - "cp1255": "windows-1255", - "cp1256": "windows-1256", - "cp1254": "Windows-1254", - "cp949": "CP949", -} - - -COMMON_SAFE_ASCII_CHARACTERS: Set[str] = { - "<", - ">", - "=", - ":", - "/", - "&", - ";", - "{", - "}", - "[", - "]", - ",", - "|", - '"', - "-", -} - - -KO_NAMES: Set[str] = {"johab", "cp949", "euc_kr"} -ZH_NAMES: Set[str] = {"big5", "cp950", "big5hkscs", "hz"} - -NOT_PRINTABLE_PATTERN = re_compile(r"[0-9\W\n\r\t]+") - -LANGUAGE_SUPPORTED_COUNT: int = len(FREQUENCIES) - -# Logging LEVEL bellow DEBUG -TRACE: int = 5 diff --git a/.venv/Lib/site-packages/charset_normalizer/legacy.py b/.venv/Lib/site-packages/charset_normalizer/legacy.py deleted file mode 100644 index cdebe2b..0000000 --- a/.venv/Lib/site-packages/charset_normalizer/legacy.py +++ /dev/null @@ -1,95 +0,0 @@ -import warnings -from typing import Dict, Optional, Union - -from .api import from_bytes, from_fp, from_path, normalize -from .constant import CHARDET_CORRESPONDENCE -from .models import CharsetMatch, CharsetMatches - - -def detect(byte_str: bytes) -> Dict[str, Optional[Union[str, float]]]: - """ - chardet legacy method - Detect the encoding of the given byte string. It should be mostly backward-compatible. - Encoding name will match Chardet own writing whenever possible. (Not on encoding name unsupported by it) - This function is deprecated and should be used to migrate your project easily, consult the documentation for - further information. Not planned for removal. - - :param byte_str: The byte sequence to examine. - """ - if not isinstance(byte_str, (bytearray, bytes)): - raise TypeError( # pragma: nocover - "Expected object of type bytes or bytearray, got: " - "{0}".format(type(byte_str)) - ) - - if isinstance(byte_str, bytearray): - byte_str = bytes(byte_str) - - r = from_bytes(byte_str).best() - - encoding = r.encoding if r is not None else None - language = r.language if r is not None and r.language != "Unknown" else "" - confidence = 1.0 - r.chaos if r is not None else None - - # Note: CharsetNormalizer does not return 'UTF-8-SIG' as the sig get stripped in the detection/normalization process - # but chardet does return 'utf-8-sig' and it is a valid codec name. - if r is not None and encoding == "utf_8" and r.bom: - encoding += "_sig" - - return { - "encoding": encoding - if encoding not in CHARDET_CORRESPONDENCE - else CHARDET_CORRESPONDENCE[encoding], - "language": language, - "confidence": confidence, - } - - -class CharsetNormalizerMatch(CharsetMatch): - pass - - -class CharsetNormalizerMatches(CharsetMatches): - @staticmethod - def from_fp(*args, **kwargs): # type: ignore - warnings.warn( # pragma: nocover - "staticmethod from_fp, from_bytes, from_path and normalize are deprecated " - "and scheduled to be removed in 3.0", - DeprecationWarning, - ) - return from_fp(*args, **kwargs) # pragma: nocover - - @staticmethod - def from_bytes(*args, **kwargs): # type: ignore - warnings.warn( # pragma: nocover - "staticmethod from_fp, from_bytes, from_path and normalize are deprecated " - "and scheduled to be removed in 3.0", - DeprecationWarning, - ) - return from_bytes(*args, **kwargs) # pragma: nocover - - @staticmethod - def from_path(*args, **kwargs): # type: ignore - warnings.warn( # pragma: nocover - "staticmethod from_fp, from_bytes, from_path and normalize are deprecated " - "and scheduled to be removed in 3.0", - DeprecationWarning, - ) - return from_path(*args, **kwargs) # pragma: nocover - - @staticmethod - def normalize(*args, **kwargs): # type: ignore - warnings.warn( # pragma: nocover - "staticmethod from_fp, from_bytes, from_path and normalize are deprecated " - "and scheduled to be removed in 3.0", - DeprecationWarning, - ) - return normalize(*args, **kwargs) # pragma: nocover - - -class CharsetDetector(CharsetNormalizerMatches): - pass - - -class CharsetDoctor(CharsetNormalizerMatches): - pass diff --git a/.venv/Lib/site-packages/charset_normalizer/md.py b/.venv/Lib/site-packages/charset_normalizer/md.py deleted file mode 100644 index 31808af..0000000 --- a/.venv/Lib/site-packages/charset_normalizer/md.py +++ /dev/null @@ -1,553 +0,0 @@ -from functools import lru_cache -from typing import List, Optional - -from .constant import COMMON_SAFE_ASCII_CHARACTERS, UNICODE_SECONDARY_RANGE_KEYWORD -from .utils import ( - is_accentuated, - is_ascii, - is_case_variable, - is_cjk, - is_emoticon, - is_hangul, - is_hiragana, - is_katakana, - is_latin, - is_punctuation, - is_separator, - is_symbol, - is_thai, - is_unprintable, - remove_accent, - unicode_range, -) - - -class MessDetectorPlugin: - """ - Base abstract class used for mess detection plugins. - All detectors MUST extend and implement given methods. - """ - - def eligible(self, character: str) -> bool: - """ - Determine if given character should be fed in. - """ - raise NotImplementedError # pragma: nocover - - def feed(self, character: str) -> None: - """ - The main routine to be executed upon character. - Insert the logic in witch the text would be considered chaotic. - """ - raise NotImplementedError # pragma: nocover - - def reset(self) -> None: # pragma: no cover - """ - Permit to reset the plugin to the initial state. - """ - raise NotImplementedError - - @property - def ratio(self) -> float: - """ - Compute the chaos ratio based on what your feed() has seen. - Must NOT be lower than 0.; No restriction gt 0. - """ - raise NotImplementedError # pragma: nocover - - -class TooManySymbolOrPunctuationPlugin(MessDetectorPlugin): - def __init__(self) -> None: - self._punctuation_count: int = 0 - self._symbol_count: int = 0 - self._character_count: int = 0 - - self._last_printable_char: Optional[str] = None - self._frenzy_symbol_in_word: bool = False - - def eligible(self, character: str) -> bool: - return character.isprintable() - - def feed(self, character: str) -> None: - self._character_count += 1 - - if ( - character != self._last_printable_char - and character not in COMMON_SAFE_ASCII_CHARACTERS - ): - if is_punctuation(character): - self._punctuation_count += 1 - elif ( - character.isdigit() is False - and is_symbol(character) - and is_emoticon(character) is False - ): - self._symbol_count += 2 - - self._last_printable_char = character - - def reset(self) -> None: # pragma: no cover - self._punctuation_count = 0 - self._character_count = 0 - self._symbol_count = 0 - - @property - def ratio(self) -> float: - if self._character_count == 0: - return 0.0 - - ratio_of_punctuation: float = ( - self._punctuation_count + self._symbol_count - ) / self._character_count - - return ratio_of_punctuation if ratio_of_punctuation >= 0.3 else 0.0 - - -class TooManyAccentuatedPlugin(MessDetectorPlugin): - def __init__(self) -> None: - self._character_count: int = 0 - self._accentuated_count: int = 0 - - def eligible(self, character: str) -> bool: - return character.isalpha() - - def feed(self, character: str) -> None: - self._character_count += 1 - - if is_accentuated(character): - self._accentuated_count += 1 - - def reset(self) -> None: # pragma: no cover - self._character_count = 0 - self._accentuated_count = 0 - - @property - def ratio(self) -> float: - if self._character_count == 0: - return 0.0 - ratio_of_accentuation: float = self._accentuated_count / self._character_count - return ratio_of_accentuation if ratio_of_accentuation >= 0.35 else 0.0 - - -class UnprintablePlugin(MessDetectorPlugin): - def __init__(self) -> None: - self._unprintable_count: int = 0 - self._character_count: int = 0 - - def eligible(self, character: str) -> bool: - return True - - def feed(self, character: str) -> None: - if is_unprintable(character): - self._unprintable_count += 1 - self._character_count += 1 - - def reset(self) -> None: # pragma: no cover - self._unprintable_count = 0 - - @property - def ratio(self) -> float: - if self._character_count == 0: - return 0.0 - - return (self._unprintable_count * 8) / self._character_count - - -class SuspiciousDuplicateAccentPlugin(MessDetectorPlugin): - def __init__(self) -> None: - self._successive_count: int = 0 - self._character_count: int = 0 - - self._last_latin_character: Optional[str] = None - - def eligible(self, character: str) -> bool: - return character.isalpha() and is_latin(character) - - def feed(self, character: str) -> None: - self._character_count += 1 - if ( - self._last_latin_character is not None - and is_accentuated(character) - and is_accentuated(self._last_latin_character) - ): - if character.isupper() and self._last_latin_character.isupper(): - self._successive_count += 1 - # Worse if its the same char duplicated with different accent. - if remove_accent(character) == remove_accent(self._last_latin_character): - self._successive_count += 1 - self._last_latin_character = character - - def reset(self) -> None: # pragma: no cover - self._successive_count = 0 - self._character_count = 0 - self._last_latin_character = None - - @property - def ratio(self) -> float: - if self._character_count == 0: - return 0.0 - - return (self._successive_count * 2) / self._character_count - - -class SuspiciousRange(MessDetectorPlugin): - def __init__(self) -> None: - self._suspicious_successive_range_count: int = 0 - self._character_count: int = 0 - self._last_printable_seen: Optional[str] = None - - def eligible(self, character: str) -> bool: - return character.isprintable() - - def feed(self, character: str) -> None: - self._character_count += 1 - - if ( - character.isspace() - or is_punctuation(character) - or character in COMMON_SAFE_ASCII_CHARACTERS - ): - self._last_printable_seen = None - return - - if self._last_printable_seen is None: - self._last_printable_seen = character - return - - unicode_range_a: Optional[str] = unicode_range(self._last_printable_seen) - unicode_range_b: Optional[str] = unicode_range(character) - - if is_suspiciously_successive_range(unicode_range_a, unicode_range_b): - self._suspicious_successive_range_count += 1 - - self._last_printable_seen = character - - def reset(self) -> None: # pragma: no cover - self._character_count = 0 - self._suspicious_successive_range_count = 0 - self._last_printable_seen = None - - @property - def ratio(self) -> float: - if self._character_count == 0: - return 0.0 - - ratio_of_suspicious_range_usage: float = ( - self._suspicious_successive_range_count * 2 - ) / self._character_count - - if ratio_of_suspicious_range_usage < 0.1: - return 0.0 - - return ratio_of_suspicious_range_usage - - -class SuperWeirdWordPlugin(MessDetectorPlugin): - def __init__(self) -> None: - self._word_count: int = 0 - self._bad_word_count: int = 0 - self._foreign_long_count: int = 0 - - self._is_current_word_bad: bool = False - self._foreign_long_watch: bool = False - - self._character_count: int = 0 - self._bad_character_count: int = 0 - - self._buffer: str = "" - self._buffer_accent_count: int = 0 - - def eligible(self, character: str) -> bool: - return True - - def feed(self, character: str) -> None: - if character.isalpha(): - self._buffer += character - if is_accentuated(character): - self._buffer_accent_count += 1 - if ( - self._foreign_long_watch is False - and (is_latin(character) is False or is_accentuated(character)) - and is_cjk(character) is False - and is_hangul(character) is False - and is_katakana(character) is False - and is_hiragana(character) is False - and is_thai(character) is False - ): - self._foreign_long_watch = True - return - if not self._buffer: - return - if ( - character.isspace() or is_punctuation(character) or is_separator(character) - ) and self._buffer: - self._word_count += 1 - buffer_length: int = len(self._buffer) - - self._character_count += buffer_length - - if buffer_length >= 4: - if self._buffer_accent_count / buffer_length > 0.34: - self._is_current_word_bad = True - # Word/Buffer ending with a upper case accentuated letter are so rare, - # that we will consider them all as suspicious. Same weight as foreign_long suspicious. - if is_accentuated(self._buffer[-1]) and self._buffer[-1].isupper(): - self._foreign_long_count += 1 - self._is_current_word_bad = True - if buffer_length >= 24 and self._foreign_long_watch: - self._foreign_long_count += 1 - self._is_current_word_bad = True - - if self._is_current_word_bad: - self._bad_word_count += 1 - self._bad_character_count += len(self._buffer) - self._is_current_word_bad = False - - self._foreign_long_watch = False - self._buffer = "" - self._buffer_accent_count = 0 - elif ( - character not in {"<", ">", "-", "=", "~", "|", "_"} - and character.isdigit() is False - and is_symbol(character) - ): - self._is_current_word_bad = True - self._buffer += character - - def reset(self) -> None: # pragma: no cover - self._buffer = "" - self._is_current_word_bad = False - self._foreign_long_watch = False - self._bad_word_count = 0 - self._word_count = 0 - self._character_count = 0 - self._bad_character_count = 0 - self._foreign_long_count = 0 - - @property - def ratio(self) -> float: - if self._word_count <= 10 and self._foreign_long_count == 0: - return 0.0 - - return self._bad_character_count / self._character_count - - -class CjkInvalidStopPlugin(MessDetectorPlugin): - """ - GB(Chinese) based encoding often render the stop incorrectly when the content does not fit and - can be easily detected. Searching for the overuse of '丅' and '丄'. - """ - - def __init__(self) -> None: - self._wrong_stop_count: int = 0 - self._cjk_character_count: int = 0 - - def eligible(self, character: str) -> bool: - return True - - def feed(self, character: str) -> None: - if character in {"丅", "丄"}: - self._wrong_stop_count += 1 - return - if is_cjk(character): - self._cjk_character_count += 1 - - def reset(self) -> None: # pragma: no cover - self._wrong_stop_count = 0 - self._cjk_character_count = 0 - - @property - def ratio(self) -> float: - if self._cjk_character_count < 16: - return 0.0 - return self._wrong_stop_count / self._cjk_character_count - - -class ArchaicUpperLowerPlugin(MessDetectorPlugin): - def __init__(self) -> None: - self._buf: bool = False - - self._character_count_since_last_sep: int = 0 - - self._successive_upper_lower_count: int = 0 - self._successive_upper_lower_count_final: int = 0 - - self._character_count: int = 0 - - self._last_alpha_seen: Optional[str] = None - self._current_ascii_only: bool = True - - def eligible(self, character: str) -> bool: - return True - - def feed(self, character: str) -> None: - is_concerned = character.isalpha() and is_case_variable(character) - chunk_sep = is_concerned is False - - if chunk_sep and self._character_count_since_last_sep > 0: - if ( - self._character_count_since_last_sep <= 64 - and character.isdigit() is False - and self._current_ascii_only is False - ): - self._successive_upper_lower_count_final += ( - self._successive_upper_lower_count - ) - - self._successive_upper_lower_count = 0 - self._character_count_since_last_sep = 0 - self._last_alpha_seen = None - self._buf = False - self._character_count += 1 - self._current_ascii_only = True - - return - - if self._current_ascii_only is True and is_ascii(character) is False: - self._current_ascii_only = False - - if self._last_alpha_seen is not None: - if (character.isupper() and self._last_alpha_seen.islower()) or ( - character.islower() and self._last_alpha_seen.isupper() - ): - if self._buf is True: - self._successive_upper_lower_count += 2 - self._buf = False - else: - self._buf = True - else: - self._buf = False - - self._character_count += 1 - self._character_count_since_last_sep += 1 - self._last_alpha_seen = character - - def reset(self) -> None: # pragma: no cover - self._character_count = 0 - self._character_count_since_last_sep = 0 - self._successive_upper_lower_count = 0 - self._successive_upper_lower_count_final = 0 - self._last_alpha_seen = None - self._buf = False - self._current_ascii_only = True - - @property - def ratio(self) -> float: - if self._character_count == 0: - return 0.0 - - return self._successive_upper_lower_count_final / self._character_count - - -@lru_cache(maxsize=1024) -def is_suspiciously_successive_range( - unicode_range_a: Optional[str], unicode_range_b: Optional[str] -) -> bool: - """ - Determine if two Unicode range seen next to each other can be considered as suspicious. - """ - if unicode_range_a is None or unicode_range_b is None: - return True - - if unicode_range_a == unicode_range_b: - return False - - if "Latin" in unicode_range_a and "Latin" in unicode_range_b: - return False - - if "Emoticons" in unicode_range_a or "Emoticons" in unicode_range_b: - return False - - # Latin characters can be accompanied with a combining diacritical mark - # eg. Vietnamese. - if ("Latin" in unicode_range_a or "Latin" in unicode_range_b) and ( - "Combining" in unicode_range_a or "Combining" in unicode_range_b - ): - return False - - keywords_range_a, keywords_range_b = unicode_range_a.split( - " " - ), unicode_range_b.split(" ") - - for el in keywords_range_a: - if el in UNICODE_SECONDARY_RANGE_KEYWORD: - continue - if el in keywords_range_b: - return False - - # Japanese Exception - range_a_jp_chars, range_b_jp_chars = ( - unicode_range_a - in ( - "Hiragana", - "Katakana", - ), - unicode_range_b in ("Hiragana", "Katakana"), - ) - if (range_a_jp_chars or range_b_jp_chars) and ( - "CJK" in unicode_range_a or "CJK" in unicode_range_b - ): - return False - if range_a_jp_chars and range_b_jp_chars: - return False - - if "Hangul" in unicode_range_a or "Hangul" in unicode_range_b: - if "CJK" in unicode_range_a or "CJK" in unicode_range_b: - return False - if unicode_range_a == "Basic Latin" or unicode_range_b == "Basic Latin": - return False - - # Chinese/Japanese use dedicated range for punctuation and/or separators. - if ("CJK" in unicode_range_a or "CJK" in unicode_range_b) or ( - unicode_range_a in ["Katakana", "Hiragana"] - and unicode_range_b in ["Katakana", "Hiragana"] - ): - if "Punctuation" in unicode_range_a or "Punctuation" in unicode_range_b: - return False - if "Forms" in unicode_range_a or "Forms" in unicode_range_b: - return False - - return True - - -@lru_cache(maxsize=2048) -def mess_ratio( - decoded_sequence: str, maximum_threshold: float = 0.2, debug: bool = False -) -> float: - """ - Compute a mess ratio given a decoded bytes sequence. The maximum threshold does stop the computation earlier. - """ - - detectors: List[MessDetectorPlugin] = [ - md_class() for md_class in MessDetectorPlugin.__subclasses__() - ] - - length: int = len(decoded_sequence) + 1 - - mean_mess_ratio: float = 0.0 - - if length < 512: - intermediary_mean_mess_ratio_calc: int = 32 - elif length <= 1024: - intermediary_mean_mess_ratio_calc = 64 - else: - intermediary_mean_mess_ratio_calc = 128 - - for character, index in zip(decoded_sequence + "\n", range(length)): - for detector in detectors: - if detector.eligible(character): - detector.feed(character) - - if ( - index > 0 and index % intermediary_mean_mess_ratio_calc == 0 - ) or index == length - 1: - mean_mess_ratio = sum(dt.ratio for dt in detectors) - - if mean_mess_ratio >= maximum_threshold: - break - - if debug: - for dt in detectors: # pragma: nocover - print(dt.__class__, dt.ratio) - - return round(mean_mess_ratio, 3) diff --git a/.venv/Lib/site-packages/charset_normalizer/models.py b/.venv/Lib/site-packages/charset_normalizer/models.py deleted file mode 100644 index ccb0d47..0000000 --- a/.venv/Lib/site-packages/charset_normalizer/models.py +++ /dev/null @@ -1,401 +0,0 @@ -import warnings -from collections import Counter -from encodings.aliases import aliases -from hashlib import sha256 -from json import dumps -from re import sub -from typing import ( - Any, - Counter as TypeCounter, - Dict, - Iterator, - List, - Optional, - Tuple, - Union, -) - -from .constant import NOT_PRINTABLE_PATTERN, TOO_BIG_SEQUENCE -from .md import mess_ratio -from .utils import iana_name, is_multi_byte_encoding, unicode_range - - -class CharsetMatch: - def __init__( - self, - payload: bytes, - guessed_encoding: str, - mean_mess_ratio: float, - has_sig_or_bom: bool, - languages: "CoherenceMatches", - decoded_payload: Optional[str] = None, - ): - self._payload: bytes = payload - - self._encoding: str = guessed_encoding - self._mean_mess_ratio: float = mean_mess_ratio - self._languages: CoherenceMatches = languages - self._has_sig_or_bom: bool = has_sig_or_bom - self._unicode_ranges: Optional[List[str]] = None - - self._leaves: List[CharsetMatch] = [] - self._mean_coherence_ratio: float = 0.0 - - self._output_payload: Optional[bytes] = None - self._output_encoding: Optional[str] = None - - self._string: Optional[str] = decoded_payload - - def __eq__(self, other: object) -> bool: - if not isinstance(other, CharsetMatch): - raise TypeError( - "__eq__ cannot be invoked on {} and {}.".format( - str(other.__class__), str(self.__class__) - ) - ) - return self.encoding == other.encoding and self.fingerprint == other.fingerprint - - def __lt__(self, other: object) -> bool: - """ - Implemented to make sorted available upon CharsetMatches items. - """ - if not isinstance(other, CharsetMatch): - raise ValueError - - chaos_difference: float = abs(self.chaos - other.chaos) - coherence_difference: float = abs(self.coherence - other.coherence) - - # Bellow 1% difference --> Use Coherence - if chaos_difference < 0.01 and coherence_difference > 0.02: - # When having a tough decision, use the result that decoded as many multi-byte as possible. - if chaos_difference == 0.0 and self.coherence == other.coherence: - return self.multi_byte_usage > other.multi_byte_usage - return self.coherence > other.coherence - - return self.chaos < other.chaos - - @property - def multi_byte_usage(self) -> float: - return 1.0 - len(str(self)) / len(self.raw) - - @property - def chaos_secondary_pass(self) -> float: - """ - Check once again chaos in decoded text, except this time, with full content. - Use with caution, this can be very slow. - Notice: Will be removed in 3.0 - """ - warnings.warn( - "chaos_secondary_pass is deprecated and will be removed in 3.0", - DeprecationWarning, - ) - return mess_ratio(str(self), 1.0) - - @property - def coherence_non_latin(self) -> float: - """ - Coherence ratio on the first non-latin language detected if ANY. - Notice: Will be removed in 3.0 - """ - warnings.warn( - "coherence_non_latin is deprecated and will be removed in 3.0", - DeprecationWarning, - ) - return 0.0 - - @property - def w_counter(self) -> TypeCounter[str]: - """ - Word counter instance on decoded text. - Notice: Will be removed in 3.0 - """ - warnings.warn( - "w_counter is deprecated and will be removed in 3.0", DeprecationWarning - ) - - string_printable_only = sub(NOT_PRINTABLE_PATTERN, " ", str(self).lower()) - - return Counter(string_printable_only.split()) - - def __str__(self) -> str: - # Lazy Str Loading - if self._string is None: - self._string = str(self._payload, self._encoding, "strict") - return self._string - - def __repr__(self) -> str: - return "".format(self.encoding, self.fingerprint) - - def add_submatch(self, other: "CharsetMatch") -> None: - if not isinstance(other, CharsetMatch) or other == self: - raise ValueError( - "Unable to add instance <{}> as a submatch of a CharsetMatch".format( - other.__class__ - ) - ) - - other._string = None # Unload RAM usage; dirty trick. - self._leaves.append(other) - - @property - def encoding(self) -> str: - return self._encoding - - @property - def encoding_aliases(self) -> List[str]: - """ - Encoding name are known by many name, using this could help when searching for IBM855 when it's listed as CP855. - """ - also_known_as: List[str] = [] - for u, p in aliases.items(): - if self.encoding == u: - also_known_as.append(p) - elif self.encoding == p: - also_known_as.append(u) - return also_known_as - - @property - def bom(self) -> bool: - return self._has_sig_or_bom - - @property - def byte_order_mark(self) -> bool: - return self._has_sig_or_bom - - @property - def languages(self) -> List[str]: - """ - Return the complete list of possible languages found in decoded sequence. - Usually not really useful. Returned list may be empty even if 'language' property return something != 'Unknown'. - """ - return [e[0] for e in self._languages] - - @property - def language(self) -> str: - """ - Most probable language found in decoded sequence. If none were detected or inferred, the property will return - "Unknown". - """ - if not self._languages: - # Trying to infer the language based on the given encoding - # Its either English or we should not pronounce ourselves in certain cases. - if "ascii" in self.could_be_from_charset: - return "English" - - # doing it there to avoid circular import - from charset_normalizer.cd import encoding_languages, mb_encoding_languages - - languages = ( - mb_encoding_languages(self.encoding) - if is_multi_byte_encoding(self.encoding) - else encoding_languages(self.encoding) - ) - - if len(languages) == 0 or "Latin Based" in languages: - return "Unknown" - - return languages[0] - - return self._languages[0][0] - - @property - def chaos(self) -> float: - return self._mean_mess_ratio - - @property - def coherence(self) -> float: - if not self._languages: - return 0.0 - return self._languages[0][1] - - @property - def percent_chaos(self) -> float: - return round(self.chaos * 100, ndigits=3) - - @property - def percent_coherence(self) -> float: - return round(self.coherence * 100, ndigits=3) - - @property - def raw(self) -> bytes: - """ - Original untouched bytes. - """ - return self._payload - - @property - def submatch(self) -> List["CharsetMatch"]: - return self._leaves - - @property - def has_submatch(self) -> bool: - return len(self._leaves) > 0 - - @property - def alphabets(self) -> List[str]: - if self._unicode_ranges is not None: - return self._unicode_ranges - # list detected ranges - detected_ranges: List[Optional[str]] = [ - unicode_range(char) for char in str(self) - ] - # filter and sort - self._unicode_ranges = sorted(list({r for r in detected_ranges if r})) - return self._unicode_ranges - - @property - def could_be_from_charset(self) -> List[str]: - """ - The complete list of encoding that output the exact SAME str result and therefore could be the originating - encoding. - This list does include the encoding available in property 'encoding'. - """ - return [self._encoding] + [m.encoding for m in self._leaves] - - def first(self) -> "CharsetMatch": - """ - Kept for BC reasons. Will be removed in 3.0. - """ - return self - - def best(self) -> "CharsetMatch": - """ - Kept for BC reasons. Will be removed in 3.0. - """ - return self - - def output(self, encoding: str = "utf_8") -> bytes: - """ - Method to get re-encoded bytes payload using given target encoding. Default to UTF-8. - Any errors will be simply ignored by the encoder NOT replaced. - """ - if self._output_encoding is None or self._output_encoding != encoding: - self._output_encoding = encoding - self._output_payload = str(self).encode(encoding, "replace") - - return self._output_payload # type: ignore - - @property - def fingerprint(self) -> str: - """ - Retrieve the unique SHA256 computed using the transformed (re-encoded) payload. Not the original one. - """ - return sha256(self.output()).hexdigest() - - -class CharsetMatches: - """ - Container with every CharsetMatch items ordered by default from most probable to the less one. - Act like a list(iterable) but does not implements all related methods. - """ - - def __init__(self, results: Optional[List[CharsetMatch]] = None): - self._results: List[CharsetMatch] = sorted(results) if results else [] - - def __iter__(self) -> Iterator[CharsetMatch]: - yield from self._results - - def __getitem__(self, item: Union[int, str]) -> CharsetMatch: - """ - Retrieve a single item either by its position or encoding name (alias may be used here). - Raise KeyError upon invalid index or encoding not present in results. - """ - if isinstance(item, int): - return self._results[item] - if isinstance(item, str): - item = iana_name(item, False) - for result in self._results: - if item in result.could_be_from_charset: - return result - raise KeyError - - def __len__(self) -> int: - return len(self._results) - - def __bool__(self) -> bool: - return len(self._results) > 0 - - def append(self, item: CharsetMatch) -> None: - """ - Insert a single match. Will be inserted accordingly to preserve sort. - Can be inserted as a submatch. - """ - if not isinstance(item, CharsetMatch): - raise ValueError( - "Cannot append instance '{}' to CharsetMatches".format( - str(item.__class__) - ) - ) - # We should disable the submatch factoring when the input file is too heavy (conserve RAM usage) - if len(item.raw) <= TOO_BIG_SEQUENCE: - for match in self._results: - if match.fingerprint == item.fingerprint and match.chaos == item.chaos: - match.add_submatch(item) - return - self._results.append(item) - self._results = sorted(self._results) - - def best(self) -> Optional["CharsetMatch"]: - """ - Simply return the first match. Strict equivalent to matches[0]. - """ - if not self._results: - return None - return self._results[0] - - def first(self) -> Optional["CharsetMatch"]: - """ - Redundant method, call the method best(). Kept for BC reasons. - """ - return self.best() - - -CoherenceMatch = Tuple[str, float] -CoherenceMatches = List[CoherenceMatch] - - -class CliDetectionResult: - def __init__( - self, - path: str, - encoding: Optional[str], - encoding_aliases: List[str], - alternative_encodings: List[str], - language: str, - alphabets: List[str], - has_sig_or_bom: bool, - chaos: float, - coherence: float, - unicode_path: Optional[str], - is_preferred: bool, - ): - self.path: str = path - self.unicode_path: Optional[str] = unicode_path - self.encoding: Optional[str] = encoding - self.encoding_aliases: List[str] = encoding_aliases - self.alternative_encodings: List[str] = alternative_encodings - self.language: str = language - self.alphabets: List[str] = alphabets - self.has_sig_or_bom: bool = has_sig_or_bom - self.chaos: float = chaos - self.coherence: float = coherence - self.is_preferred: bool = is_preferred - - @property - def __dict__(self) -> Dict[str, Any]: # type: ignore - return { - "path": self.path, - "encoding": self.encoding, - "encoding_aliases": self.encoding_aliases, - "alternative_encodings": self.alternative_encodings, - "language": self.language, - "alphabets": self.alphabets, - "has_sig_or_bom": self.has_sig_or_bom, - "chaos": self.chaos, - "coherence": self.coherence, - "unicode_path": self.unicode_path, - "is_preferred": self.is_preferred, - } - - def to_json(self) -> str: - return dumps(self.__dict__, ensure_ascii=True, indent=4) diff --git a/.venv/Lib/site-packages/charset_normalizer/py.typed b/.venv/Lib/site-packages/charset_normalizer/py.typed deleted file mode 100644 index e69de29..0000000 diff --git a/.venv/Lib/site-packages/charset_normalizer/utils.py b/.venv/Lib/site-packages/charset_normalizer/utils.py deleted file mode 100644 index 859f212..0000000 --- a/.venv/Lib/site-packages/charset_normalizer/utils.py +++ /dev/null @@ -1,424 +0,0 @@ -try: - # WARNING: unicodedata2 support is going to be removed in 3.0 - # Python is quickly catching up. - import unicodedata2 as unicodedata -except ImportError: - import unicodedata # type: ignore[no-redef] - -import importlib -import logging -from codecs import IncrementalDecoder -from encodings.aliases import aliases -from functools import lru_cache -from re import findall -from typing import Generator, List, Optional, Set, Tuple, Union - -from _multibytecodec import MultibyteIncrementalDecoder - -from .constant import ( - ENCODING_MARKS, - IANA_SUPPORTED_SIMILAR, - RE_POSSIBLE_ENCODING_INDICATION, - UNICODE_RANGES_COMBINED, - UNICODE_SECONDARY_RANGE_KEYWORD, - UTF8_MAXIMAL_ALLOCATION, -) - - -@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) -def is_accentuated(character: str) -> bool: - try: - description: str = unicodedata.name(character) - except ValueError: - return False - return ( - "WITH GRAVE" in description - or "WITH ACUTE" in description - or "WITH CEDILLA" in description - or "WITH DIAERESIS" in description - or "WITH CIRCUMFLEX" in description - or "WITH TILDE" in description - ) - - -@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) -def remove_accent(character: str) -> str: - decomposed: str = unicodedata.decomposition(character) - if not decomposed: - return character - - codes: List[str] = decomposed.split(" ") - - return chr(int(codes[0], 16)) - - -@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) -def unicode_range(character: str) -> Optional[str]: - """ - Retrieve the Unicode range official name from a single character. - """ - character_ord: int = ord(character) - - for range_name, ord_range in UNICODE_RANGES_COMBINED.items(): - if character_ord in ord_range: - return range_name - - return None - - -@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) -def is_latin(character: str) -> bool: - try: - description: str = unicodedata.name(character) - except ValueError: - return False - return "LATIN" in description - - -@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) -def is_ascii(character: str) -> bool: - try: - character.encode("ascii") - except UnicodeEncodeError: - return False - return True - - -@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) -def is_punctuation(character: str) -> bool: - character_category: str = unicodedata.category(character) - - if "P" in character_category: - return True - - character_range: Optional[str] = unicode_range(character) - - if character_range is None: - return False - - return "Punctuation" in character_range - - -@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) -def is_symbol(character: str) -> bool: - character_category: str = unicodedata.category(character) - - if "S" in character_category or "N" in character_category: - return True - - character_range: Optional[str] = unicode_range(character) - - if character_range is None: - return False - - return "Forms" in character_range - - -@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) -def is_emoticon(character: str) -> bool: - character_range: Optional[str] = unicode_range(character) - - if character_range is None: - return False - - return "Emoticons" in character_range - - -@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) -def is_separator(character: str) -> bool: - if character.isspace() or character in {"|", "+", ",", ";", "<", ">"}: - return True - - character_category: str = unicodedata.category(character) - - return "Z" in character_category - - -@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) -def is_case_variable(character: str) -> bool: - return character.islower() != character.isupper() - - -def is_private_use_only(character: str) -> bool: - character_category: str = unicodedata.category(character) - - return character_category == "Co" - - -@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) -def is_cjk(character: str) -> bool: - try: - character_name = unicodedata.name(character) - except ValueError: - return False - - return "CJK" in character_name - - -@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) -def is_hiragana(character: str) -> bool: - try: - character_name = unicodedata.name(character) - except ValueError: - return False - - return "HIRAGANA" in character_name - - -@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) -def is_katakana(character: str) -> bool: - try: - character_name = unicodedata.name(character) - except ValueError: - return False - - return "KATAKANA" in character_name - - -@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) -def is_hangul(character: str) -> bool: - try: - character_name = unicodedata.name(character) - except ValueError: - return False - - return "HANGUL" in character_name - - -@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) -def is_thai(character: str) -> bool: - try: - character_name = unicodedata.name(character) - except ValueError: - return False - - return "THAI" in character_name - - -@lru_cache(maxsize=len(UNICODE_RANGES_COMBINED)) -def is_unicode_range_secondary(range_name: str) -> bool: - return any(keyword in range_name for keyword in UNICODE_SECONDARY_RANGE_KEYWORD) - - -@lru_cache(maxsize=UTF8_MAXIMAL_ALLOCATION) -def is_unprintable(character: str) -> bool: - return ( - character.isspace() is False # includes \n \t \r \v - and character.isprintable() is False - and character != "\x1A" # Why? Its the ASCII substitute character. - and character != "\ufeff" # bug discovered in Python, - # Zero Width No-Break Space located in Arabic Presentation Forms-B, Unicode 1.1 not acknowledged as space. - ) - - -def any_specified_encoding(sequence: bytes, search_zone: int = 4096) -> Optional[str]: - """ - Extract using ASCII-only decoder any specified encoding in the first n-bytes. - """ - if not isinstance(sequence, bytes): - raise TypeError - - seq_len: int = len(sequence) - - results: List[str] = findall( - RE_POSSIBLE_ENCODING_INDICATION, - sequence[: min(seq_len, search_zone)].decode("ascii", errors="ignore"), - ) - - if len(results) == 0: - return None - - for specified_encoding in results: - specified_encoding = specified_encoding.lower().replace("-", "_") - - encoding_alias: str - encoding_iana: str - - for encoding_alias, encoding_iana in aliases.items(): - if encoding_alias == specified_encoding: - return encoding_iana - if encoding_iana == specified_encoding: - return encoding_iana - - return None - - -@lru_cache(maxsize=128) -def is_multi_byte_encoding(name: str) -> bool: - """ - Verify is a specific encoding is a multi byte one based on it IANA name - """ - return name in { - "utf_8", - "utf_8_sig", - "utf_16", - "utf_16_be", - "utf_16_le", - "utf_32", - "utf_32_le", - "utf_32_be", - "utf_7", - } or issubclass( - importlib.import_module("encodings.{}".format(name)).IncrementalDecoder, - MultibyteIncrementalDecoder, - ) - - -def identify_sig_or_bom(sequence: bytes) -> Tuple[Optional[str], bytes]: - """ - Identify and extract SIG/BOM in given sequence. - """ - - for iana_encoding in ENCODING_MARKS: - marks: Union[bytes, List[bytes]] = ENCODING_MARKS[iana_encoding] - - if isinstance(marks, bytes): - marks = [marks] - - for mark in marks: - if sequence.startswith(mark): - return iana_encoding, mark - - return None, b"" - - -def should_strip_sig_or_bom(iana_encoding: str) -> bool: - return iana_encoding not in {"utf_16", "utf_32"} - - -def iana_name(cp_name: str, strict: bool = True) -> str: - cp_name = cp_name.lower().replace("-", "_") - - encoding_alias: str - encoding_iana: str - - for encoding_alias, encoding_iana in aliases.items(): - if cp_name in [encoding_alias, encoding_iana]: - return encoding_iana - - if strict: - raise ValueError("Unable to retrieve IANA for '{}'".format(cp_name)) - - return cp_name - - -def range_scan(decoded_sequence: str) -> List[str]: - ranges: Set[str] = set() - - for character in decoded_sequence: - character_range: Optional[str] = unicode_range(character) - - if character_range is None: - continue - - ranges.add(character_range) - - return list(ranges) - - -def cp_similarity(iana_name_a: str, iana_name_b: str) -> float: - - if is_multi_byte_encoding(iana_name_a) or is_multi_byte_encoding(iana_name_b): - return 0.0 - - decoder_a = importlib.import_module( - "encodings.{}".format(iana_name_a) - ).IncrementalDecoder - decoder_b = importlib.import_module( - "encodings.{}".format(iana_name_b) - ).IncrementalDecoder - - id_a: IncrementalDecoder = decoder_a(errors="ignore") - id_b: IncrementalDecoder = decoder_b(errors="ignore") - - character_match_count: int = 0 - - for i in range(255): - to_be_decoded: bytes = bytes([i]) - if id_a.decode(to_be_decoded) == id_b.decode(to_be_decoded): - character_match_count += 1 - - return character_match_count / 254 - - -def is_cp_similar(iana_name_a: str, iana_name_b: str) -> bool: - """ - Determine if two code page are at least 80% similar. IANA_SUPPORTED_SIMILAR dict was generated using - the function cp_similarity. - """ - return ( - iana_name_a in IANA_SUPPORTED_SIMILAR - and iana_name_b in IANA_SUPPORTED_SIMILAR[iana_name_a] - ) - - -def set_logging_handler( - name: str = "charset_normalizer", - level: int = logging.INFO, - format_string: str = "%(asctime)s | %(levelname)s | %(message)s", -) -> None: - - logger = logging.getLogger(name) - logger.setLevel(level) - - handler = logging.StreamHandler() - handler.setFormatter(logging.Formatter(format_string)) - logger.addHandler(handler) - - -def cut_sequence_chunks( - sequences: bytes, - encoding_iana: str, - offsets: range, - chunk_size: int, - bom_or_sig_available: bool, - strip_sig_or_bom: bool, - sig_payload: bytes, - is_multi_byte_decoder: bool, - decoded_payload: Optional[str] = None, -) -> Generator[str, None, None]: - - if decoded_payload and is_multi_byte_decoder is False: - for i in offsets: - chunk = decoded_payload[i : i + chunk_size] - if not chunk: - break - yield chunk - else: - for i in offsets: - chunk_end = i + chunk_size - if chunk_end > len(sequences) + 8: - continue - - cut_sequence = sequences[i : i + chunk_size] - - if bom_or_sig_available and strip_sig_or_bom is False: - cut_sequence = sig_payload + cut_sequence - - chunk = cut_sequence.decode( - encoding_iana, - errors="ignore" if is_multi_byte_decoder else "strict", - ) - - # multi-byte bad cutting detector and adjustment - # not the cleanest way to perform that fix but clever enough for now. - if is_multi_byte_decoder and i > 0 and sequences[i] >= 0x80: - - chunk_partial_size_chk: int = min(chunk_size, 16) - - if ( - decoded_payload - and chunk[:chunk_partial_size_chk] not in decoded_payload - ): - for j in range(i, i - 4, -1): - cut_sequence = sequences[j:chunk_end] - - if bom_or_sig_available and strip_sig_or_bom is False: - cut_sequence = sig_payload + cut_sequence - - chunk = cut_sequence.decode(encoding_iana, errors="ignore") - - if chunk[:chunk_partial_size_chk] in decoded_payload: - break - - yield chunk diff --git a/.venv/Lib/site-packages/charset_normalizer/version.py b/.venv/Lib/site-packages/charset_normalizer/version.py deleted file mode 100644 index 64c0dbd..0000000 --- a/.venv/Lib/site-packages/charset_normalizer/version.py +++ /dev/null @@ -1,6 +0,0 @@ -""" -Expose version -""" - -__version__ = "2.1.1" -VERSION = __version__.split(".") diff --git a/.venv/Lib/site-packages/dateutil/__init__.py b/.venv/Lib/site-packages/dateutil/__init__.py deleted file mode 100644 index 0defb82..0000000 --- a/.venv/Lib/site-packages/dateutil/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# -*- coding: utf-8 -*- -try: - from ._version import version as __version__ -except ImportError: - __version__ = 'unknown' - -__all__ = ['easter', 'parser', 'relativedelta', 'rrule', 'tz', - 'utils', 'zoneinfo'] diff --git a/.venv/Lib/site-packages/dateutil/__pycache__/__init__.cpython-38.pyc b/.venv/Lib/site-packages/dateutil/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index e48f1e8..0000000 Binary files a/.venv/Lib/site-packages/dateutil/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/dateutil/__pycache__/_common.cpython-38.pyc b/.venv/Lib/site-packages/dateutil/__pycache__/_common.cpython-38.pyc deleted file mode 100644 index 95bd1d3..0000000 Binary files a/.venv/Lib/site-packages/dateutil/__pycache__/_common.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/dateutil/__pycache__/_version.cpython-38.pyc b/.venv/Lib/site-packages/dateutil/__pycache__/_version.cpython-38.pyc deleted file mode 100644 index 62c3935..0000000 Binary files a/.venv/Lib/site-packages/dateutil/__pycache__/_version.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/dateutil/__pycache__/easter.cpython-38.pyc b/.venv/Lib/site-packages/dateutil/__pycache__/easter.cpython-38.pyc deleted file mode 100644 index 369148a..0000000 Binary files a/.venv/Lib/site-packages/dateutil/__pycache__/easter.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/dateutil/__pycache__/relativedelta.cpython-38.pyc b/.venv/Lib/site-packages/dateutil/__pycache__/relativedelta.cpython-38.pyc deleted file mode 100644 index 15388e3..0000000 Binary files a/.venv/Lib/site-packages/dateutil/__pycache__/relativedelta.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/dateutil/__pycache__/rrule.cpython-38.pyc b/.venv/Lib/site-packages/dateutil/__pycache__/rrule.cpython-38.pyc deleted file mode 100644 index 94662a7..0000000 Binary files a/.venv/Lib/site-packages/dateutil/__pycache__/rrule.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/dateutil/__pycache__/tzwin.cpython-38.pyc b/.venv/Lib/site-packages/dateutil/__pycache__/tzwin.cpython-38.pyc deleted file mode 100644 index f241bb8..0000000 Binary files a/.venv/Lib/site-packages/dateutil/__pycache__/tzwin.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/dateutil/__pycache__/utils.cpython-38.pyc b/.venv/Lib/site-packages/dateutil/__pycache__/utils.cpython-38.pyc deleted file mode 100644 index 5a7e953..0000000 Binary files a/.venv/Lib/site-packages/dateutil/__pycache__/utils.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/dateutil/_common.py b/.venv/Lib/site-packages/dateutil/_common.py deleted file mode 100644 index 4eb2659..0000000 --- a/.venv/Lib/site-packages/dateutil/_common.py +++ /dev/null @@ -1,43 +0,0 @@ -""" -Common code used in multiple modules. -""" - - -class weekday(object): - __slots__ = ["weekday", "n"] - - def __init__(self, weekday, n=None): - self.weekday = weekday - self.n = n - - def __call__(self, n): - if n == self.n: - return self - else: - return self.__class__(self.weekday, n) - - def __eq__(self, other): - try: - if self.weekday != other.weekday or self.n != other.n: - return False - except AttributeError: - return False - return True - - def __hash__(self): - return hash(( - self.weekday, - self.n, - )) - - def __ne__(self, other): - return not (self == other) - - def __repr__(self): - s = ("MO", "TU", "WE", "TH", "FR", "SA", "SU")[self.weekday] - if not self.n: - return s - else: - return "%s(%+d)" % (s, self.n) - -# vim:ts=4:sw=4:et diff --git a/.venv/Lib/site-packages/dateutil/_version.py b/.venv/Lib/site-packages/dateutil/_version.py deleted file mode 100644 index b723056..0000000 --- a/.venv/Lib/site-packages/dateutil/_version.py +++ /dev/null @@ -1,5 +0,0 @@ -# coding: utf-8 -# file generated by setuptools_scm -# don't change, don't track in version control -version = '2.8.2' -version_tuple = (2, 8, 2) diff --git a/.venv/Lib/site-packages/dateutil/easter.py b/.venv/Lib/site-packages/dateutil/easter.py deleted file mode 100644 index f74d1f7..0000000 --- a/.venv/Lib/site-packages/dateutil/easter.py +++ /dev/null @@ -1,89 +0,0 @@ -# -*- coding: utf-8 -*- -""" -This module offers a generic Easter computing method for any given year, using -Western, Orthodox or Julian algorithms. -""" - -import datetime - -__all__ = ["easter", "EASTER_JULIAN", "EASTER_ORTHODOX", "EASTER_WESTERN"] - -EASTER_JULIAN = 1 -EASTER_ORTHODOX = 2 -EASTER_WESTERN = 3 - - -def easter(year, method=EASTER_WESTERN): - """ - This method was ported from the work done by GM Arts, - on top of the algorithm by Claus Tondering, which was - based in part on the algorithm of Ouding (1940), as - quoted in "Explanatory Supplement to the Astronomical - Almanac", P. Kenneth Seidelmann, editor. - - This algorithm implements three different Easter - calculation methods: - - 1. Original calculation in Julian calendar, valid in - dates after 326 AD - 2. Original method, with date converted to Gregorian - calendar, valid in years 1583 to 4099 - 3. Revised method, in Gregorian calendar, valid in - years 1583 to 4099 as well - - These methods are represented by the constants: - - * ``EASTER_JULIAN = 1`` - * ``EASTER_ORTHODOX = 2`` - * ``EASTER_WESTERN = 3`` - - The default method is method 3. - - More about the algorithm may be found at: - - `GM Arts: Easter Algorithms `_ - - and - - `The Calendar FAQ: Easter `_ - - """ - - if not (1 <= method <= 3): - raise ValueError("invalid method") - - # g - Golden year - 1 - # c - Century - # h - (23 - Epact) mod 30 - # i - Number of days from March 21 to Paschal Full Moon - # j - Weekday for PFM (0=Sunday, etc) - # p - Number of days from March 21 to Sunday on or before PFM - # (-6 to 28 methods 1 & 3, to 56 for method 2) - # e - Extra days to add for method 2 (converting Julian - # date to Gregorian date) - - y = year - g = y % 19 - e = 0 - if method < 3: - # Old method - i = (19*g + 15) % 30 - j = (y + y//4 + i) % 7 - if method == 2: - # Extra dates to convert Julian to Gregorian date - e = 10 - if y > 1600: - e = e + y//100 - 16 - (y//100 - 16)//4 - else: - # New method - c = y//100 - h = (c - c//4 - (8*c + 13)//25 + 19*g + 15) % 30 - i = h - (h//28)*(1 - (h//28)*(29//(h + 1))*((21 - g)//11)) - j = (y + y//4 + i + 2 - c + c//4) % 7 - - # p can be from -6 to 56 corresponding to dates 22 March to 23 May - # (later dates apply to method 2, although 23 May never actually occurs) - p = i - j + e - d = 1 + (p + 27 + (p + 6)//40) % 31 - m = 3 + (p + 26)//30 - return datetime.date(int(y), int(m), int(d)) diff --git a/.venv/Lib/site-packages/dateutil/parser/__init__.py b/.venv/Lib/site-packages/dateutil/parser/__init__.py deleted file mode 100644 index d174b0e..0000000 --- a/.venv/Lib/site-packages/dateutil/parser/__init__.py +++ /dev/null @@ -1,61 +0,0 @@ -# -*- coding: utf-8 -*- -from ._parser import parse, parser, parserinfo, ParserError -from ._parser import DEFAULTPARSER, DEFAULTTZPARSER -from ._parser import UnknownTimezoneWarning - -from ._parser import __doc__ - -from .isoparser import isoparser, isoparse - -__all__ = ['parse', 'parser', 'parserinfo', - 'isoparse', 'isoparser', - 'ParserError', - 'UnknownTimezoneWarning'] - - -### -# Deprecate portions of the private interface so that downstream code that -# is improperly relying on it is given *some* notice. - - -def __deprecated_private_func(f): - from functools import wraps - import warnings - - msg = ('{name} is a private function and may break without warning, ' - 'it will be moved and or renamed in future versions.') - msg = msg.format(name=f.__name__) - - @wraps(f) - def deprecated_func(*args, **kwargs): - warnings.warn(msg, DeprecationWarning) - return f(*args, **kwargs) - - return deprecated_func - -def __deprecate_private_class(c): - import warnings - - msg = ('{name} is a private class and may break without warning, ' - 'it will be moved and or renamed in future versions.') - msg = msg.format(name=c.__name__) - - class private_class(c): - __doc__ = c.__doc__ - - def __init__(self, *args, **kwargs): - warnings.warn(msg, DeprecationWarning) - super(private_class, self).__init__(*args, **kwargs) - - private_class.__name__ = c.__name__ - - return private_class - - -from ._parser import _timelex, _resultbase -from ._parser import _tzparser, _parsetz - -_timelex = __deprecate_private_class(_timelex) -_tzparser = __deprecate_private_class(_tzparser) -_resultbase = __deprecate_private_class(_resultbase) -_parsetz = __deprecated_private_func(_parsetz) diff --git a/.venv/Lib/site-packages/dateutil/parser/__pycache__/__init__.cpython-38.pyc b/.venv/Lib/site-packages/dateutil/parser/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index 727b2c3..0000000 Binary files a/.venv/Lib/site-packages/dateutil/parser/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/dateutil/parser/__pycache__/_parser.cpython-38.pyc b/.venv/Lib/site-packages/dateutil/parser/__pycache__/_parser.cpython-38.pyc deleted file mode 100644 index 45952da..0000000 Binary files a/.venv/Lib/site-packages/dateutil/parser/__pycache__/_parser.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/dateutil/parser/__pycache__/isoparser.cpython-38.pyc b/.venv/Lib/site-packages/dateutil/parser/__pycache__/isoparser.cpython-38.pyc deleted file mode 100644 index 2b94abb..0000000 Binary files a/.venv/Lib/site-packages/dateutil/parser/__pycache__/isoparser.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/dateutil/parser/_parser.py b/.venv/Lib/site-packages/dateutil/parser/_parser.py deleted file mode 100644 index 37d1663..0000000 --- a/.venv/Lib/site-packages/dateutil/parser/_parser.py +++ /dev/null @@ -1,1613 +0,0 @@ -# -*- coding: utf-8 -*- -""" -This module offers a generic date/time string parser which is able to parse -most known formats to represent a date and/or time. - -This module attempts to be forgiving with regards to unlikely input formats, -returning a datetime object even for dates which are ambiguous. If an element -of a date/time stamp is omitted, the following rules are applied: - -- If AM or PM is left unspecified, a 24-hour clock is assumed, however, an hour - on a 12-hour clock (``0 <= hour <= 12``) *must* be specified if AM or PM is - specified. -- If a time zone is omitted, a timezone-naive datetime is returned. - -If any other elements are missing, they are taken from the -:class:`datetime.datetime` object passed to the parameter ``default``. If this -results in a day number exceeding the valid number of days per month, the -value falls back to the end of the month. - -Additional resources about date/time string formats can be found below: - -- `A summary of the international standard date and time notation - `_ -- `W3C Date and Time Formats `_ -- `Time Formats (Planetary Rings Node) `_ -- `CPAN ParseDate module - `_ -- `Java SimpleDateFormat Class - `_ -""" -from __future__ import unicode_literals - -import datetime -import re -import string -import time -import warnings - -from calendar import monthrange -from io import StringIO - -import six -from six import integer_types, text_type - -from decimal import Decimal - -from warnings import warn - -from .. import relativedelta -from .. import tz - -__all__ = ["parse", "parserinfo", "ParserError"] - - -# TODO: pandas.core.tools.datetimes imports this explicitly. Might be worth -# making public and/or figuring out if there is something we can -# take off their plate. -class _timelex(object): - # Fractional seconds are sometimes split by a comma - _split_decimal = re.compile("([.,])") - - def __init__(self, instream): - if isinstance(instream, (bytes, bytearray)): - instream = instream.decode() - - if isinstance(instream, text_type): - instream = StringIO(instream) - elif getattr(instream, 'read', None) is None: - raise TypeError('Parser must be a string or character stream, not ' - '{itype}'.format(itype=instream.__class__.__name__)) - - self.instream = instream - self.charstack = [] - self.tokenstack = [] - self.eof = False - - def get_token(self): - """ - This function breaks the time string into lexical units (tokens), which - can be parsed by the parser. Lexical units are demarcated by changes in - the character set, so any continuous string of letters is considered - one unit, any continuous string of numbers is considered one unit. - - The main complication arises from the fact that dots ('.') can be used - both as separators (e.g. "Sep.20.2009") or decimal points (e.g. - "4:30:21.447"). As such, it is necessary to read the full context of - any dot-separated strings before breaking it into tokens; as such, this - function maintains a "token stack", for when the ambiguous context - demands that multiple tokens be parsed at once. - """ - if self.tokenstack: - return self.tokenstack.pop(0) - - seenletters = False - token = None - state = None - - while not self.eof: - # We only realize that we've reached the end of a token when we - # find a character that's not part of the current token - since - # that character may be part of the next token, it's stored in the - # charstack. - if self.charstack: - nextchar = self.charstack.pop(0) - else: - nextchar = self.instream.read(1) - while nextchar == '\x00': - nextchar = self.instream.read(1) - - if not nextchar: - self.eof = True - break - elif not state: - # First character of the token - determines if we're starting - # to parse a word, a number or something else. - token = nextchar - if self.isword(nextchar): - state = 'a' - elif self.isnum(nextchar): - state = '0' - elif self.isspace(nextchar): - token = ' ' - break # emit token - else: - break # emit token - elif state == 'a': - # If we've already started reading a word, we keep reading - # letters until we find something that's not part of a word. - seenletters = True - if self.isword(nextchar): - token += nextchar - elif nextchar == '.': - token += nextchar - state = 'a.' - else: - self.charstack.append(nextchar) - break # emit token - elif state == '0': - # If we've already started reading a number, we keep reading - # numbers until we find something that doesn't fit. - if self.isnum(nextchar): - token += nextchar - elif nextchar == '.' or (nextchar == ',' and len(token) >= 2): - token += nextchar - state = '0.' - else: - self.charstack.append(nextchar) - break # emit token - elif state == 'a.': - # If we've seen some letters and a dot separator, continue - # parsing, and the tokens will be broken up later. - seenletters = True - if nextchar == '.' or self.isword(nextchar): - token += nextchar - elif self.isnum(nextchar) and token[-1] == '.': - token += nextchar - state = '0.' - else: - self.charstack.append(nextchar) - break # emit token - elif state == '0.': - # If we've seen at least one dot separator, keep going, we'll - # break up the tokens later. - if nextchar == '.' or self.isnum(nextchar): - token += nextchar - elif self.isword(nextchar) and token[-1] == '.': - token += nextchar - state = 'a.' - else: - self.charstack.append(nextchar) - break # emit token - - if (state in ('a.', '0.') and (seenletters or token.count('.') > 1 or - token[-1] in '.,')): - l = self._split_decimal.split(token) - token = l[0] - for tok in l[1:]: - if tok: - self.tokenstack.append(tok) - - if state == '0.' and token.count('.') == 0: - token = token.replace(',', '.') - - return token - - def __iter__(self): - return self - - def __next__(self): - token = self.get_token() - if token is None: - raise StopIteration - - return token - - def next(self): - return self.__next__() # Python 2.x support - - @classmethod - def split(cls, s): - return list(cls(s)) - - @classmethod - def isword(cls, nextchar): - """ Whether or not the next character is part of a word """ - return nextchar.isalpha() - - @classmethod - def isnum(cls, nextchar): - """ Whether the next character is part of a number """ - return nextchar.isdigit() - - @classmethod - def isspace(cls, nextchar): - """ Whether the next character is whitespace """ - return nextchar.isspace() - - -class _resultbase(object): - - def __init__(self): - for attr in self.__slots__: - setattr(self, attr, None) - - def _repr(self, classname): - l = [] - for attr in self.__slots__: - value = getattr(self, attr) - if value is not None: - l.append("%s=%s" % (attr, repr(value))) - return "%s(%s)" % (classname, ", ".join(l)) - - def __len__(self): - return (sum(getattr(self, attr) is not None - for attr in self.__slots__)) - - def __repr__(self): - return self._repr(self.__class__.__name__) - - -class parserinfo(object): - """ - Class which handles what inputs are accepted. Subclass this to customize - the language and acceptable values for each parameter. - - :param dayfirst: - Whether to interpret the first value in an ambiguous 3-integer date - (e.g. 01/05/09) as the day (``True``) or month (``False``). If - ``yearfirst`` is set to ``True``, this distinguishes between YDM - and YMD. Default is ``False``. - - :param yearfirst: - Whether to interpret the first value in an ambiguous 3-integer date - (e.g. 01/05/09) as the year. If ``True``, the first number is taken - to be the year, otherwise the last number is taken to be the year. - Default is ``False``. - """ - - # m from a.m/p.m, t from ISO T separator - JUMP = [" ", ".", ",", ";", "-", "/", "'", - "at", "on", "and", "ad", "m", "t", "of", - "st", "nd", "rd", "th"] - - WEEKDAYS = [("Mon", "Monday"), - ("Tue", "Tuesday"), # TODO: "Tues" - ("Wed", "Wednesday"), - ("Thu", "Thursday"), # TODO: "Thurs" - ("Fri", "Friday"), - ("Sat", "Saturday"), - ("Sun", "Sunday")] - MONTHS = [("Jan", "January"), - ("Feb", "February"), # TODO: "Febr" - ("Mar", "March"), - ("Apr", "April"), - ("May", "May"), - ("Jun", "June"), - ("Jul", "July"), - ("Aug", "August"), - ("Sep", "Sept", "September"), - ("Oct", "October"), - ("Nov", "November"), - ("Dec", "December")] - HMS = [("h", "hour", "hours"), - ("m", "minute", "minutes"), - ("s", "second", "seconds")] - AMPM = [("am", "a"), - ("pm", "p")] - UTCZONE = ["UTC", "GMT", "Z", "z"] - PERTAIN = ["of"] - TZOFFSET = {} - # TODO: ERA = ["AD", "BC", "CE", "BCE", "Stardate", - # "Anno Domini", "Year of Our Lord"] - - def __init__(self, dayfirst=False, yearfirst=False): - self._jump = self._convert(self.JUMP) - self._weekdays = self._convert(self.WEEKDAYS) - self._months = self._convert(self.MONTHS) - self._hms = self._convert(self.HMS) - self._ampm = self._convert(self.AMPM) - self._utczone = self._convert(self.UTCZONE) - self._pertain = self._convert(self.PERTAIN) - - self.dayfirst = dayfirst - self.yearfirst = yearfirst - - self._year = time.localtime().tm_year - self._century = self._year // 100 * 100 - - def _convert(self, lst): - dct = {} - for i, v in enumerate(lst): - if isinstance(v, tuple): - for v in v: - dct[v.lower()] = i - else: - dct[v.lower()] = i - return dct - - def jump(self, name): - return name.lower() in self._jump - - def weekday(self, name): - try: - return self._weekdays[name.lower()] - except KeyError: - pass - return None - - def month(self, name): - try: - return self._months[name.lower()] + 1 - except KeyError: - pass - return None - - def hms(self, name): - try: - return self._hms[name.lower()] - except KeyError: - return None - - def ampm(self, name): - try: - return self._ampm[name.lower()] - except KeyError: - return None - - def pertain(self, name): - return name.lower() in self._pertain - - def utczone(self, name): - return name.lower() in self._utczone - - def tzoffset(self, name): - if name in self._utczone: - return 0 - - return self.TZOFFSET.get(name) - - def convertyear(self, year, century_specified=False): - """ - Converts two-digit years to year within [-50, 49] - range of self._year (current local time) - """ - - # Function contract is that the year is always positive - assert year >= 0 - - if year < 100 and not century_specified: - # assume current century to start - year += self._century - - if year >= self._year + 50: # if too far in future - year -= 100 - elif year < self._year - 50: # if too far in past - year += 100 - - return year - - def validate(self, res): - # move to info - if res.year is not None: - res.year = self.convertyear(res.year, res.century_specified) - - if ((res.tzoffset == 0 and not res.tzname) or - (res.tzname == 'Z' or res.tzname == 'z')): - res.tzname = "UTC" - res.tzoffset = 0 - elif res.tzoffset != 0 and res.tzname and self.utczone(res.tzname): - res.tzoffset = 0 - return True - - -class _ymd(list): - def __init__(self, *args, **kwargs): - super(self.__class__, self).__init__(*args, **kwargs) - self.century_specified = False - self.dstridx = None - self.mstridx = None - self.ystridx = None - - @property - def has_year(self): - return self.ystridx is not None - - @property - def has_month(self): - return self.mstridx is not None - - @property - def has_day(self): - return self.dstridx is not None - - def could_be_day(self, value): - if self.has_day: - return False - elif not self.has_month: - return 1 <= value <= 31 - elif not self.has_year: - # Be permissive, assume leap year - month = self[self.mstridx] - return 1 <= value <= monthrange(2000, month)[1] - else: - month = self[self.mstridx] - year = self[self.ystridx] - return 1 <= value <= monthrange(year, month)[1] - - def append(self, val, label=None): - if hasattr(val, '__len__'): - if val.isdigit() and len(val) > 2: - self.century_specified = True - if label not in [None, 'Y']: # pragma: no cover - raise ValueError(label) - label = 'Y' - elif val > 100: - self.century_specified = True - if label not in [None, 'Y']: # pragma: no cover - raise ValueError(label) - label = 'Y' - - super(self.__class__, self).append(int(val)) - - if label == 'M': - if self.has_month: - raise ValueError('Month is already set') - self.mstridx = len(self) - 1 - elif label == 'D': - if self.has_day: - raise ValueError('Day is already set') - self.dstridx = len(self) - 1 - elif label == 'Y': - if self.has_year: - raise ValueError('Year is already set') - self.ystridx = len(self) - 1 - - def _resolve_from_stridxs(self, strids): - """ - Try to resolve the identities of year/month/day elements using - ystridx, mstridx, and dstridx, if enough of these are specified. - """ - if len(self) == 3 and len(strids) == 2: - # we can back out the remaining stridx value - missing = [x for x in range(3) if x not in strids.values()] - key = [x for x in ['y', 'm', 'd'] if x not in strids] - assert len(missing) == len(key) == 1 - key = key[0] - val = missing[0] - strids[key] = val - - assert len(self) == len(strids) # otherwise this should not be called - out = {key: self[strids[key]] for key in strids} - return (out.get('y'), out.get('m'), out.get('d')) - - def resolve_ymd(self, yearfirst, dayfirst): - len_ymd = len(self) - year, month, day = (None, None, None) - - strids = (('y', self.ystridx), - ('m', self.mstridx), - ('d', self.dstridx)) - - strids = {key: val for key, val in strids if val is not None} - if (len(self) == len(strids) > 0 or - (len(self) == 3 and len(strids) == 2)): - return self._resolve_from_stridxs(strids) - - mstridx = self.mstridx - - if len_ymd > 3: - raise ValueError("More than three YMD values") - elif len_ymd == 1 or (mstridx is not None and len_ymd == 2): - # One member, or two members with a month string - if mstridx is not None: - month = self[mstridx] - # since mstridx is 0 or 1, self[mstridx-1] always - # looks up the other element - other = self[mstridx - 1] - else: - other = self[0] - - if len_ymd > 1 or mstridx is None: - if other > 31: - year = other - else: - day = other - - elif len_ymd == 2: - # Two members with numbers - if self[0] > 31: - # 99-01 - year, month = self - elif self[1] > 31: - # 01-99 - month, year = self - elif dayfirst and self[1] <= 12: - # 13-01 - day, month = self - else: - # 01-13 - month, day = self - - elif len_ymd == 3: - # Three members - if mstridx == 0: - if self[1] > 31: - # Apr-2003-25 - month, year, day = self - else: - month, day, year = self - elif mstridx == 1: - if self[0] > 31 or (yearfirst and self[2] <= 31): - # 99-Jan-01 - year, month, day = self - else: - # 01-Jan-01 - # Give precedence to day-first, since - # two-digit years is usually hand-written. - day, month, year = self - - elif mstridx == 2: - # WTF!? - if self[1] > 31: - # 01-99-Jan - day, year, month = self - else: - # 99-01-Jan - year, day, month = self - - else: - if (self[0] > 31 or - self.ystridx == 0 or - (yearfirst and self[1] <= 12 and self[2] <= 31)): - # 99-01-01 - if dayfirst and self[2] <= 12: - year, day, month = self - else: - year, month, day = self - elif self[0] > 12 or (dayfirst and self[1] <= 12): - # 13-01-01 - day, month, year = self - else: - # 01-13-01 - month, day, year = self - - return year, month, day - - -class parser(object): - def __init__(self, info=None): - self.info = info or parserinfo() - - def parse(self, timestr, default=None, - ignoretz=False, tzinfos=None, **kwargs): - """ - Parse the date/time string into a :class:`datetime.datetime` object. - - :param timestr: - Any date/time string using the supported formats. - - :param default: - The default datetime object, if this is a datetime object and not - ``None``, elements specified in ``timestr`` replace elements in the - default object. - - :param ignoretz: - If set ``True``, time zones in parsed strings are ignored and a - naive :class:`datetime.datetime` object is returned. - - :param tzinfos: - Additional time zone names / aliases which may be present in the - string. This argument maps time zone names (and optionally offsets - from those time zones) to time zones. This parameter can be a - dictionary with timezone aliases mapping time zone names to time - zones or a function taking two parameters (``tzname`` and - ``tzoffset``) and returning a time zone. - - The timezones to which the names are mapped can be an integer - offset from UTC in seconds or a :class:`tzinfo` object. - - .. doctest:: - :options: +NORMALIZE_WHITESPACE - - >>> from dateutil.parser import parse - >>> from dateutil.tz import gettz - >>> tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")} - >>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos) - datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200)) - >>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos) - datetime.datetime(2012, 1, 19, 17, 21, - tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago')) - - This parameter is ignored if ``ignoretz`` is set. - - :param \\*\\*kwargs: - Keyword arguments as passed to ``_parse()``. - - :return: - Returns a :class:`datetime.datetime` object or, if the - ``fuzzy_with_tokens`` option is ``True``, returns a tuple, the - first element being a :class:`datetime.datetime` object, the second - a tuple containing the fuzzy tokens. - - :raises ParserError: - Raised for invalid or unknown string format, if the provided - :class:`tzinfo` is not in a valid format, or if an invalid date - would be created. - - :raises TypeError: - Raised for non-string or character stream input. - - :raises OverflowError: - Raised if the parsed date exceeds the largest valid C integer on - your system. - """ - - if default is None: - default = datetime.datetime.now().replace(hour=0, minute=0, - second=0, microsecond=0) - - res, skipped_tokens = self._parse(timestr, **kwargs) - - if res is None: - raise ParserError("Unknown string format: %s", timestr) - - if len(res) == 0: - raise ParserError("String does not contain a date: %s", timestr) - - try: - ret = self._build_naive(res, default) - except ValueError as e: - six.raise_from(ParserError(str(e) + ": %s", timestr), e) - - if not ignoretz: - ret = self._build_tzaware(ret, res, tzinfos) - - if kwargs.get('fuzzy_with_tokens', False): - return ret, skipped_tokens - else: - return ret - - class _result(_resultbase): - __slots__ = ["year", "month", "day", "weekday", - "hour", "minute", "second", "microsecond", - "tzname", "tzoffset", "ampm","any_unused_tokens"] - - def _parse(self, timestr, dayfirst=None, yearfirst=None, fuzzy=False, - fuzzy_with_tokens=False): - """ - Private method which performs the heavy lifting of parsing, called from - ``parse()``, which passes on its ``kwargs`` to this function. - - :param timestr: - The string to parse. - - :param dayfirst: - Whether to interpret the first value in an ambiguous 3-integer date - (e.g. 01/05/09) as the day (``True``) or month (``False``). If - ``yearfirst`` is set to ``True``, this distinguishes between YDM - and YMD. If set to ``None``, this value is retrieved from the - current :class:`parserinfo` object (which itself defaults to - ``False``). - - :param yearfirst: - Whether to interpret the first value in an ambiguous 3-integer date - (e.g. 01/05/09) as the year. If ``True``, the first number is taken - to be the year, otherwise the last number is taken to be the year. - If this is set to ``None``, the value is retrieved from the current - :class:`parserinfo` object (which itself defaults to ``False``). - - :param fuzzy: - Whether to allow fuzzy parsing, allowing for string like "Today is - January 1, 2047 at 8:21:00AM". - - :param fuzzy_with_tokens: - If ``True``, ``fuzzy`` is automatically set to True, and the parser - will return a tuple where the first element is the parsed - :class:`datetime.datetime` datetimestamp and the second element is - a tuple containing the portions of the string which were ignored: - - .. doctest:: - - >>> from dateutil.parser import parse - >>> parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True) - (datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at ')) - - """ - if fuzzy_with_tokens: - fuzzy = True - - info = self.info - - if dayfirst is None: - dayfirst = info.dayfirst - - if yearfirst is None: - yearfirst = info.yearfirst - - res = self._result() - l = _timelex.split(timestr) # Splits the timestr into tokens - - skipped_idxs = [] - - # year/month/day list - ymd = _ymd() - - len_l = len(l) - i = 0 - try: - while i < len_l: - - # Check if it's a number - value_repr = l[i] - try: - value = float(value_repr) - except ValueError: - value = None - - if value is not None: - # Numeric token - i = self._parse_numeric_token(l, i, info, ymd, res, fuzzy) - - # Check weekday - elif info.weekday(l[i]) is not None: - value = info.weekday(l[i]) - res.weekday = value - - # Check month name - elif info.month(l[i]) is not None: - value = info.month(l[i]) - ymd.append(value, 'M') - - if i + 1 < len_l: - if l[i + 1] in ('-', '/'): - # Jan-01[-99] - sep = l[i + 1] - ymd.append(l[i + 2]) - - if i + 3 < len_l and l[i + 3] == sep: - # Jan-01-99 - ymd.append(l[i + 4]) - i += 2 - - i += 2 - - elif (i + 4 < len_l and l[i + 1] == l[i + 3] == ' ' and - info.pertain(l[i + 2])): - # Jan of 01 - # In this case, 01 is clearly year - if l[i + 4].isdigit(): - # Convert it here to become unambiguous - value = int(l[i + 4]) - year = str(info.convertyear(value)) - ymd.append(year, 'Y') - else: - # Wrong guess - pass - # TODO: not hit in tests - i += 4 - - # Check am/pm - elif info.ampm(l[i]) is not None: - value = info.ampm(l[i]) - val_is_ampm = self._ampm_valid(res.hour, res.ampm, fuzzy) - - if val_is_ampm: - res.hour = self._adjust_ampm(res.hour, value) - res.ampm = value - - elif fuzzy: - skipped_idxs.append(i) - - # Check for a timezone name - elif self._could_be_tzname(res.hour, res.tzname, res.tzoffset, l[i]): - res.tzname = l[i] - res.tzoffset = info.tzoffset(res.tzname) - - # Check for something like GMT+3, or BRST+3. Notice - # that it doesn't mean "I am 3 hours after GMT", but - # "my time +3 is GMT". If found, we reverse the - # logic so that timezone parsing code will get it - # right. - if i + 1 < len_l and l[i + 1] in ('+', '-'): - l[i + 1] = ('+', '-')[l[i + 1] == '+'] - res.tzoffset = None - if info.utczone(res.tzname): - # With something like GMT+3, the timezone - # is *not* GMT. - res.tzname = None - - # Check for a numbered timezone - elif res.hour is not None and l[i] in ('+', '-'): - signal = (-1, 1)[l[i] == '+'] - len_li = len(l[i + 1]) - - # TODO: check that l[i + 1] is integer? - if len_li == 4: - # -0300 - hour_offset = int(l[i + 1][:2]) - min_offset = int(l[i + 1][2:]) - elif i + 2 < len_l and l[i + 2] == ':': - # -03:00 - hour_offset = int(l[i + 1]) - min_offset = int(l[i + 3]) # TODO: Check that l[i+3] is minute-like? - i += 2 - elif len_li <= 2: - # -[0]3 - hour_offset = int(l[i + 1][:2]) - min_offset = 0 - else: - raise ValueError(timestr) - - res.tzoffset = signal * (hour_offset * 3600 + min_offset * 60) - - # Look for a timezone name between parenthesis - if (i + 5 < len_l and - info.jump(l[i + 2]) and l[i + 3] == '(' and - l[i + 5] == ')' and - 3 <= len(l[i + 4]) and - self._could_be_tzname(res.hour, res.tzname, - None, l[i + 4])): - # -0300 (BRST) - res.tzname = l[i + 4] - i += 4 - - i += 1 - - # Check jumps - elif not (info.jump(l[i]) or fuzzy): - raise ValueError(timestr) - - else: - skipped_idxs.append(i) - i += 1 - - # Process year/month/day - year, month, day = ymd.resolve_ymd(yearfirst, dayfirst) - - res.century_specified = ymd.century_specified - res.year = year - res.month = month - res.day = day - - except (IndexError, ValueError): - return None, None - - if not info.validate(res): - return None, None - - if fuzzy_with_tokens: - skipped_tokens = self._recombine_skipped(l, skipped_idxs) - return res, tuple(skipped_tokens) - else: - return res, None - - def _parse_numeric_token(self, tokens, idx, info, ymd, res, fuzzy): - # Token is a number - value_repr = tokens[idx] - try: - value = self._to_decimal(value_repr) - except Exception as e: - six.raise_from(ValueError('Unknown numeric token'), e) - - len_li = len(value_repr) - - len_l = len(tokens) - - if (len(ymd) == 3 and len_li in (2, 4) and - res.hour is None and - (idx + 1 >= len_l or - (tokens[idx + 1] != ':' and - info.hms(tokens[idx + 1]) is None))): - # 19990101T23[59] - s = tokens[idx] - res.hour = int(s[:2]) - - if len_li == 4: - res.minute = int(s[2:]) - - elif len_li == 6 or (len_li > 6 and tokens[idx].find('.') == 6): - # YYMMDD or HHMMSS[.ss] - s = tokens[idx] - - if not ymd and '.' not in tokens[idx]: - ymd.append(s[:2]) - ymd.append(s[2:4]) - ymd.append(s[4:]) - else: - # 19990101T235959[.59] - - # TODO: Check if res attributes already set. - res.hour = int(s[:2]) - res.minute = int(s[2:4]) - res.second, res.microsecond = self._parsems(s[4:]) - - elif len_li in (8, 12, 14): - # YYYYMMDD - s = tokens[idx] - ymd.append(s[:4], 'Y') - ymd.append(s[4:6]) - ymd.append(s[6:8]) - - if len_li > 8: - res.hour = int(s[8:10]) - res.minute = int(s[10:12]) - - if len_li > 12: - res.second = int(s[12:]) - - elif self._find_hms_idx(idx, tokens, info, allow_jump=True) is not None: - # HH[ ]h or MM[ ]m or SS[.ss][ ]s - hms_idx = self._find_hms_idx(idx, tokens, info, allow_jump=True) - (idx, hms) = self._parse_hms(idx, tokens, info, hms_idx) - if hms is not None: - # TODO: checking that hour/minute/second are not - # already set? - self._assign_hms(res, value_repr, hms) - - elif idx + 2 < len_l and tokens[idx + 1] == ':': - # HH:MM[:SS[.ss]] - res.hour = int(value) - value = self._to_decimal(tokens[idx + 2]) # TODO: try/except for this? - (res.minute, res.second) = self._parse_min_sec(value) - - if idx + 4 < len_l and tokens[idx + 3] == ':': - res.second, res.microsecond = self._parsems(tokens[idx + 4]) - - idx += 2 - - idx += 2 - - elif idx + 1 < len_l and tokens[idx + 1] in ('-', '/', '.'): - sep = tokens[idx + 1] - ymd.append(value_repr) - - if idx + 2 < len_l and not info.jump(tokens[idx + 2]): - if tokens[idx + 2].isdigit(): - # 01-01[-01] - ymd.append(tokens[idx + 2]) - else: - # 01-Jan[-01] - value = info.month(tokens[idx + 2]) - - if value is not None: - ymd.append(value, 'M') - else: - raise ValueError() - - if idx + 3 < len_l and tokens[idx + 3] == sep: - # We have three members - value = info.month(tokens[idx + 4]) - - if value is not None: - ymd.append(value, 'M') - else: - ymd.append(tokens[idx + 4]) - idx += 2 - - idx += 1 - idx += 1 - - elif idx + 1 >= len_l or info.jump(tokens[idx + 1]): - if idx + 2 < len_l and info.ampm(tokens[idx + 2]) is not None: - # 12 am - hour = int(value) - res.hour = self._adjust_ampm(hour, info.ampm(tokens[idx + 2])) - idx += 1 - else: - # Year, month or day - ymd.append(value) - idx += 1 - - elif info.ampm(tokens[idx + 1]) is not None and (0 <= value < 24): - # 12am - hour = int(value) - res.hour = self._adjust_ampm(hour, info.ampm(tokens[idx + 1])) - idx += 1 - - elif ymd.could_be_day(value): - ymd.append(value) - - elif not fuzzy: - raise ValueError() - - return idx - - def _find_hms_idx(self, idx, tokens, info, allow_jump): - len_l = len(tokens) - - if idx+1 < len_l and info.hms(tokens[idx+1]) is not None: - # There is an "h", "m", or "s" label following this token. We take - # assign the upcoming label to the current token. - # e.g. the "12" in 12h" - hms_idx = idx + 1 - - elif (allow_jump and idx+2 < len_l and tokens[idx+1] == ' ' and - info.hms(tokens[idx+2]) is not None): - # There is a space and then an "h", "m", or "s" label. - # e.g. the "12" in "12 h" - hms_idx = idx + 2 - - elif idx > 0 and info.hms(tokens[idx-1]) is not None: - # There is a "h", "m", or "s" preceding this token. Since neither - # of the previous cases was hit, there is no label following this - # token, so we use the previous label. - # e.g. the "04" in "12h04" - hms_idx = idx-1 - - elif (1 < idx == len_l-1 and tokens[idx-1] == ' ' and - info.hms(tokens[idx-2]) is not None): - # If we are looking at the final token, we allow for a - # backward-looking check to skip over a space. - # TODO: Are we sure this is the right condition here? - hms_idx = idx - 2 - - else: - hms_idx = None - - return hms_idx - - def _assign_hms(self, res, value_repr, hms): - # See GH issue #427, fixing float rounding - value = self._to_decimal(value_repr) - - if hms == 0: - # Hour - res.hour = int(value) - if value % 1: - res.minute = int(60*(value % 1)) - - elif hms == 1: - (res.minute, res.second) = self._parse_min_sec(value) - - elif hms == 2: - (res.second, res.microsecond) = self._parsems(value_repr) - - def _could_be_tzname(self, hour, tzname, tzoffset, token): - return (hour is not None and - tzname is None and - tzoffset is None and - len(token) <= 5 and - (all(x in string.ascii_uppercase for x in token) - or token in self.info.UTCZONE)) - - def _ampm_valid(self, hour, ampm, fuzzy): - """ - For fuzzy parsing, 'a' or 'am' (both valid English words) - may erroneously trigger the AM/PM flag. Deal with that - here. - """ - val_is_ampm = True - - # If there's already an AM/PM flag, this one isn't one. - if fuzzy and ampm is not None: - val_is_ampm = False - - # If AM/PM is found and hour is not, raise a ValueError - if hour is None: - if fuzzy: - val_is_ampm = False - else: - raise ValueError('No hour specified with AM or PM flag.') - elif not 0 <= hour <= 12: - # If AM/PM is found, it's a 12 hour clock, so raise - # an error for invalid range - if fuzzy: - val_is_ampm = False - else: - raise ValueError('Invalid hour specified for 12-hour clock.') - - return val_is_ampm - - def _adjust_ampm(self, hour, ampm): - if hour < 12 and ampm == 1: - hour += 12 - elif hour == 12 and ampm == 0: - hour = 0 - return hour - - def _parse_min_sec(self, value): - # TODO: Every usage of this function sets res.second to the return - # value. Are there any cases where second will be returned as None and - # we *don't* want to set res.second = None? - minute = int(value) - second = None - - sec_remainder = value % 1 - if sec_remainder: - second = int(60 * sec_remainder) - return (minute, second) - - def _parse_hms(self, idx, tokens, info, hms_idx): - # TODO: Is this going to admit a lot of false-positives for when we - # just happen to have digits and "h", "m" or "s" characters in non-date - # text? I guess hex hashes won't have that problem, but there's plenty - # of random junk out there. - if hms_idx is None: - hms = None - new_idx = idx - elif hms_idx > idx: - hms = info.hms(tokens[hms_idx]) - new_idx = hms_idx - else: - # Looking backwards, increment one. - hms = info.hms(tokens[hms_idx]) + 1 - new_idx = idx - - return (new_idx, hms) - - # ------------------------------------------------------------------ - # Handling for individual tokens. These are kept as methods instead - # of functions for the sake of customizability via subclassing. - - def _parsems(self, value): - """Parse a I[.F] seconds value into (seconds, microseconds).""" - if "." not in value: - return int(value), 0 - else: - i, f = value.split(".") - return int(i), int(f.ljust(6, "0")[:6]) - - def _to_decimal(self, val): - try: - decimal_value = Decimal(val) - # See GH 662, edge case, infinite value should not be converted - # via `_to_decimal` - if not decimal_value.is_finite(): - raise ValueError("Converted decimal value is infinite or NaN") - except Exception as e: - msg = "Could not convert %s to decimal" % val - six.raise_from(ValueError(msg), e) - else: - return decimal_value - - # ------------------------------------------------------------------ - # Post-Parsing construction of datetime output. These are kept as - # methods instead of functions for the sake of customizability via - # subclassing. - - def _build_tzinfo(self, tzinfos, tzname, tzoffset): - if callable(tzinfos): - tzdata = tzinfos(tzname, tzoffset) - else: - tzdata = tzinfos.get(tzname) - # handle case where tzinfo is paased an options that returns None - # eg tzinfos = {'BRST' : None} - if isinstance(tzdata, datetime.tzinfo) or tzdata is None: - tzinfo = tzdata - elif isinstance(tzdata, text_type): - tzinfo = tz.tzstr(tzdata) - elif isinstance(tzdata, integer_types): - tzinfo = tz.tzoffset(tzname, tzdata) - else: - raise TypeError("Offset must be tzinfo subclass, tz string, " - "or int offset.") - return tzinfo - - def _build_tzaware(self, naive, res, tzinfos): - if (callable(tzinfos) or (tzinfos and res.tzname in tzinfos)): - tzinfo = self._build_tzinfo(tzinfos, res.tzname, res.tzoffset) - aware = naive.replace(tzinfo=tzinfo) - aware = self._assign_tzname(aware, res.tzname) - - elif res.tzname and res.tzname in time.tzname: - aware = naive.replace(tzinfo=tz.tzlocal()) - - # Handle ambiguous local datetime - aware = self._assign_tzname(aware, res.tzname) - - # This is mostly relevant for winter GMT zones parsed in the UK - if (aware.tzname() != res.tzname and - res.tzname in self.info.UTCZONE): - aware = aware.replace(tzinfo=tz.UTC) - - elif res.tzoffset == 0: - aware = naive.replace(tzinfo=tz.UTC) - - elif res.tzoffset: - aware = naive.replace(tzinfo=tz.tzoffset(res.tzname, res.tzoffset)) - - elif not res.tzname and not res.tzoffset: - # i.e. no timezone information was found. - aware = naive - - elif res.tzname: - # tz-like string was parsed but we don't know what to do - # with it - warnings.warn("tzname {tzname} identified but not understood. " - "Pass `tzinfos` argument in order to correctly " - "return a timezone-aware datetime. In a future " - "version, this will raise an " - "exception.".format(tzname=res.tzname), - category=UnknownTimezoneWarning) - aware = naive - - return aware - - def _build_naive(self, res, default): - repl = {} - for attr in ("year", "month", "day", "hour", - "minute", "second", "microsecond"): - value = getattr(res, attr) - if value is not None: - repl[attr] = value - - if 'day' not in repl: - # If the default day exceeds the last day of the month, fall back - # to the end of the month. - cyear = default.year if res.year is None else res.year - cmonth = default.month if res.month is None else res.month - cday = default.day if res.day is None else res.day - - if cday > monthrange(cyear, cmonth)[1]: - repl['day'] = monthrange(cyear, cmonth)[1] - - naive = default.replace(**repl) - - if res.weekday is not None and not res.day: - naive = naive + relativedelta.relativedelta(weekday=res.weekday) - - return naive - - def _assign_tzname(self, dt, tzname): - if dt.tzname() != tzname: - new_dt = tz.enfold(dt, fold=1) - if new_dt.tzname() == tzname: - return new_dt - - return dt - - def _recombine_skipped(self, tokens, skipped_idxs): - """ - >>> tokens = ["foo", " ", "bar", " ", "19June2000", "baz"] - >>> skipped_idxs = [0, 1, 2, 5] - >>> _recombine_skipped(tokens, skipped_idxs) - ["foo bar", "baz"] - """ - skipped_tokens = [] - for i, idx in enumerate(sorted(skipped_idxs)): - if i > 0 and idx - 1 == skipped_idxs[i - 1]: - skipped_tokens[-1] = skipped_tokens[-1] + tokens[idx] - else: - skipped_tokens.append(tokens[idx]) - - return skipped_tokens - - -DEFAULTPARSER = parser() - - -def parse(timestr, parserinfo=None, **kwargs): - """ - - Parse a string in one of the supported formats, using the - ``parserinfo`` parameters. - - :param timestr: - A string containing a date/time stamp. - - :param parserinfo: - A :class:`parserinfo` object containing parameters for the parser. - If ``None``, the default arguments to the :class:`parserinfo` - constructor are used. - - The ``**kwargs`` parameter takes the following keyword arguments: - - :param default: - The default datetime object, if this is a datetime object and not - ``None``, elements specified in ``timestr`` replace elements in the - default object. - - :param ignoretz: - If set ``True``, time zones in parsed strings are ignored and a naive - :class:`datetime` object is returned. - - :param tzinfos: - Additional time zone names / aliases which may be present in the - string. This argument maps time zone names (and optionally offsets - from those time zones) to time zones. This parameter can be a - dictionary with timezone aliases mapping time zone names to time - zones or a function taking two parameters (``tzname`` and - ``tzoffset``) and returning a time zone. - - The timezones to which the names are mapped can be an integer - offset from UTC in seconds or a :class:`tzinfo` object. - - .. doctest:: - :options: +NORMALIZE_WHITESPACE - - >>> from dateutil.parser import parse - >>> from dateutil.tz import gettz - >>> tzinfos = {"BRST": -7200, "CST": gettz("America/Chicago")} - >>> parse("2012-01-19 17:21:00 BRST", tzinfos=tzinfos) - datetime.datetime(2012, 1, 19, 17, 21, tzinfo=tzoffset(u'BRST', -7200)) - >>> parse("2012-01-19 17:21:00 CST", tzinfos=tzinfos) - datetime.datetime(2012, 1, 19, 17, 21, - tzinfo=tzfile('/usr/share/zoneinfo/America/Chicago')) - - This parameter is ignored if ``ignoretz`` is set. - - :param dayfirst: - Whether to interpret the first value in an ambiguous 3-integer date - (e.g. 01/05/09) as the day (``True``) or month (``False``). If - ``yearfirst`` is set to ``True``, this distinguishes between YDM and - YMD. If set to ``None``, this value is retrieved from the current - :class:`parserinfo` object (which itself defaults to ``False``). - - :param yearfirst: - Whether to interpret the first value in an ambiguous 3-integer date - (e.g. 01/05/09) as the year. If ``True``, the first number is taken to - be the year, otherwise the last number is taken to be the year. If - this is set to ``None``, the value is retrieved from the current - :class:`parserinfo` object (which itself defaults to ``False``). - - :param fuzzy: - Whether to allow fuzzy parsing, allowing for string like "Today is - January 1, 2047 at 8:21:00AM". - - :param fuzzy_with_tokens: - If ``True``, ``fuzzy`` is automatically set to True, and the parser - will return a tuple where the first element is the parsed - :class:`datetime.datetime` datetimestamp and the second element is - a tuple containing the portions of the string which were ignored: - - .. doctest:: - - >>> from dateutil.parser import parse - >>> parse("Today is January 1, 2047 at 8:21:00AM", fuzzy_with_tokens=True) - (datetime.datetime(2047, 1, 1, 8, 21), (u'Today is ', u' ', u'at ')) - - :return: - Returns a :class:`datetime.datetime` object or, if the - ``fuzzy_with_tokens`` option is ``True``, returns a tuple, the - first element being a :class:`datetime.datetime` object, the second - a tuple containing the fuzzy tokens. - - :raises ParserError: - Raised for invalid or unknown string formats, if the provided - :class:`tzinfo` is not in a valid format, or if an invalid date would - be created. - - :raises OverflowError: - Raised if the parsed date exceeds the largest valid C integer on - your system. - """ - if parserinfo: - return parser(parserinfo).parse(timestr, **kwargs) - else: - return DEFAULTPARSER.parse(timestr, **kwargs) - - -class _tzparser(object): - - class _result(_resultbase): - - __slots__ = ["stdabbr", "stdoffset", "dstabbr", "dstoffset", - "start", "end"] - - class _attr(_resultbase): - __slots__ = ["month", "week", "weekday", - "yday", "jyday", "day", "time"] - - def __repr__(self): - return self._repr("") - - def __init__(self): - _resultbase.__init__(self) - self.start = self._attr() - self.end = self._attr() - - def parse(self, tzstr): - res = self._result() - l = [x for x in re.split(r'([,:.]|[a-zA-Z]+|[0-9]+)',tzstr) if x] - used_idxs = list() - try: - - len_l = len(l) - - i = 0 - while i < len_l: - # BRST+3[BRDT[+2]] - j = i - while j < len_l and not [x for x in l[j] - if x in "0123456789:,-+"]: - j += 1 - if j != i: - if not res.stdabbr: - offattr = "stdoffset" - res.stdabbr = "".join(l[i:j]) - else: - offattr = "dstoffset" - res.dstabbr = "".join(l[i:j]) - - for ii in range(j): - used_idxs.append(ii) - i = j - if (i < len_l and (l[i] in ('+', '-') or l[i][0] in - "0123456789")): - if l[i] in ('+', '-'): - # Yes, that's right. See the TZ variable - # documentation. - signal = (1, -1)[l[i] == '+'] - used_idxs.append(i) - i += 1 - else: - signal = -1 - len_li = len(l[i]) - if len_li == 4: - # -0300 - setattr(res, offattr, (int(l[i][:2]) * 3600 + - int(l[i][2:]) * 60) * signal) - elif i + 1 < len_l and l[i + 1] == ':': - # -03:00 - setattr(res, offattr, - (int(l[i]) * 3600 + - int(l[i + 2]) * 60) * signal) - used_idxs.append(i) - i += 2 - elif len_li <= 2: - # -[0]3 - setattr(res, offattr, - int(l[i][:2]) * 3600 * signal) - else: - return None - used_idxs.append(i) - i += 1 - if res.dstabbr: - break - else: - break - - - if i < len_l: - for j in range(i, len_l): - if l[j] == ';': - l[j] = ',' - - assert l[i] == ',' - - i += 1 - - if i >= len_l: - pass - elif (8 <= l.count(',') <= 9 and - not [y for x in l[i:] if x != ',' - for y in x if y not in "0123456789+-"]): - # GMT0BST,3,0,30,3600,10,0,26,7200[,3600] - for x in (res.start, res.end): - x.month = int(l[i]) - used_idxs.append(i) - i += 2 - if l[i] == '-': - value = int(l[i + 1]) * -1 - used_idxs.append(i) - i += 1 - else: - value = int(l[i]) - used_idxs.append(i) - i += 2 - if value: - x.week = value - x.weekday = (int(l[i]) - 1) % 7 - else: - x.day = int(l[i]) - used_idxs.append(i) - i += 2 - x.time = int(l[i]) - used_idxs.append(i) - i += 2 - if i < len_l: - if l[i] in ('-', '+'): - signal = (-1, 1)[l[i] == "+"] - used_idxs.append(i) - i += 1 - else: - signal = 1 - used_idxs.append(i) - res.dstoffset = (res.stdoffset + int(l[i]) * signal) - - # This was a made-up format that is not in normal use - warn(('Parsed time zone "%s"' % tzstr) + - 'is in a non-standard dateutil-specific format, which ' + - 'is now deprecated; support for parsing this format ' + - 'will be removed in future versions. It is recommended ' + - 'that you switch to a standard format like the GNU ' + - 'TZ variable format.', tz.DeprecatedTzFormatWarning) - elif (l.count(',') == 2 and l[i:].count('/') <= 2 and - not [y for x in l[i:] if x not in (',', '/', 'J', 'M', - '.', '-', ':') - for y in x if y not in "0123456789"]): - for x in (res.start, res.end): - if l[i] == 'J': - # non-leap year day (1 based) - used_idxs.append(i) - i += 1 - x.jyday = int(l[i]) - elif l[i] == 'M': - # month[-.]week[-.]weekday - used_idxs.append(i) - i += 1 - x.month = int(l[i]) - used_idxs.append(i) - i += 1 - assert l[i] in ('-', '.') - used_idxs.append(i) - i += 1 - x.week = int(l[i]) - if x.week == 5: - x.week = -1 - used_idxs.append(i) - i += 1 - assert l[i] in ('-', '.') - used_idxs.append(i) - i += 1 - x.weekday = (int(l[i]) - 1) % 7 - else: - # year day (zero based) - x.yday = int(l[i]) + 1 - - used_idxs.append(i) - i += 1 - - if i < len_l and l[i] == '/': - used_idxs.append(i) - i += 1 - # start time - len_li = len(l[i]) - if len_li == 4: - # -0300 - x.time = (int(l[i][:2]) * 3600 + - int(l[i][2:]) * 60) - elif i + 1 < len_l and l[i + 1] == ':': - # -03:00 - x.time = int(l[i]) * 3600 + int(l[i + 2]) * 60 - used_idxs.append(i) - i += 2 - if i + 1 < len_l and l[i + 1] == ':': - used_idxs.append(i) - i += 2 - x.time += int(l[i]) - elif len_li <= 2: - # -[0]3 - x.time = (int(l[i][:2]) * 3600) - else: - return None - used_idxs.append(i) - i += 1 - - assert i == len_l or l[i] == ',' - - i += 1 - - assert i >= len_l - - except (IndexError, ValueError, AssertionError): - return None - - unused_idxs = set(range(len_l)).difference(used_idxs) - res.any_unused_tokens = not {l[n] for n in unused_idxs}.issubset({",",":"}) - return res - - -DEFAULTTZPARSER = _tzparser() - - -def _parsetz(tzstr): - return DEFAULTTZPARSER.parse(tzstr) - - -class ParserError(ValueError): - """Exception subclass used for any failure to parse a datetime string. - - This is a subclass of :py:exc:`ValueError`, and should be raised any time - earlier versions of ``dateutil`` would have raised ``ValueError``. - - .. versionadded:: 2.8.1 - """ - def __str__(self): - try: - return self.args[0] % self.args[1:] - except (TypeError, IndexError): - return super(ParserError, self).__str__() - - def __repr__(self): - args = ", ".join("'%s'" % arg for arg in self.args) - return "%s(%s)" % (self.__class__.__name__, args) - - -class UnknownTimezoneWarning(RuntimeWarning): - """Raised when the parser finds a timezone it cannot parse into a tzinfo. - - .. versionadded:: 2.7.0 - """ -# vim:ts=4:sw=4:et diff --git a/.venv/Lib/site-packages/dateutil/parser/isoparser.py b/.venv/Lib/site-packages/dateutil/parser/isoparser.py deleted file mode 100644 index 5d7bee3..0000000 --- a/.venv/Lib/site-packages/dateutil/parser/isoparser.py +++ /dev/null @@ -1,416 +0,0 @@ -# -*- coding: utf-8 -*- -""" -This module offers a parser for ISO-8601 strings - -It is intended to support all valid date, time and datetime formats per the -ISO-8601 specification. - -..versionadded:: 2.7.0 -""" -from datetime import datetime, timedelta, time, date -import calendar -from dateutil import tz - -from functools import wraps - -import re -import six - -__all__ = ["isoparse", "isoparser"] - - -def _takes_ascii(f): - @wraps(f) - def func(self, str_in, *args, **kwargs): - # If it's a stream, read the whole thing - str_in = getattr(str_in, 'read', lambda: str_in)() - - # If it's unicode, turn it into bytes, since ISO-8601 only covers ASCII - if isinstance(str_in, six.text_type): - # ASCII is the same in UTF-8 - try: - str_in = str_in.encode('ascii') - except UnicodeEncodeError as e: - msg = 'ISO-8601 strings should contain only ASCII characters' - six.raise_from(ValueError(msg), e) - - return f(self, str_in, *args, **kwargs) - - return func - - -class isoparser(object): - def __init__(self, sep=None): - """ - :param sep: - A single character that separates date and time portions. If - ``None``, the parser will accept any single character. - For strict ISO-8601 adherence, pass ``'T'``. - """ - if sep is not None: - if (len(sep) != 1 or ord(sep) >= 128 or sep in '0123456789'): - raise ValueError('Separator must be a single, non-numeric ' + - 'ASCII character') - - sep = sep.encode('ascii') - - self._sep = sep - - @_takes_ascii - def isoparse(self, dt_str): - """ - Parse an ISO-8601 datetime string into a :class:`datetime.datetime`. - - An ISO-8601 datetime string consists of a date portion, followed - optionally by a time portion - the date and time portions are separated - by a single character separator, which is ``T`` in the official - standard. Incomplete date formats (such as ``YYYY-MM``) may *not* be - combined with a time portion. - - Supported date formats are: - - Common: - - - ``YYYY`` - - ``YYYY-MM`` or ``YYYYMM`` - - ``YYYY-MM-DD`` or ``YYYYMMDD`` - - Uncommon: - - - ``YYYY-Www`` or ``YYYYWww`` - ISO week (day defaults to 0) - - ``YYYY-Www-D`` or ``YYYYWwwD`` - ISO week and day - - The ISO week and day numbering follows the same logic as - :func:`datetime.date.isocalendar`. - - Supported time formats are: - - - ``hh`` - - ``hh:mm`` or ``hhmm`` - - ``hh:mm:ss`` or ``hhmmss`` - - ``hh:mm:ss.ssssss`` (Up to 6 sub-second digits) - - Midnight is a special case for `hh`, as the standard supports both - 00:00 and 24:00 as a representation. The decimal separator can be - either a dot or a comma. - - - .. caution:: - - Support for fractional components other than seconds is part of the - ISO-8601 standard, but is not currently implemented in this parser. - - Supported time zone offset formats are: - - - `Z` (UTC) - - `±HH:MM` - - `±HHMM` - - `±HH` - - Offsets will be represented as :class:`dateutil.tz.tzoffset` objects, - with the exception of UTC, which will be represented as - :class:`dateutil.tz.tzutc`. Time zone offsets equivalent to UTC (such - as `+00:00`) will also be represented as :class:`dateutil.tz.tzutc`. - - :param dt_str: - A string or stream containing only an ISO-8601 datetime string - - :return: - Returns a :class:`datetime.datetime` representing the string. - Unspecified components default to their lowest value. - - .. warning:: - - As of version 2.7.0, the strictness of the parser should not be - considered a stable part of the contract. Any valid ISO-8601 string - that parses correctly with the default settings will continue to - parse correctly in future versions, but invalid strings that - currently fail (e.g. ``2017-01-01T00:00+00:00:00``) are not - guaranteed to continue failing in future versions if they encode - a valid date. - - .. versionadded:: 2.7.0 - """ - components, pos = self._parse_isodate(dt_str) - - if len(dt_str) > pos: - if self._sep is None or dt_str[pos:pos + 1] == self._sep: - components += self._parse_isotime(dt_str[pos + 1:]) - else: - raise ValueError('String contains unknown ISO components') - - if len(components) > 3 and components[3] == 24: - components[3] = 0 - return datetime(*components) + timedelta(days=1) - - return datetime(*components) - - @_takes_ascii - def parse_isodate(self, datestr): - """ - Parse the date portion of an ISO string. - - :param datestr: - The string portion of an ISO string, without a separator - - :return: - Returns a :class:`datetime.date` object - """ - components, pos = self._parse_isodate(datestr) - if pos < len(datestr): - raise ValueError('String contains unknown ISO ' + - 'components: {!r}'.format(datestr.decode('ascii'))) - return date(*components) - - @_takes_ascii - def parse_isotime(self, timestr): - """ - Parse the time portion of an ISO string. - - :param timestr: - The time portion of an ISO string, without a separator - - :return: - Returns a :class:`datetime.time` object - """ - components = self._parse_isotime(timestr) - if components[0] == 24: - components[0] = 0 - return time(*components) - - @_takes_ascii - def parse_tzstr(self, tzstr, zero_as_utc=True): - """ - Parse a valid ISO time zone string. - - See :func:`isoparser.isoparse` for details on supported formats. - - :param tzstr: - A string representing an ISO time zone offset - - :param zero_as_utc: - Whether to return :class:`dateutil.tz.tzutc` for zero-offset zones - - :return: - Returns :class:`dateutil.tz.tzoffset` for offsets and - :class:`dateutil.tz.tzutc` for ``Z`` and (if ``zero_as_utc`` is - specified) offsets equivalent to UTC. - """ - return self._parse_tzstr(tzstr, zero_as_utc=zero_as_utc) - - # Constants - _DATE_SEP = b'-' - _TIME_SEP = b':' - _FRACTION_REGEX = re.compile(b'[\\.,]([0-9]+)') - - def _parse_isodate(self, dt_str): - try: - return self._parse_isodate_common(dt_str) - except ValueError: - return self._parse_isodate_uncommon(dt_str) - - def _parse_isodate_common(self, dt_str): - len_str = len(dt_str) - components = [1, 1, 1] - - if len_str < 4: - raise ValueError('ISO string too short') - - # Year - components[0] = int(dt_str[0:4]) - pos = 4 - if pos >= len_str: - return components, pos - - has_sep = dt_str[pos:pos + 1] == self._DATE_SEP - if has_sep: - pos += 1 - - # Month - if len_str - pos < 2: - raise ValueError('Invalid common month') - - components[1] = int(dt_str[pos:pos + 2]) - pos += 2 - - if pos >= len_str: - if has_sep: - return components, pos - else: - raise ValueError('Invalid ISO format') - - if has_sep: - if dt_str[pos:pos + 1] != self._DATE_SEP: - raise ValueError('Invalid separator in ISO string') - pos += 1 - - # Day - if len_str - pos < 2: - raise ValueError('Invalid common day') - components[2] = int(dt_str[pos:pos + 2]) - return components, pos + 2 - - def _parse_isodate_uncommon(self, dt_str): - if len(dt_str) < 4: - raise ValueError('ISO string too short') - - # All ISO formats start with the year - year = int(dt_str[0:4]) - - has_sep = dt_str[4:5] == self._DATE_SEP - - pos = 4 + has_sep # Skip '-' if it's there - if dt_str[pos:pos + 1] == b'W': - # YYYY-?Www-?D? - pos += 1 - weekno = int(dt_str[pos:pos + 2]) - pos += 2 - - dayno = 1 - if len(dt_str) > pos: - if (dt_str[pos:pos + 1] == self._DATE_SEP) != has_sep: - raise ValueError('Inconsistent use of dash separator') - - pos += has_sep - - dayno = int(dt_str[pos:pos + 1]) - pos += 1 - - base_date = self._calculate_weekdate(year, weekno, dayno) - else: - # YYYYDDD or YYYY-DDD - if len(dt_str) - pos < 3: - raise ValueError('Invalid ordinal day') - - ordinal_day = int(dt_str[pos:pos + 3]) - pos += 3 - - if ordinal_day < 1 or ordinal_day > (365 + calendar.isleap(year)): - raise ValueError('Invalid ordinal day' + - ' {} for year {}'.format(ordinal_day, year)) - - base_date = date(year, 1, 1) + timedelta(days=ordinal_day - 1) - - components = [base_date.year, base_date.month, base_date.day] - return components, pos - - def _calculate_weekdate(self, year, week, day): - """ - Calculate the day of corresponding to the ISO year-week-day calendar. - - This function is effectively the inverse of - :func:`datetime.date.isocalendar`. - - :param year: - The year in the ISO calendar - - :param week: - The week in the ISO calendar - range is [1, 53] - - :param day: - The day in the ISO calendar - range is [1 (MON), 7 (SUN)] - - :return: - Returns a :class:`datetime.date` - """ - if not 0 < week < 54: - raise ValueError('Invalid week: {}'.format(week)) - - if not 0 < day < 8: # Range is 1-7 - raise ValueError('Invalid weekday: {}'.format(day)) - - # Get week 1 for the specific year: - jan_4 = date(year, 1, 4) # Week 1 always has January 4th in it - week_1 = jan_4 - timedelta(days=jan_4.isocalendar()[2] - 1) - - # Now add the specific number of weeks and days to get what we want - week_offset = (week - 1) * 7 + (day - 1) - return week_1 + timedelta(days=week_offset) - - def _parse_isotime(self, timestr): - len_str = len(timestr) - components = [0, 0, 0, 0, None] - pos = 0 - comp = -1 - - if len_str < 2: - raise ValueError('ISO time too short') - - has_sep = False - - while pos < len_str and comp < 5: - comp += 1 - - if timestr[pos:pos + 1] in b'-+Zz': - # Detect time zone boundary - components[-1] = self._parse_tzstr(timestr[pos:]) - pos = len_str - break - - if comp == 1 and timestr[pos:pos+1] == self._TIME_SEP: - has_sep = True - pos += 1 - elif comp == 2 and has_sep: - if timestr[pos:pos+1] != self._TIME_SEP: - raise ValueError('Inconsistent use of colon separator') - pos += 1 - - if comp < 3: - # Hour, minute, second - components[comp] = int(timestr[pos:pos + 2]) - pos += 2 - - if comp == 3: - # Fraction of a second - frac = self._FRACTION_REGEX.match(timestr[pos:]) - if not frac: - continue - - us_str = frac.group(1)[:6] # Truncate to microseconds - components[comp] = int(us_str) * 10**(6 - len(us_str)) - pos += len(frac.group()) - - if pos < len_str: - raise ValueError('Unused components in ISO string') - - if components[0] == 24: - # Standard supports 00:00 and 24:00 as representations of midnight - if any(component != 0 for component in components[1:4]): - raise ValueError('Hour may only be 24 at 24:00:00.000') - - return components - - def _parse_tzstr(self, tzstr, zero_as_utc=True): - if tzstr == b'Z' or tzstr == b'z': - return tz.UTC - - if len(tzstr) not in {3, 5, 6}: - raise ValueError('Time zone offset must be 1, 3, 5 or 6 characters') - - if tzstr[0:1] == b'-': - mult = -1 - elif tzstr[0:1] == b'+': - mult = 1 - else: - raise ValueError('Time zone offset requires sign') - - hours = int(tzstr[1:3]) - if len(tzstr) == 3: - minutes = 0 - else: - minutes = int(tzstr[(4 if tzstr[3:4] == self._TIME_SEP else 3):]) - - if zero_as_utc and hours == 0 and minutes == 0: - return tz.UTC - else: - if minutes > 59: - raise ValueError('Invalid minutes in time zone offset') - - if hours > 23: - raise ValueError('Invalid hours in time zone offset') - - return tz.tzoffset(None, mult * (hours * 60 + minutes) * 60) - - -DEFAULT_ISOPARSER = isoparser() -isoparse = DEFAULT_ISOPARSER.isoparse diff --git a/.venv/Lib/site-packages/dateutil/relativedelta.py b/.venv/Lib/site-packages/dateutil/relativedelta.py deleted file mode 100644 index a9e85f7..0000000 --- a/.venv/Lib/site-packages/dateutil/relativedelta.py +++ /dev/null @@ -1,599 +0,0 @@ -# -*- coding: utf-8 -*- -import datetime -import calendar - -import operator -from math import copysign - -from six import integer_types -from warnings import warn - -from ._common import weekday - -MO, TU, WE, TH, FR, SA, SU = weekdays = tuple(weekday(x) for x in range(7)) - -__all__ = ["relativedelta", "MO", "TU", "WE", "TH", "FR", "SA", "SU"] - - -class relativedelta(object): - """ - The relativedelta type is designed to be applied to an existing datetime and - can replace specific components of that datetime, or represents an interval - of time. - - It is based on the specification of the excellent work done by M.-A. Lemburg - in his - `mx.DateTime `_ extension. - However, notice that this type does *NOT* implement the same algorithm as - his work. Do *NOT* expect it to behave like mx.DateTime's counterpart. - - There are two different ways to build a relativedelta instance. The - first one is passing it two date/datetime classes:: - - relativedelta(datetime1, datetime2) - - The second one is passing it any number of the following keyword arguments:: - - relativedelta(arg1=x,arg2=y,arg3=z...) - - year, month, day, hour, minute, second, microsecond: - Absolute information (argument is singular); adding or subtracting a - relativedelta with absolute information does not perform an arithmetic - operation, but rather REPLACES the corresponding value in the - original datetime with the value(s) in relativedelta. - - years, months, weeks, days, hours, minutes, seconds, microseconds: - Relative information, may be negative (argument is plural); adding - or subtracting a relativedelta with relative information performs - the corresponding arithmetic operation on the original datetime value - with the information in the relativedelta. - - weekday: - One of the weekday instances (MO, TU, etc) available in the - relativedelta module. These instances may receive a parameter N, - specifying the Nth weekday, which could be positive or negative - (like MO(+1) or MO(-2)). Not specifying it is the same as specifying - +1. You can also use an integer, where 0=MO. This argument is always - relative e.g. if the calculated date is already Monday, using MO(1) - or MO(-1) won't change the day. To effectively make it absolute, use - it in combination with the day argument (e.g. day=1, MO(1) for first - Monday of the month). - - leapdays: - Will add given days to the date found, if year is a leap - year, and the date found is post 28 of february. - - yearday, nlyearday: - Set the yearday or the non-leap year day (jump leap days). - These are converted to day/month/leapdays information. - - There are relative and absolute forms of the keyword - arguments. The plural is relative, and the singular is - absolute. For each argument in the order below, the absolute form - is applied first (by setting each attribute to that value) and - then the relative form (by adding the value to the attribute). - - The order of attributes considered when this relativedelta is - added to a datetime is: - - 1. Year - 2. Month - 3. Day - 4. Hours - 5. Minutes - 6. Seconds - 7. Microseconds - - Finally, weekday is applied, using the rule described above. - - For example - - >>> from datetime import datetime - >>> from dateutil.relativedelta import relativedelta, MO - >>> dt = datetime(2018, 4, 9, 13, 37, 0) - >>> delta = relativedelta(hours=25, day=1, weekday=MO(1)) - >>> dt + delta - datetime.datetime(2018, 4, 2, 14, 37) - - First, the day is set to 1 (the first of the month), then 25 hours - are added, to get to the 2nd day and 14th hour, finally the - weekday is applied, but since the 2nd is already a Monday there is - no effect. - - """ - - def __init__(self, dt1=None, dt2=None, - years=0, months=0, days=0, leapdays=0, weeks=0, - hours=0, minutes=0, seconds=0, microseconds=0, - year=None, month=None, day=None, weekday=None, - yearday=None, nlyearday=None, - hour=None, minute=None, second=None, microsecond=None): - - if dt1 and dt2: - # datetime is a subclass of date. So both must be date - if not (isinstance(dt1, datetime.date) and - isinstance(dt2, datetime.date)): - raise TypeError("relativedelta only diffs datetime/date") - - # We allow two dates, or two datetimes, so we coerce them to be - # of the same type - if (isinstance(dt1, datetime.datetime) != - isinstance(dt2, datetime.datetime)): - if not isinstance(dt1, datetime.datetime): - dt1 = datetime.datetime.fromordinal(dt1.toordinal()) - elif not isinstance(dt2, datetime.datetime): - dt2 = datetime.datetime.fromordinal(dt2.toordinal()) - - self.years = 0 - self.months = 0 - self.days = 0 - self.leapdays = 0 - self.hours = 0 - self.minutes = 0 - self.seconds = 0 - self.microseconds = 0 - self.year = None - self.month = None - self.day = None - self.weekday = None - self.hour = None - self.minute = None - self.second = None - self.microsecond = None - self._has_time = 0 - - # Get year / month delta between the two - months = (dt1.year - dt2.year) * 12 + (dt1.month - dt2.month) - self._set_months(months) - - # Remove the year/month delta so the timedelta is just well-defined - # time units (seconds, days and microseconds) - dtm = self.__radd__(dt2) - - # If we've overshot our target, make an adjustment - if dt1 < dt2: - compare = operator.gt - increment = 1 - else: - compare = operator.lt - increment = -1 - - while compare(dt1, dtm): - months += increment - self._set_months(months) - dtm = self.__radd__(dt2) - - # Get the timedelta between the "months-adjusted" date and dt1 - delta = dt1 - dtm - self.seconds = delta.seconds + delta.days * 86400 - self.microseconds = delta.microseconds - else: - # Check for non-integer values in integer-only quantities - if any(x is not None and x != int(x) for x in (years, months)): - raise ValueError("Non-integer years and months are " - "ambiguous and not currently supported.") - - # Relative information - self.years = int(years) - self.months = int(months) - self.days = days + weeks * 7 - self.leapdays = leapdays - self.hours = hours - self.minutes = minutes - self.seconds = seconds - self.microseconds = microseconds - - # Absolute information - self.year = year - self.month = month - self.day = day - self.hour = hour - self.minute = minute - self.second = second - self.microsecond = microsecond - - if any(x is not None and int(x) != x - for x in (year, month, day, hour, - minute, second, microsecond)): - # For now we'll deprecate floats - later it'll be an error. - warn("Non-integer value passed as absolute information. " + - "This is not a well-defined condition and will raise " + - "errors in future versions.", DeprecationWarning) - - if isinstance(weekday, integer_types): - self.weekday = weekdays[weekday] - else: - self.weekday = weekday - - yday = 0 - if nlyearday: - yday = nlyearday - elif yearday: - yday = yearday - if yearday > 59: - self.leapdays = -1 - if yday: - ydayidx = [31, 59, 90, 120, 151, 181, 212, - 243, 273, 304, 334, 366] - for idx, ydays in enumerate(ydayidx): - if yday <= ydays: - self.month = idx+1 - if idx == 0: - self.day = yday - else: - self.day = yday-ydayidx[idx-1] - break - else: - raise ValueError("invalid year day (%d)" % yday) - - self._fix() - - def _fix(self): - if abs(self.microseconds) > 999999: - s = _sign(self.microseconds) - div, mod = divmod(self.microseconds * s, 1000000) - self.microseconds = mod * s - self.seconds += div * s - if abs(self.seconds) > 59: - s = _sign(self.seconds) - div, mod = divmod(self.seconds * s, 60) - self.seconds = mod * s - self.minutes += div * s - if abs(self.minutes) > 59: - s = _sign(self.minutes) - div, mod = divmod(self.minutes * s, 60) - self.minutes = mod * s - self.hours += div * s - if abs(self.hours) > 23: - s = _sign(self.hours) - div, mod = divmod(self.hours * s, 24) - self.hours = mod * s - self.days += div * s - if abs(self.months) > 11: - s = _sign(self.months) - div, mod = divmod(self.months * s, 12) - self.months = mod * s - self.years += div * s - if (self.hours or self.minutes or self.seconds or self.microseconds - or self.hour is not None or self.minute is not None or - self.second is not None or self.microsecond is not None): - self._has_time = 1 - else: - self._has_time = 0 - - @property - def weeks(self): - return int(self.days / 7.0) - - @weeks.setter - def weeks(self, value): - self.days = self.days - (self.weeks * 7) + value * 7 - - def _set_months(self, months): - self.months = months - if abs(self.months) > 11: - s = _sign(self.months) - div, mod = divmod(self.months * s, 12) - self.months = mod * s - self.years = div * s - else: - self.years = 0 - - def normalized(self): - """ - Return a version of this object represented entirely using integer - values for the relative attributes. - - >>> relativedelta(days=1.5, hours=2).normalized() - relativedelta(days=+1, hours=+14) - - :return: - Returns a :class:`dateutil.relativedelta.relativedelta` object. - """ - # Cascade remainders down (rounding each to roughly nearest microsecond) - days = int(self.days) - - hours_f = round(self.hours + 24 * (self.days - days), 11) - hours = int(hours_f) - - minutes_f = round(self.minutes + 60 * (hours_f - hours), 10) - minutes = int(minutes_f) - - seconds_f = round(self.seconds + 60 * (minutes_f - minutes), 8) - seconds = int(seconds_f) - - microseconds = round(self.microseconds + 1e6 * (seconds_f - seconds)) - - # Constructor carries overflow back up with call to _fix() - return self.__class__(years=self.years, months=self.months, - days=days, hours=hours, minutes=minutes, - seconds=seconds, microseconds=microseconds, - leapdays=self.leapdays, year=self.year, - month=self.month, day=self.day, - weekday=self.weekday, hour=self.hour, - minute=self.minute, second=self.second, - microsecond=self.microsecond) - - def __add__(self, other): - if isinstance(other, relativedelta): - return self.__class__(years=other.years + self.years, - months=other.months + self.months, - days=other.days + self.days, - hours=other.hours + self.hours, - minutes=other.minutes + self.minutes, - seconds=other.seconds + self.seconds, - microseconds=(other.microseconds + - self.microseconds), - leapdays=other.leapdays or self.leapdays, - year=(other.year if other.year is not None - else self.year), - month=(other.month if other.month is not None - else self.month), - day=(other.day if other.day is not None - else self.day), - weekday=(other.weekday if other.weekday is not None - else self.weekday), - hour=(other.hour if other.hour is not None - else self.hour), - minute=(other.minute if other.minute is not None - else self.minute), - second=(other.second if other.second is not None - else self.second), - microsecond=(other.microsecond if other.microsecond - is not None else - self.microsecond)) - if isinstance(other, datetime.timedelta): - return self.__class__(years=self.years, - months=self.months, - days=self.days + other.days, - hours=self.hours, - minutes=self.minutes, - seconds=self.seconds + other.seconds, - microseconds=self.microseconds + other.microseconds, - leapdays=self.leapdays, - year=self.year, - month=self.month, - day=self.day, - weekday=self.weekday, - hour=self.hour, - minute=self.minute, - second=self.second, - microsecond=self.microsecond) - if not isinstance(other, datetime.date): - return NotImplemented - elif self._has_time and not isinstance(other, datetime.datetime): - other = datetime.datetime.fromordinal(other.toordinal()) - year = (self.year or other.year)+self.years - month = self.month or other.month - if self.months: - assert 1 <= abs(self.months) <= 12 - month += self.months - if month > 12: - year += 1 - month -= 12 - elif month < 1: - year -= 1 - month += 12 - day = min(calendar.monthrange(year, month)[1], - self.day or other.day) - repl = {"year": year, "month": month, "day": day} - for attr in ["hour", "minute", "second", "microsecond"]: - value = getattr(self, attr) - if value is not None: - repl[attr] = value - days = self.days - if self.leapdays and month > 2 and calendar.isleap(year): - days += self.leapdays - ret = (other.replace(**repl) - + datetime.timedelta(days=days, - hours=self.hours, - minutes=self.minutes, - seconds=self.seconds, - microseconds=self.microseconds)) - if self.weekday: - weekday, nth = self.weekday.weekday, self.weekday.n or 1 - jumpdays = (abs(nth) - 1) * 7 - if nth > 0: - jumpdays += (7 - ret.weekday() + weekday) % 7 - else: - jumpdays += (ret.weekday() - weekday) % 7 - jumpdays *= -1 - ret += datetime.timedelta(days=jumpdays) - return ret - - def __radd__(self, other): - return self.__add__(other) - - def __rsub__(self, other): - return self.__neg__().__radd__(other) - - def __sub__(self, other): - if not isinstance(other, relativedelta): - return NotImplemented # In case the other object defines __rsub__ - return self.__class__(years=self.years - other.years, - months=self.months - other.months, - days=self.days - other.days, - hours=self.hours - other.hours, - minutes=self.minutes - other.minutes, - seconds=self.seconds - other.seconds, - microseconds=self.microseconds - other.microseconds, - leapdays=self.leapdays or other.leapdays, - year=(self.year if self.year is not None - else other.year), - month=(self.month if self.month is not None else - other.month), - day=(self.day if self.day is not None else - other.day), - weekday=(self.weekday if self.weekday is not None else - other.weekday), - hour=(self.hour if self.hour is not None else - other.hour), - minute=(self.minute if self.minute is not None else - other.minute), - second=(self.second if self.second is not None else - other.second), - microsecond=(self.microsecond if self.microsecond - is not None else - other.microsecond)) - - def __abs__(self): - return self.__class__(years=abs(self.years), - months=abs(self.months), - days=abs(self.days), - hours=abs(self.hours), - minutes=abs(self.minutes), - seconds=abs(self.seconds), - microseconds=abs(self.microseconds), - leapdays=self.leapdays, - year=self.year, - month=self.month, - day=self.day, - weekday=self.weekday, - hour=self.hour, - minute=self.minute, - second=self.second, - microsecond=self.microsecond) - - def __neg__(self): - return self.__class__(years=-self.years, - months=-self.months, - days=-self.days, - hours=-self.hours, - minutes=-self.minutes, - seconds=-self.seconds, - microseconds=-self.microseconds, - leapdays=self.leapdays, - year=self.year, - month=self.month, - day=self.day, - weekday=self.weekday, - hour=self.hour, - minute=self.minute, - second=self.second, - microsecond=self.microsecond) - - def __bool__(self): - return not (not self.years and - not self.months and - not self.days and - not self.hours and - not self.minutes and - not self.seconds and - not self.microseconds and - not self.leapdays and - self.year is None and - self.month is None and - self.day is None and - self.weekday is None and - self.hour is None and - self.minute is None and - self.second is None and - self.microsecond is None) - # Compatibility with Python 2.x - __nonzero__ = __bool__ - - def __mul__(self, other): - try: - f = float(other) - except TypeError: - return NotImplemented - - return self.__class__(years=int(self.years * f), - months=int(self.months * f), - days=int(self.days * f), - hours=int(self.hours * f), - minutes=int(self.minutes * f), - seconds=int(self.seconds * f), - microseconds=int(self.microseconds * f), - leapdays=self.leapdays, - year=self.year, - month=self.month, - day=self.day, - weekday=self.weekday, - hour=self.hour, - minute=self.minute, - second=self.second, - microsecond=self.microsecond) - - __rmul__ = __mul__ - - def __eq__(self, other): - if not isinstance(other, relativedelta): - return NotImplemented - if self.weekday or other.weekday: - if not self.weekday or not other.weekday: - return False - if self.weekday.weekday != other.weekday.weekday: - return False - n1, n2 = self.weekday.n, other.weekday.n - if n1 != n2 and not ((not n1 or n1 == 1) and (not n2 or n2 == 1)): - return False - return (self.years == other.years and - self.months == other.months and - self.days == other.days and - self.hours == other.hours and - self.minutes == other.minutes and - self.seconds == other.seconds and - self.microseconds == other.microseconds and - self.leapdays == other.leapdays and - self.year == other.year and - self.month == other.month and - self.day == other.day and - self.hour == other.hour and - self.minute == other.minute and - self.second == other.second and - self.microsecond == other.microsecond) - - def __hash__(self): - return hash(( - self.weekday, - self.years, - self.months, - self.days, - self.hours, - self.minutes, - self.seconds, - self.microseconds, - self.leapdays, - self.year, - self.month, - self.day, - self.hour, - self.minute, - self.second, - self.microsecond, - )) - - def __ne__(self, other): - return not self.__eq__(other) - - def __div__(self, other): - try: - reciprocal = 1 / float(other) - except TypeError: - return NotImplemented - - return self.__mul__(reciprocal) - - __truediv__ = __div__ - - def __repr__(self): - l = [] - for attr in ["years", "months", "days", "leapdays", - "hours", "minutes", "seconds", "microseconds"]: - value = getattr(self, attr) - if value: - l.append("{attr}={value:+g}".format(attr=attr, value=value)) - for attr in ["year", "month", "day", "weekday", - "hour", "minute", "second", "microsecond"]: - value = getattr(self, attr) - if value is not None: - l.append("{attr}={value}".format(attr=attr, value=repr(value))) - return "{classname}({attrs})".format(classname=self.__class__.__name__, - attrs=", ".join(l)) - - -def _sign(x): - return int(copysign(1, x)) - -# vim:ts=4:sw=4:et diff --git a/.venv/Lib/site-packages/dateutil/rrule.py b/.venv/Lib/site-packages/dateutil/rrule.py deleted file mode 100644 index b320339..0000000 --- a/.venv/Lib/site-packages/dateutil/rrule.py +++ /dev/null @@ -1,1737 +0,0 @@ -# -*- coding: utf-8 -*- -""" -The rrule module offers a small, complete, and very fast, implementation of -the recurrence rules documented in the -`iCalendar RFC `_, -including support for caching of results. -""" -import calendar -import datetime -import heapq -import itertools -import re -import sys -from functools import wraps -# For warning about deprecation of until and count -from warnings import warn - -from six import advance_iterator, integer_types - -from six.moves import _thread, range - -from ._common import weekday as weekdaybase - -try: - from math import gcd -except ImportError: - from fractions import gcd - -__all__ = ["rrule", "rruleset", "rrulestr", - "YEARLY", "MONTHLY", "WEEKLY", "DAILY", - "HOURLY", "MINUTELY", "SECONDLY", - "MO", "TU", "WE", "TH", "FR", "SA", "SU"] - -# Every mask is 7 days longer to handle cross-year weekly periods. -M366MASK = tuple([1]*31+[2]*29+[3]*31+[4]*30+[5]*31+[6]*30 + - [7]*31+[8]*31+[9]*30+[10]*31+[11]*30+[12]*31+[1]*7) -M365MASK = list(M366MASK) -M29, M30, M31 = list(range(1, 30)), list(range(1, 31)), list(range(1, 32)) -MDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7]) -MDAY365MASK = list(MDAY366MASK) -M29, M30, M31 = list(range(-29, 0)), list(range(-30, 0)), list(range(-31, 0)) -NMDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7]) -NMDAY365MASK = list(NMDAY366MASK) -M366RANGE = (0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366) -M365RANGE = (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365) -WDAYMASK = [0, 1, 2, 3, 4, 5, 6]*55 -del M29, M30, M31, M365MASK[59], MDAY365MASK[59], NMDAY365MASK[31] -MDAY365MASK = tuple(MDAY365MASK) -M365MASK = tuple(M365MASK) - -FREQNAMES = ['YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY', 'HOURLY', 'MINUTELY', 'SECONDLY'] - -(YEARLY, - MONTHLY, - WEEKLY, - DAILY, - HOURLY, - MINUTELY, - SECONDLY) = list(range(7)) - -# Imported on demand. -easter = None -parser = None - - -class weekday(weekdaybase): - """ - This version of weekday does not allow n = 0. - """ - def __init__(self, wkday, n=None): - if n == 0: - raise ValueError("Can't create weekday with n==0") - - super(weekday, self).__init__(wkday, n) - - -MO, TU, WE, TH, FR, SA, SU = weekdays = tuple(weekday(x) for x in range(7)) - - -def _invalidates_cache(f): - """ - Decorator for rruleset methods which may invalidate the - cached length. - """ - @wraps(f) - def inner_func(self, *args, **kwargs): - rv = f(self, *args, **kwargs) - self._invalidate_cache() - return rv - - return inner_func - - -class rrulebase(object): - def __init__(self, cache=False): - if cache: - self._cache = [] - self._cache_lock = _thread.allocate_lock() - self._invalidate_cache() - else: - self._cache = None - self._cache_complete = False - self._len = None - - def __iter__(self): - if self._cache_complete: - return iter(self._cache) - elif self._cache is None: - return self._iter() - else: - return self._iter_cached() - - def _invalidate_cache(self): - if self._cache is not None: - self._cache = [] - self._cache_complete = False - self._cache_gen = self._iter() - - if self._cache_lock.locked(): - self._cache_lock.release() - - self._len = None - - def _iter_cached(self): - i = 0 - gen = self._cache_gen - cache = self._cache - acquire = self._cache_lock.acquire - release = self._cache_lock.release - while gen: - if i == len(cache): - acquire() - if self._cache_complete: - break - try: - for j in range(10): - cache.append(advance_iterator(gen)) - except StopIteration: - self._cache_gen = gen = None - self._cache_complete = True - break - release() - yield cache[i] - i += 1 - while i < self._len: - yield cache[i] - i += 1 - - def __getitem__(self, item): - if self._cache_complete: - return self._cache[item] - elif isinstance(item, slice): - if item.step and item.step < 0: - return list(iter(self))[item] - else: - return list(itertools.islice(self, - item.start or 0, - item.stop or sys.maxsize, - item.step or 1)) - elif item >= 0: - gen = iter(self) - try: - for i in range(item+1): - res = advance_iterator(gen) - except StopIteration: - raise IndexError - return res - else: - return list(iter(self))[item] - - def __contains__(self, item): - if self._cache_complete: - return item in self._cache - else: - for i in self: - if i == item: - return True - elif i > item: - return False - return False - - # __len__() introduces a large performance penalty. - def count(self): - """ Returns the number of recurrences in this set. It will have go - trough the whole recurrence, if this hasn't been done before. """ - if self._len is None: - for x in self: - pass - return self._len - - def before(self, dt, inc=False): - """ Returns the last recurrence before the given datetime instance. The - inc keyword defines what happens if dt is an occurrence. With - inc=True, if dt itself is an occurrence, it will be returned. """ - if self._cache_complete: - gen = self._cache - else: - gen = self - last = None - if inc: - for i in gen: - if i > dt: - break - last = i - else: - for i in gen: - if i >= dt: - break - last = i - return last - - def after(self, dt, inc=False): - """ Returns the first recurrence after the given datetime instance. The - inc keyword defines what happens if dt is an occurrence. With - inc=True, if dt itself is an occurrence, it will be returned. """ - if self._cache_complete: - gen = self._cache - else: - gen = self - if inc: - for i in gen: - if i >= dt: - return i - else: - for i in gen: - if i > dt: - return i - return None - - def xafter(self, dt, count=None, inc=False): - """ - Generator which yields up to `count` recurrences after the given - datetime instance, equivalent to `after`. - - :param dt: - The datetime at which to start generating recurrences. - - :param count: - The maximum number of recurrences to generate. If `None` (default), - dates are generated until the recurrence rule is exhausted. - - :param inc: - If `dt` is an instance of the rule and `inc` is `True`, it is - included in the output. - - :yields: Yields a sequence of `datetime` objects. - """ - - if self._cache_complete: - gen = self._cache - else: - gen = self - - # Select the comparison function - if inc: - comp = lambda dc, dtc: dc >= dtc - else: - comp = lambda dc, dtc: dc > dtc - - # Generate dates - n = 0 - for d in gen: - if comp(d, dt): - if count is not None: - n += 1 - if n > count: - break - - yield d - - def between(self, after, before, inc=False, count=1): - """ Returns all the occurrences of the rrule between after and before. - The inc keyword defines what happens if after and/or before are - themselves occurrences. With inc=True, they will be included in the - list, if they are found in the recurrence set. """ - if self._cache_complete: - gen = self._cache - else: - gen = self - started = False - l = [] - if inc: - for i in gen: - if i > before: - break - elif not started: - if i >= after: - started = True - l.append(i) - else: - l.append(i) - else: - for i in gen: - if i >= before: - break - elif not started: - if i > after: - started = True - l.append(i) - else: - l.append(i) - return l - - -class rrule(rrulebase): - """ - That's the base of the rrule operation. It accepts all the keywords - defined in the RFC as its constructor parameters (except byday, - which was renamed to byweekday) and more. The constructor prototype is:: - - rrule(freq) - - Where freq must be one of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, - or SECONDLY. - - .. note:: - Per RFC section 3.3.10, recurrence instances falling on invalid dates - and times are ignored rather than coerced: - - Recurrence rules may generate recurrence instances with an invalid - date (e.g., February 30) or nonexistent local time (e.g., 1:30 AM - on a day where the local time is moved forward by an hour at 1:00 - AM). Such recurrence instances MUST be ignored and MUST NOT be - counted as part of the recurrence set. - - This can lead to possibly surprising behavior when, for example, the - start date occurs at the end of the month: - - >>> from dateutil.rrule import rrule, MONTHLY - >>> from datetime import datetime - >>> start_date = datetime(2014, 12, 31) - >>> list(rrule(freq=MONTHLY, count=4, dtstart=start_date)) - ... # doctest: +NORMALIZE_WHITESPACE - [datetime.datetime(2014, 12, 31, 0, 0), - datetime.datetime(2015, 1, 31, 0, 0), - datetime.datetime(2015, 3, 31, 0, 0), - datetime.datetime(2015, 5, 31, 0, 0)] - - Additionally, it supports the following keyword arguments: - - :param dtstart: - The recurrence start. Besides being the base for the recurrence, - missing parameters in the final recurrence instances will also be - extracted from this date. If not given, datetime.now() will be used - instead. - :param interval: - The interval between each freq iteration. For example, when using - YEARLY, an interval of 2 means once every two years, but with HOURLY, - it means once every two hours. The default interval is 1. - :param wkst: - The week start day. Must be one of the MO, TU, WE constants, or an - integer, specifying the first day of the week. This will affect - recurrences based on weekly periods. The default week start is got - from calendar.firstweekday(), and may be modified by - calendar.setfirstweekday(). - :param count: - If given, this determines how many occurrences will be generated. - - .. note:: - As of version 2.5.0, the use of the keyword ``until`` in conjunction - with ``count`` is deprecated, to make sure ``dateutil`` is fully - compliant with `RFC-5545 Sec. 3.3.10 `_. Therefore, ``until`` and ``count`` - **must not** occur in the same call to ``rrule``. - :param until: - If given, this must be a datetime instance specifying the upper-bound - limit of the recurrence. The last recurrence in the rule is the greatest - datetime that is less than or equal to the value specified in the - ``until`` parameter. - - .. note:: - As of version 2.5.0, the use of the keyword ``until`` in conjunction - with ``count`` is deprecated, to make sure ``dateutil`` is fully - compliant with `RFC-5545 Sec. 3.3.10 `_. Therefore, ``until`` and ``count`` - **must not** occur in the same call to ``rrule``. - :param bysetpos: - If given, it must be either an integer, or a sequence of integers, - positive or negative. Each given integer will specify an occurrence - number, corresponding to the nth occurrence of the rule inside the - frequency period. For example, a bysetpos of -1 if combined with a - MONTHLY frequency, and a byweekday of (MO, TU, WE, TH, FR), will - result in the last work day of every month. - :param bymonth: - If given, it must be either an integer, or a sequence of integers, - meaning the months to apply the recurrence to. - :param bymonthday: - If given, it must be either an integer, or a sequence of integers, - meaning the month days to apply the recurrence to. - :param byyearday: - If given, it must be either an integer, or a sequence of integers, - meaning the year days to apply the recurrence to. - :param byeaster: - If given, it must be either an integer, or a sequence of integers, - positive or negative. Each integer will define an offset from the - Easter Sunday. Passing the offset 0 to byeaster will yield the Easter - Sunday itself. This is an extension to the RFC specification. - :param byweekno: - If given, it must be either an integer, or a sequence of integers, - meaning the week numbers to apply the recurrence to. Week numbers - have the meaning described in ISO8601, that is, the first week of - the year is that containing at least four days of the new year. - :param byweekday: - If given, it must be either an integer (0 == MO), a sequence of - integers, one of the weekday constants (MO, TU, etc), or a sequence - of these constants. When given, these variables will define the - weekdays where the recurrence will be applied. It's also possible to - use an argument n for the weekday instances, which will mean the nth - occurrence of this weekday in the period. For example, with MONTHLY, - or with YEARLY and BYMONTH, using FR(+1) in byweekday will specify the - first friday of the month where the recurrence happens. Notice that in - the RFC documentation, this is specified as BYDAY, but was renamed to - avoid the ambiguity of that keyword. - :param byhour: - If given, it must be either an integer, or a sequence of integers, - meaning the hours to apply the recurrence to. - :param byminute: - If given, it must be either an integer, or a sequence of integers, - meaning the minutes to apply the recurrence to. - :param bysecond: - If given, it must be either an integer, or a sequence of integers, - meaning the seconds to apply the recurrence to. - :param cache: - If given, it must be a boolean value specifying to enable or disable - caching of results. If you will use the same rrule instance multiple - times, enabling caching will improve the performance considerably. - """ - def __init__(self, freq, dtstart=None, - interval=1, wkst=None, count=None, until=None, bysetpos=None, - bymonth=None, bymonthday=None, byyearday=None, byeaster=None, - byweekno=None, byweekday=None, - byhour=None, byminute=None, bysecond=None, - cache=False): - super(rrule, self).__init__(cache) - global easter - if not dtstart: - if until and until.tzinfo: - dtstart = datetime.datetime.now(tz=until.tzinfo).replace(microsecond=0) - else: - dtstart = datetime.datetime.now().replace(microsecond=0) - elif not isinstance(dtstart, datetime.datetime): - dtstart = datetime.datetime.fromordinal(dtstart.toordinal()) - else: - dtstart = dtstart.replace(microsecond=0) - self._dtstart = dtstart - self._tzinfo = dtstart.tzinfo - self._freq = freq - self._interval = interval - self._count = count - - # Cache the original byxxx rules, if they are provided, as the _byxxx - # attributes do not necessarily map to the inputs, and this can be - # a problem in generating the strings. Only store things if they've - # been supplied (the string retrieval will just use .get()) - self._original_rule = {} - - if until and not isinstance(until, datetime.datetime): - until = datetime.datetime.fromordinal(until.toordinal()) - self._until = until - - if self._dtstart and self._until: - if (self._dtstart.tzinfo is not None) != (self._until.tzinfo is not None): - # According to RFC5545 Section 3.3.10: - # https://tools.ietf.org/html/rfc5545#section-3.3.10 - # - # > If the "DTSTART" property is specified as a date with UTC - # > time or a date with local time and time zone reference, - # > then the UNTIL rule part MUST be specified as a date with - # > UTC time. - raise ValueError( - 'RRULE UNTIL values must be specified in UTC when DTSTART ' - 'is timezone-aware' - ) - - if count is not None and until: - warn("Using both 'count' and 'until' is inconsistent with RFC 5545" - " and has been deprecated in dateutil. Future versions will " - "raise an error.", DeprecationWarning) - - if wkst is None: - self._wkst = calendar.firstweekday() - elif isinstance(wkst, integer_types): - self._wkst = wkst - else: - self._wkst = wkst.weekday - - if bysetpos is None: - self._bysetpos = None - elif isinstance(bysetpos, integer_types): - if bysetpos == 0 or not (-366 <= bysetpos <= 366): - raise ValueError("bysetpos must be between 1 and 366, " - "or between -366 and -1") - self._bysetpos = (bysetpos,) - else: - self._bysetpos = tuple(bysetpos) - for pos in self._bysetpos: - if pos == 0 or not (-366 <= pos <= 366): - raise ValueError("bysetpos must be between 1 and 366, " - "or between -366 and -1") - - if self._bysetpos: - self._original_rule['bysetpos'] = self._bysetpos - - if (byweekno is None and byyearday is None and bymonthday is None and - byweekday is None and byeaster is None): - if freq == YEARLY: - if bymonth is None: - bymonth = dtstart.month - self._original_rule['bymonth'] = None - bymonthday = dtstart.day - self._original_rule['bymonthday'] = None - elif freq == MONTHLY: - bymonthday = dtstart.day - self._original_rule['bymonthday'] = None - elif freq == WEEKLY: - byweekday = dtstart.weekday() - self._original_rule['byweekday'] = None - - # bymonth - if bymonth is None: - self._bymonth = None - else: - if isinstance(bymonth, integer_types): - bymonth = (bymonth,) - - self._bymonth = tuple(sorted(set(bymonth))) - - if 'bymonth' not in self._original_rule: - self._original_rule['bymonth'] = self._bymonth - - # byyearday - if byyearday is None: - self._byyearday = None - else: - if isinstance(byyearday, integer_types): - byyearday = (byyearday,) - - self._byyearday = tuple(sorted(set(byyearday))) - self._original_rule['byyearday'] = self._byyearday - - # byeaster - if byeaster is not None: - if not easter: - from dateutil import easter - if isinstance(byeaster, integer_types): - self._byeaster = (byeaster,) - else: - self._byeaster = tuple(sorted(byeaster)) - - self._original_rule['byeaster'] = self._byeaster - else: - self._byeaster = None - - # bymonthday - if bymonthday is None: - self._bymonthday = () - self._bynmonthday = () - else: - if isinstance(bymonthday, integer_types): - bymonthday = (bymonthday,) - - bymonthday = set(bymonthday) # Ensure it's unique - - self._bymonthday = tuple(sorted(x for x in bymonthday if x > 0)) - self._bynmonthday = tuple(sorted(x for x in bymonthday if x < 0)) - - # Storing positive numbers first, then negative numbers - if 'bymonthday' not in self._original_rule: - self._original_rule['bymonthday'] = tuple( - itertools.chain(self._bymonthday, self._bynmonthday)) - - # byweekno - if byweekno is None: - self._byweekno = None - else: - if isinstance(byweekno, integer_types): - byweekno = (byweekno,) - - self._byweekno = tuple(sorted(set(byweekno))) - - self._original_rule['byweekno'] = self._byweekno - - # byweekday / bynweekday - if byweekday is None: - self._byweekday = None - self._bynweekday = None - else: - # If it's one of the valid non-sequence types, convert to a - # single-element sequence before the iterator that builds the - # byweekday set. - if isinstance(byweekday, integer_types) or hasattr(byweekday, "n"): - byweekday = (byweekday,) - - self._byweekday = set() - self._bynweekday = set() - for wday in byweekday: - if isinstance(wday, integer_types): - self._byweekday.add(wday) - elif not wday.n or freq > MONTHLY: - self._byweekday.add(wday.weekday) - else: - self._bynweekday.add((wday.weekday, wday.n)) - - if not self._byweekday: - self._byweekday = None - elif not self._bynweekday: - self._bynweekday = None - - if self._byweekday is not None: - self._byweekday = tuple(sorted(self._byweekday)) - orig_byweekday = [weekday(x) for x in self._byweekday] - else: - orig_byweekday = () - - if self._bynweekday is not None: - self._bynweekday = tuple(sorted(self._bynweekday)) - orig_bynweekday = [weekday(*x) for x in self._bynweekday] - else: - orig_bynweekday = () - - if 'byweekday' not in self._original_rule: - self._original_rule['byweekday'] = tuple(itertools.chain( - orig_byweekday, orig_bynweekday)) - - # byhour - if byhour is None: - if freq < HOURLY: - self._byhour = {dtstart.hour} - else: - self._byhour = None - else: - if isinstance(byhour, integer_types): - byhour = (byhour,) - - if freq == HOURLY: - self._byhour = self.__construct_byset(start=dtstart.hour, - byxxx=byhour, - base=24) - else: - self._byhour = set(byhour) - - self._byhour = tuple(sorted(self._byhour)) - self._original_rule['byhour'] = self._byhour - - # byminute - if byminute is None: - if freq < MINUTELY: - self._byminute = {dtstart.minute} - else: - self._byminute = None - else: - if isinstance(byminute, integer_types): - byminute = (byminute,) - - if freq == MINUTELY: - self._byminute = self.__construct_byset(start=dtstart.minute, - byxxx=byminute, - base=60) - else: - self._byminute = set(byminute) - - self._byminute = tuple(sorted(self._byminute)) - self._original_rule['byminute'] = self._byminute - - # bysecond - if bysecond is None: - if freq < SECONDLY: - self._bysecond = ((dtstart.second,)) - else: - self._bysecond = None - else: - if isinstance(bysecond, integer_types): - bysecond = (bysecond,) - - self._bysecond = set(bysecond) - - if freq == SECONDLY: - self._bysecond = self.__construct_byset(start=dtstart.second, - byxxx=bysecond, - base=60) - else: - self._bysecond = set(bysecond) - - self._bysecond = tuple(sorted(self._bysecond)) - self._original_rule['bysecond'] = self._bysecond - - if self._freq >= HOURLY: - self._timeset = None - else: - self._timeset = [] - for hour in self._byhour: - for minute in self._byminute: - for second in self._bysecond: - self._timeset.append( - datetime.time(hour, minute, second, - tzinfo=self._tzinfo)) - self._timeset.sort() - self._timeset = tuple(self._timeset) - - def __str__(self): - """ - Output a string that would generate this RRULE if passed to rrulestr. - This is mostly compatible with RFC5545, except for the - dateutil-specific extension BYEASTER. - """ - - output = [] - h, m, s = [None] * 3 - if self._dtstart: - output.append(self._dtstart.strftime('DTSTART:%Y%m%dT%H%M%S')) - h, m, s = self._dtstart.timetuple()[3:6] - - parts = ['FREQ=' + FREQNAMES[self._freq]] - if self._interval != 1: - parts.append('INTERVAL=' + str(self._interval)) - - if self._wkst: - parts.append('WKST=' + repr(weekday(self._wkst))[0:2]) - - if self._count is not None: - parts.append('COUNT=' + str(self._count)) - - if self._until: - parts.append(self._until.strftime('UNTIL=%Y%m%dT%H%M%S')) - - if self._original_rule.get('byweekday') is not None: - # The str() method on weekday objects doesn't generate - # RFC5545-compliant strings, so we should modify that. - original_rule = dict(self._original_rule) - wday_strings = [] - for wday in original_rule['byweekday']: - if wday.n: - wday_strings.append('{n:+d}{wday}'.format( - n=wday.n, - wday=repr(wday)[0:2])) - else: - wday_strings.append(repr(wday)) - - original_rule['byweekday'] = wday_strings - else: - original_rule = self._original_rule - - partfmt = '{name}={vals}' - for name, key in [('BYSETPOS', 'bysetpos'), - ('BYMONTH', 'bymonth'), - ('BYMONTHDAY', 'bymonthday'), - ('BYYEARDAY', 'byyearday'), - ('BYWEEKNO', 'byweekno'), - ('BYDAY', 'byweekday'), - ('BYHOUR', 'byhour'), - ('BYMINUTE', 'byminute'), - ('BYSECOND', 'bysecond'), - ('BYEASTER', 'byeaster')]: - value = original_rule.get(key) - if value: - parts.append(partfmt.format(name=name, vals=(','.join(str(v) - for v in value)))) - - output.append('RRULE:' + ';'.join(parts)) - return '\n'.join(output) - - def replace(self, **kwargs): - """Return new rrule with same attributes except for those attributes given new - values by whichever keyword arguments are specified.""" - new_kwargs = {"interval": self._interval, - "count": self._count, - "dtstart": self._dtstart, - "freq": self._freq, - "until": self._until, - "wkst": self._wkst, - "cache": False if self._cache is None else True } - new_kwargs.update(self._original_rule) - new_kwargs.update(kwargs) - return rrule(**new_kwargs) - - def _iter(self): - year, month, day, hour, minute, second, weekday, yearday, _ = \ - self._dtstart.timetuple() - - # Some local variables to speed things up a bit - freq = self._freq - interval = self._interval - wkst = self._wkst - until = self._until - bymonth = self._bymonth - byweekno = self._byweekno - byyearday = self._byyearday - byweekday = self._byweekday - byeaster = self._byeaster - bymonthday = self._bymonthday - bynmonthday = self._bynmonthday - bysetpos = self._bysetpos - byhour = self._byhour - byminute = self._byminute - bysecond = self._bysecond - - ii = _iterinfo(self) - ii.rebuild(year, month) - - getdayset = {YEARLY: ii.ydayset, - MONTHLY: ii.mdayset, - WEEKLY: ii.wdayset, - DAILY: ii.ddayset, - HOURLY: ii.ddayset, - MINUTELY: ii.ddayset, - SECONDLY: ii.ddayset}[freq] - - if freq < HOURLY: - timeset = self._timeset - else: - gettimeset = {HOURLY: ii.htimeset, - MINUTELY: ii.mtimeset, - SECONDLY: ii.stimeset}[freq] - if ((freq >= HOURLY and - self._byhour and hour not in self._byhour) or - (freq >= MINUTELY and - self._byminute and minute not in self._byminute) or - (freq >= SECONDLY and - self._bysecond and second not in self._bysecond)): - timeset = () - else: - timeset = gettimeset(hour, minute, second) - - total = 0 - count = self._count - while True: - # Get dayset with the right frequency - dayset, start, end = getdayset(year, month, day) - - # Do the "hard" work ;-) - filtered = False - for i in dayset[start:end]: - if ((bymonth and ii.mmask[i] not in bymonth) or - (byweekno and not ii.wnomask[i]) or - (byweekday and ii.wdaymask[i] not in byweekday) or - (ii.nwdaymask and not ii.nwdaymask[i]) or - (byeaster and not ii.eastermask[i]) or - ((bymonthday or bynmonthday) and - ii.mdaymask[i] not in bymonthday and - ii.nmdaymask[i] not in bynmonthday) or - (byyearday and - ((i < ii.yearlen and i+1 not in byyearday and - -ii.yearlen+i not in byyearday) or - (i >= ii.yearlen and i+1-ii.yearlen not in byyearday and - -ii.nextyearlen+i-ii.yearlen not in byyearday)))): - dayset[i] = None - filtered = True - - # Output results - if bysetpos and timeset: - poslist = [] - for pos in bysetpos: - if pos < 0: - daypos, timepos = divmod(pos, len(timeset)) - else: - daypos, timepos = divmod(pos-1, len(timeset)) - try: - i = [x for x in dayset[start:end] - if x is not None][daypos] - time = timeset[timepos] - except IndexError: - pass - else: - date = datetime.date.fromordinal(ii.yearordinal+i) - res = datetime.datetime.combine(date, time) - if res not in poslist: - poslist.append(res) - poslist.sort() - for res in poslist: - if until and res > until: - self._len = total - return - elif res >= self._dtstart: - if count is not None: - count -= 1 - if count < 0: - self._len = total - return - total += 1 - yield res - else: - for i in dayset[start:end]: - if i is not None: - date = datetime.date.fromordinal(ii.yearordinal + i) - for time in timeset: - res = datetime.datetime.combine(date, time) - if until and res > until: - self._len = total - return - elif res >= self._dtstart: - if count is not None: - count -= 1 - if count < 0: - self._len = total - return - - total += 1 - yield res - - # Handle frequency and interval - fixday = False - if freq == YEARLY: - year += interval - if year > datetime.MAXYEAR: - self._len = total - return - ii.rebuild(year, month) - elif freq == MONTHLY: - month += interval - if month > 12: - div, mod = divmod(month, 12) - month = mod - year += div - if month == 0: - month = 12 - year -= 1 - if year > datetime.MAXYEAR: - self._len = total - return - ii.rebuild(year, month) - elif freq == WEEKLY: - if wkst > weekday: - day += -(weekday+1+(6-wkst))+self._interval*7 - else: - day += -(weekday-wkst)+self._interval*7 - weekday = wkst - fixday = True - elif freq == DAILY: - day += interval - fixday = True - elif freq == HOURLY: - if filtered: - # Jump to one iteration before next day - hour += ((23-hour)//interval)*interval - - if byhour: - ndays, hour = self.__mod_distance(value=hour, - byxxx=self._byhour, - base=24) - else: - ndays, hour = divmod(hour+interval, 24) - - if ndays: - day += ndays - fixday = True - - timeset = gettimeset(hour, minute, second) - elif freq == MINUTELY: - if filtered: - # Jump to one iteration before next day - minute += ((1439-(hour*60+minute))//interval)*interval - - valid = False - rep_rate = (24*60) - for j in range(rep_rate // gcd(interval, rep_rate)): - if byminute: - nhours, minute = \ - self.__mod_distance(value=minute, - byxxx=self._byminute, - base=60) - else: - nhours, minute = divmod(minute+interval, 60) - - div, hour = divmod(hour+nhours, 24) - if div: - day += div - fixday = True - filtered = False - - if not byhour or hour in byhour: - valid = True - break - - if not valid: - raise ValueError('Invalid combination of interval and ' + - 'byhour resulting in empty rule.') - - timeset = gettimeset(hour, minute, second) - elif freq == SECONDLY: - if filtered: - # Jump to one iteration before next day - second += (((86399 - (hour * 3600 + minute * 60 + second)) - // interval) * interval) - - rep_rate = (24 * 3600) - valid = False - for j in range(0, rep_rate // gcd(interval, rep_rate)): - if bysecond: - nminutes, second = \ - self.__mod_distance(value=second, - byxxx=self._bysecond, - base=60) - else: - nminutes, second = divmod(second+interval, 60) - - div, minute = divmod(minute+nminutes, 60) - if div: - hour += div - div, hour = divmod(hour, 24) - if div: - day += div - fixday = True - - if ((not byhour or hour in byhour) and - (not byminute or minute in byminute) and - (not bysecond or second in bysecond)): - valid = True - break - - if not valid: - raise ValueError('Invalid combination of interval, ' + - 'byhour and byminute resulting in empty' + - ' rule.') - - timeset = gettimeset(hour, minute, second) - - if fixday and day > 28: - daysinmonth = calendar.monthrange(year, month)[1] - if day > daysinmonth: - while day > daysinmonth: - day -= daysinmonth - month += 1 - if month == 13: - month = 1 - year += 1 - if year > datetime.MAXYEAR: - self._len = total - return - daysinmonth = calendar.monthrange(year, month)[1] - ii.rebuild(year, month) - - def __construct_byset(self, start, byxxx, base): - """ - If a `BYXXX` sequence is passed to the constructor at the same level as - `FREQ` (e.g. `FREQ=HOURLY,BYHOUR={2,4,7},INTERVAL=3`), there are some - specifications which cannot be reached given some starting conditions. - - This occurs whenever the interval is not coprime with the base of a - given unit and the difference between the starting position and the - ending position is not coprime with the greatest common denominator - between the interval and the base. For example, with a FREQ of hourly - starting at 17:00 and an interval of 4, the only valid values for - BYHOUR would be {21, 1, 5, 9, 13, 17}, because 4 and 24 are not - coprime. - - :param start: - Specifies the starting position. - :param byxxx: - An iterable containing the list of allowed values. - :param base: - The largest allowable value for the specified frequency (e.g. - 24 hours, 60 minutes). - - This does not preserve the type of the iterable, returning a set, since - the values should be unique and the order is irrelevant, this will - speed up later lookups. - - In the event of an empty set, raises a :exception:`ValueError`, as this - results in an empty rrule. - """ - - cset = set() - - # Support a single byxxx value. - if isinstance(byxxx, integer_types): - byxxx = (byxxx, ) - - for num in byxxx: - i_gcd = gcd(self._interval, base) - # Use divmod rather than % because we need to wrap negative nums. - if i_gcd == 1 or divmod(num - start, i_gcd)[1] == 0: - cset.add(num) - - if len(cset) == 0: - raise ValueError("Invalid rrule byxxx generates an empty set.") - - return cset - - def __mod_distance(self, value, byxxx, base): - """ - Calculates the next value in a sequence where the `FREQ` parameter is - specified along with a `BYXXX` parameter at the same "level" - (e.g. `HOURLY` specified with `BYHOUR`). - - :param value: - The old value of the component. - :param byxxx: - The `BYXXX` set, which should have been generated by - `rrule._construct_byset`, or something else which checks that a - valid rule is present. - :param base: - The largest allowable value for the specified frequency (e.g. - 24 hours, 60 minutes). - - If a valid value is not found after `base` iterations (the maximum - number before the sequence would start to repeat), this raises a - :exception:`ValueError`, as no valid values were found. - - This returns a tuple of `divmod(n*interval, base)`, where `n` is the - smallest number of `interval` repetitions until the next specified - value in `byxxx` is found. - """ - accumulator = 0 - for ii in range(1, base + 1): - # Using divmod() over % to account for negative intervals - div, value = divmod(value + self._interval, base) - accumulator += div - if value in byxxx: - return (accumulator, value) - - -class _iterinfo(object): - __slots__ = ["rrule", "lastyear", "lastmonth", - "yearlen", "nextyearlen", "yearordinal", "yearweekday", - "mmask", "mrange", "mdaymask", "nmdaymask", - "wdaymask", "wnomask", "nwdaymask", "eastermask"] - - def __init__(self, rrule): - for attr in self.__slots__: - setattr(self, attr, None) - self.rrule = rrule - - def rebuild(self, year, month): - # Every mask is 7 days longer to handle cross-year weekly periods. - rr = self.rrule - if year != self.lastyear: - self.yearlen = 365 + calendar.isleap(year) - self.nextyearlen = 365 + calendar.isleap(year + 1) - firstyday = datetime.date(year, 1, 1) - self.yearordinal = firstyday.toordinal() - self.yearweekday = firstyday.weekday() - - wday = datetime.date(year, 1, 1).weekday() - if self.yearlen == 365: - self.mmask = M365MASK - self.mdaymask = MDAY365MASK - self.nmdaymask = NMDAY365MASK - self.wdaymask = WDAYMASK[wday:] - self.mrange = M365RANGE - else: - self.mmask = M366MASK - self.mdaymask = MDAY366MASK - self.nmdaymask = NMDAY366MASK - self.wdaymask = WDAYMASK[wday:] - self.mrange = M366RANGE - - if not rr._byweekno: - self.wnomask = None - else: - self.wnomask = [0]*(self.yearlen+7) - # no1wkst = firstwkst = self.wdaymask.index(rr._wkst) - no1wkst = firstwkst = (7-self.yearweekday+rr._wkst) % 7 - if no1wkst >= 4: - no1wkst = 0 - # Number of days in the year, plus the days we got - # from last year. - wyearlen = self.yearlen+(self.yearweekday-rr._wkst) % 7 - else: - # Number of days in the year, minus the days we - # left in last year. - wyearlen = self.yearlen-no1wkst - div, mod = divmod(wyearlen, 7) - numweeks = div+mod//4 - for n in rr._byweekno: - if n < 0: - n += numweeks+1 - if not (0 < n <= numweeks): - continue - if n > 1: - i = no1wkst+(n-1)*7 - if no1wkst != firstwkst: - i -= 7-firstwkst - else: - i = no1wkst - for j in range(7): - self.wnomask[i] = 1 - i += 1 - if self.wdaymask[i] == rr._wkst: - break - if 1 in rr._byweekno: - # Check week number 1 of next year as well - # TODO: Check -numweeks for next year. - i = no1wkst+numweeks*7 - if no1wkst != firstwkst: - i -= 7-firstwkst - if i < self.yearlen: - # If week starts in next year, we - # don't care about it. - for j in range(7): - self.wnomask[i] = 1 - i += 1 - if self.wdaymask[i] == rr._wkst: - break - if no1wkst: - # Check last week number of last year as - # well. If no1wkst is 0, either the year - # started on week start, or week number 1 - # got days from last year, so there are no - # days from last year's last week number in - # this year. - if -1 not in rr._byweekno: - lyearweekday = datetime.date(year-1, 1, 1).weekday() - lno1wkst = (7-lyearweekday+rr._wkst) % 7 - lyearlen = 365+calendar.isleap(year-1) - if lno1wkst >= 4: - lno1wkst = 0 - lnumweeks = 52+(lyearlen + - (lyearweekday-rr._wkst) % 7) % 7//4 - else: - lnumweeks = 52+(self.yearlen-no1wkst) % 7//4 - else: - lnumweeks = -1 - if lnumweeks in rr._byweekno: - for i in range(no1wkst): - self.wnomask[i] = 1 - - if (rr._bynweekday and (month != self.lastmonth or - year != self.lastyear)): - ranges = [] - if rr._freq == YEARLY: - if rr._bymonth: - for month in rr._bymonth: - ranges.append(self.mrange[month-1:month+1]) - else: - ranges = [(0, self.yearlen)] - elif rr._freq == MONTHLY: - ranges = [self.mrange[month-1:month+1]] - if ranges: - # Weekly frequency won't get here, so we may not - # care about cross-year weekly periods. - self.nwdaymask = [0]*self.yearlen - for first, last in ranges: - last -= 1 - for wday, n in rr._bynweekday: - if n < 0: - i = last+(n+1)*7 - i -= (self.wdaymask[i]-wday) % 7 - else: - i = first+(n-1)*7 - i += (7-self.wdaymask[i]+wday) % 7 - if first <= i <= last: - self.nwdaymask[i] = 1 - - if rr._byeaster: - self.eastermask = [0]*(self.yearlen+7) - eyday = easter.easter(year).toordinal()-self.yearordinal - for offset in rr._byeaster: - self.eastermask[eyday+offset] = 1 - - self.lastyear = year - self.lastmonth = month - - def ydayset(self, year, month, day): - return list(range(self.yearlen)), 0, self.yearlen - - def mdayset(self, year, month, day): - dset = [None]*self.yearlen - start, end = self.mrange[month-1:month+1] - for i in range(start, end): - dset[i] = i - return dset, start, end - - def wdayset(self, year, month, day): - # We need to handle cross-year weeks here. - dset = [None]*(self.yearlen+7) - i = datetime.date(year, month, day).toordinal()-self.yearordinal - start = i - for j in range(7): - dset[i] = i - i += 1 - # if (not (0 <= i < self.yearlen) or - # self.wdaymask[i] == self.rrule._wkst): - # This will cross the year boundary, if necessary. - if self.wdaymask[i] == self.rrule._wkst: - break - return dset, start, i - - def ddayset(self, year, month, day): - dset = [None] * self.yearlen - i = datetime.date(year, month, day).toordinal() - self.yearordinal - dset[i] = i - return dset, i, i + 1 - - def htimeset(self, hour, minute, second): - tset = [] - rr = self.rrule - for minute in rr._byminute: - for second in rr._bysecond: - tset.append(datetime.time(hour, minute, second, - tzinfo=rr._tzinfo)) - tset.sort() - return tset - - def mtimeset(self, hour, minute, second): - tset = [] - rr = self.rrule - for second in rr._bysecond: - tset.append(datetime.time(hour, minute, second, tzinfo=rr._tzinfo)) - tset.sort() - return tset - - def stimeset(self, hour, minute, second): - return (datetime.time(hour, minute, second, - tzinfo=self.rrule._tzinfo),) - - -class rruleset(rrulebase): - """ The rruleset type allows more complex recurrence setups, mixing - multiple rules, dates, exclusion rules, and exclusion dates. The type - constructor takes the following keyword arguments: - - :param cache: If True, caching of results will be enabled, improving - performance of multiple queries considerably. """ - - class _genitem(object): - def __init__(self, genlist, gen): - try: - self.dt = advance_iterator(gen) - genlist.append(self) - except StopIteration: - pass - self.genlist = genlist - self.gen = gen - - def __next__(self): - try: - self.dt = advance_iterator(self.gen) - except StopIteration: - if self.genlist[0] is self: - heapq.heappop(self.genlist) - else: - self.genlist.remove(self) - heapq.heapify(self.genlist) - - next = __next__ - - def __lt__(self, other): - return self.dt < other.dt - - def __gt__(self, other): - return self.dt > other.dt - - def __eq__(self, other): - return self.dt == other.dt - - def __ne__(self, other): - return self.dt != other.dt - - def __init__(self, cache=False): - super(rruleset, self).__init__(cache) - self._rrule = [] - self._rdate = [] - self._exrule = [] - self._exdate = [] - - @_invalidates_cache - def rrule(self, rrule): - """ Include the given :py:class:`rrule` instance in the recurrence set - generation. """ - self._rrule.append(rrule) - - @_invalidates_cache - def rdate(self, rdate): - """ Include the given :py:class:`datetime` instance in the recurrence - set generation. """ - self._rdate.append(rdate) - - @_invalidates_cache - def exrule(self, exrule): - """ Include the given rrule instance in the recurrence set exclusion - list. Dates which are part of the given recurrence rules will not - be generated, even if some inclusive rrule or rdate matches them. - """ - self._exrule.append(exrule) - - @_invalidates_cache - def exdate(self, exdate): - """ Include the given datetime instance in the recurrence set - exclusion list. Dates included that way will not be generated, - even if some inclusive rrule or rdate matches them. """ - self._exdate.append(exdate) - - def _iter(self): - rlist = [] - self._rdate.sort() - self._genitem(rlist, iter(self._rdate)) - for gen in [iter(x) for x in self._rrule]: - self._genitem(rlist, gen) - exlist = [] - self._exdate.sort() - self._genitem(exlist, iter(self._exdate)) - for gen in [iter(x) for x in self._exrule]: - self._genitem(exlist, gen) - lastdt = None - total = 0 - heapq.heapify(rlist) - heapq.heapify(exlist) - while rlist: - ritem = rlist[0] - if not lastdt or lastdt != ritem.dt: - while exlist and exlist[0] < ritem: - exitem = exlist[0] - advance_iterator(exitem) - if exlist and exlist[0] is exitem: - heapq.heapreplace(exlist, exitem) - if not exlist or ritem != exlist[0]: - total += 1 - yield ritem.dt - lastdt = ritem.dt - advance_iterator(ritem) - if rlist and rlist[0] is ritem: - heapq.heapreplace(rlist, ritem) - self._len = total - - - - -class _rrulestr(object): - """ Parses a string representation of a recurrence rule or set of - recurrence rules. - - :param s: - Required, a string defining one or more recurrence rules. - - :param dtstart: - If given, used as the default recurrence start if not specified in the - rule string. - - :param cache: - If set ``True`` caching of results will be enabled, improving - performance of multiple queries considerably. - - :param unfold: - If set ``True`` indicates that a rule string is split over more - than one line and should be joined before processing. - - :param forceset: - If set ``True`` forces a :class:`dateutil.rrule.rruleset` to - be returned. - - :param compatible: - If set ``True`` forces ``unfold`` and ``forceset`` to be ``True``. - - :param ignoretz: - If set ``True``, time zones in parsed strings are ignored and a naive - :class:`datetime.datetime` object is returned. - - :param tzids: - If given, a callable or mapping used to retrieve a - :class:`datetime.tzinfo` from a string representation. - Defaults to :func:`dateutil.tz.gettz`. - - :param tzinfos: - Additional time zone names / aliases which may be present in a string - representation. See :func:`dateutil.parser.parse` for more - information. - - :return: - Returns a :class:`dateutil.rrule.rruleset` or - :class:`dateutil.rrule.rrule` - """ - - _freq_map = {"YEARLY": YEARLY, - "MONTHLY": MONTHLY, - "WEEKLY": WEEKLY, - "DAILY": DAILY, - "HOURLY": HOURLY, - "MINUTELY": MINUTELY, - "SECONDLY": SECONDLY} - - _weekday_map = {"MO": 0, "TU": 1, "WE": 2, "TH": 3, - "FR": 4, "SA": 5, "SU": 6} - - def _handle_int(self, rrkwargs, name, value, **kwargs): - rrkwargs[name.lower()] = int(value) - - def _handle_int_list(self, rrkwargs, name, value, **kwargs): - rrkwargs[name.lower()] = [int(x) for x in value.split(',')] - - _handle_INTERVAL = _handle_int - _handle_COUNT = _handle_int - _handle_BYSETPOS = _handle_int_list - _handle_BYMONTH = _handle_int_list - _handle_BYMONTHDAY = _handle_int_list - _handle_BYYEARDAY = _handle_int_list - _handle_BYEASTER = _handle_int_list - _handle_BYWEEKNO = _handle_int_list - _handle_BYHOUR = _handle_int_list - _handle_BYMINUTE = _handle_int_list - _handle_BYSECOND = _handle_int_list - - def _handle_FREQ(self, rrkwargs, name, value, **kwargs): - rrkwargs["freq"] = self._freq_map[value] - - def _handle_UNTIL(self, rrkwargs, name, value, **kwargs): - global parser - if not parser: - from dateutil import parser - try: - rrkwargs["until"] = parser.parse(value, - ignoretz=kwargs.get("ignoretz"), - tzinfos=kwargs.get("tzinfos")) - except ValueError: - raise ValueError("invalid until date") - - def _handle_WKST(self, rrkwargs, name, value, **kwargs): - rrkwargs["wkst"] = self._weekday_map[value] - - def _handle_BYWEEKDAY(self, rrkwargs, name, value, **kwargs): - """ - Two ways to specify this: +1MO or MO(+1) - """ - l = [] - for wday in value.split(','): - if '(' in wday: - # If it's of the form TH(+1), etc. - splt = wday.split('(') - w = splt[0] - n = int(splt[1][:-1]) - elif len(wday): - # If it's of the form +1MO - for i in range(len(wday)): - if wday[i] not in '+-0123456789': - break - n = wday[:i] or None - w = wday[i:] - if n: - n = int(n) - else: - raise ValueError("Invalid (empty) BYDAY specification.") - - l.append(weekdays[self._weekday_map[w]](n)) - rrkwargs["byweekday"] = l - - _handle_BYDAY = _handle_BYWEEKDAY - - def _parse_rfc_rrule(self, line, - dtstart=None, - cache=False, - ignoretz=False, - tzinfos=None): - if line.find(':') != -1: - name, value = line.split(':') - if name != "RRULE": - raise ValueError("unknown parameter name") - else: - value = line - rrkwargs = {} - for pair in value.split(';'): - name, value = pair.split('=') - name = name.upper() - value = value.upper() - try: - getattr(self, "_handle_"+name)(rrkwargs, name, value, - ignoretz=ignoretz, - tzinfos=tzinfos) - except AttributeError: - raise ValueError("unknown parameter '%s'" % name) - except (KeyError, ValueError): - raise ValueError("invalid '%s': %s" % (name, value)) - return rrule(dtstart=dtstart, cache=cache, **rrkwargs) - - def _parse_date_value(self, date_value, parms, rule_tzids, - ignoretz, tzids, tzinfos): - global parser - if not parser: - from dateutil import parser - - datevals = [] - value_found = False - TZID = None - - for parm in parms: - if parm.startswith("TZID="): - try: - tzkey = rule_tzids[parm.split('TZID=')[-1]] - except KeyError: - continue - if tzids is None: - from . import tz - tzlookup = tz.gettz - elif callable(tzids): - tzlookup = tzids - else: - tzlookup = getattr(tzids, 'get', None) - if tzlookup is None: - msg = ('tzids must be a callable, mapping, or None, ' - 'not %s' % tzids) - raise ValueError(msg) - - TZID = tzlookup(tzkey) - continue - - # RFC 5445 3.8.2.4: The VALUE parameter is optional, but may be found - # only once. - if parm not in {"VALUE=DATE-TIME", "VALUE=DATE"}: - raise ValueError("unsupported parm: " + parm) - else: - if value_found: - msg = ("Duplicate value parameter found in: " + parm) - raise ValueError(msg) - value_found = True - - for datestr in date_value.split(','): - date = parser.parse(datestr, ignoretz=ignoretz, tzinfos=tzinfos) - if TZID is not None: - if date.tzinfo is None: - date = date.replace(tzinfo=TZID) - else: - raise ValueError('DTSTART/EXDATE specifies multiple timezone') - datevals.append(date) - - return datevals - - def _parse_rfc(self, s, - dtstart=None, - cache=False, - unfold=False, - forceset=False, - compatible=False, - ignoretz=False, - tzids=None, - tzinfos=None): - global parser - if compatible: - forceset = True - unfold = True - - TZID_NAMES = dict(map( - lambda x: (x.upper(), x), - re.findall('TZID=(?P[^:]+):', s) - )) - s = s.upper() - if not s.strip(): - raise ValueError("empty string") - if unfold: - lines = s.splitlines() - i = 0 - while i < len(lines): - line = lines[i].rstrip() - if not line: - del lines[i] - elif i > 0 and line[0] == " ": - lines[i-1] += line[1:] - del lines[i] - else: - i += 1 - else: - lines = s.split() - if (not forceset and len(lines) == 1 and (s.find(':') == -1 or - s.startswith('RRULE:'))): - return self._parse_rfc_rrule(lines[0], cache=cache, - dtstart=dtstart, ignoretz=ignoretz, - tzinfos=tzinfos) - else: - rrulevals = [] - rdatevals = [] - exrulevals = [] - exdatevals = [] - for line in lines: - if not line: - continue - if line.find(':') == -1: - name = "RRULE" - value = line - else: - name, value = line.split(':', 1) - parms = name.split(';') - if not parms: - raise ValueError("empty property name") - name = parms[0] - parms = parms[1:] - if name == "RRULE": - for parm in parms: - raise ValueError("unsupported RRULE parm: "+parm) - rrulevals.append(value) - elif name == "RDATE": - for parm in parms: - if parm != "VALUE=DATE-TIME": - raise ValueError("unsupported RDATE parm: "+parm) - rdatevals.append(value) - elif name == "EXRULE": - for parm in parms: - raise ValueError("unsupported EXRULE parm: "+parm) - exrulevals.append(value) - elif name == "EXDATE": - exdatevals.extend( - self._parse_date_value(value, parms, - TZID_NAMES, ignoretz, - tzids, tzinfos) - ) - elif name == "DTSTART": - dtvals = self._parse_date_value(value, parms, TZID_NAMES, - ignoretz, tzids, tzinfos) - if len(dtvals) != 1: - raise ValueError("Multiple DTSTART values specified:" + - value) - dtstart = dtvals[0] - else: - raise ValueError("unsupported property: "+name) - if (forceset or len(rrulevals) > 1 or rdatevals - or exrulevals or exdatevals): - if not parser and (rdatevals or exdatevals): - from dateutil import parser - rset = rruleset(cache=cache) - for value in rrulevals: - rset.rrule(self._parse_rfc_rrule(value, dtstart=dtstart, - ignoretz=ignoretz, - tzinfos=tzinfos)) - for value in rdatevals: - for datestr in value.split(','): - rset.rdate(parser.parse(datestr, - ignoretz=ignoretz, - tzinfos=tzinfos)) - for value in exrulevals: - rset.exrule(self._parse_rfc_rrule(value, dtstart=dtstart, - ignoretz=ignoretz, - tzinfos=tzinfos)) - for value in exdatevals: - rset.exdate(value) - if compatible and dtstart: - rset.rdate(dtstart) - return rset - else: - return self._parse_rfc_rrule(rrulevals[0], - dtstart=dtstart, - cache=cache, - ignoretz=ignoretz, - tzinfos=tzinfos) - - def __call__(self, s, **kwargs): - return self._parse_rfc(s, **kwargs) - - -rrulestr = _rrulestr() - -# vim:ts=4:sw=4:et diff --git a/.venv/Lib/site-packages/dateutil/tz/__init__.py b/.venv/Lib/site-packages/dateutil/tz/__init__.py deleted file mode 100644 index af1352c..0000000 --- a/.venv/Lib/site-packages/dateutil/tz/__init__.py +++ /dev/null @@ -1,12 +0,0 @@ -# -*- coding: utf-8 -*- -from .tz import * -from .tz import __doc__ - -__all__ = ["tzutc", "tzoffset", "tzlocal", "tzfile", "tzrange", - "tzstr", "tzical", "tzwin", "tzwinlocal", "gettz", - "enfold", "datetime_ambiguous", "datetime_exists", - "resolve_imaginary", "UTC", "DeprecatedTzFormatWarning"] - - -class DeprecatedTzFormatWarning(Warning): - """Warning raised when time zones are parsed from deprecated formats.""" diff --git a/.venv/Lib/site-packages/dateutil/tz/__pycache__/__init__.cpython-38.pyc b/.venv/Lib/site-packages/dateutil/tz/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index 29edc5a..0000000 Binary files a/.venv/Lib/site-packages/dateutil/tz/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/dateutil/tz/__pycache__/_common.cpython-38.pyc b/.venv/Lib/site-packages/dateutil/tz/__pycache__/_common.cpython-38.pyc deleted file mode 100644 index cd0ca67..0000000 Binary files a/.venv/Lib/site-packages/dateutil/tz/__pycache__/_common.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/dateutil/tz/__pycache__/_factories.cpython-38.pyc b/.venv/Lib/site-packages/dateutil/tz/__pycache__/_factories.cpython-38.pyc deleted file mode 100644 index 088f8af..0000000 Binary files a/.venv/Lib/site-packages/dateutil/tz/__pycache__/_factories.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/dateutil/tz/__pycache__/tz.cpython-38.pyc b/.venv/Lib/site-packages/dateutil/tz/__pycache__/tz.cpython-38.pyc deleted file mode 100644 index 589c6df..0000000 Binary files a/.venv/Lib/site-packages/dateutil/tz/__pycache__/tz.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/dateutil/tz/__pycache__/win.cpython-38.pyc b/.venv/Lib/site-packages/dateutil/tz/__pycache__/win.cpython-38.pyc deleted file mode 100644 index bedb6ba..0000000 Binary files a/.venv/Lib/site-packages/dateutil/tz/__pycache__/win.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/dateutil/tz/_common.py b/.venv/Lib/site-packages/dateutil/tz/_common.py deleted file mode 100644 index e6ac118..0000000 --- a/.venv/Lib/site-packages/dateutil/tz/_common.py +++ /dev/null @@ -1,419 +0,0 @@ -from six import PY2 - -from functools import wraps - -from datetime import datetime, timedelta, tzinfo - - -ZERO = timedelta(0) - -__all__ = ['tzname_in_python2', 'enfold'] - - -def tzname_in_python2(namefunc): - """Change unicode output into bytestrings in Python 2 - - tzname() API changed in Python 3. It used to return bytes, but was changed - to unicode strings - """ - if PY2: - @wraps(namefunc) - def adjust_encoding(*args, **kwargs): - name = namefunc(*args, **kwargs) - if name is not None: - name = name.encode() - - return name - - return adjust_encoding - else: - return namefunc - - -# The following is adapted from Alexander Belopolsky's tz library -# https://github.com/abalkin/tz -if hasattr(datetime, 'fold'): - # This is the pre-python 3.6 fold situation - def enfold(dt, fold=1): - """ - Provides a unified interface for assigning the ``fold`` attribute to - datetimes both before and after the implementation of PEP-495. - - :param fold: - The value for the ``fold`` attribute in the returned datetime. This - should be either 0 or 1. - - :return: - Returns an object for which ``getattr(dt, 'fold', 0)`` returns - ``fold`` for all versions of Python. In versions prior to - Python 3.6, this is a ``_DatetimeWithFold`` object, which is a - subclass of :py:class:`datetime.datetime` with the ``fold`` - attribute added, if ``fold`` is 1. - - .. versionadded:: 2.6.0 - """ - return dt.replace(fold=fold) - -else: - class _DatetimeWithFold(datetime): - """ - This is a class designed to provide a PEP 495-compliant interface for - Python versions before 3.6. It is used only for dates in a fold, so - the ``fold`` attribute is fixed at ``1``. - - .. versionadded:: 2.6.0 - """ - __slots__ = () - - def replace(self, *args, **kwargs): - """ - Return a datetime with the same attributes, except for those - attributes given new values by whichever keyword arguments are - specified. Note that tzinfo=None can be specified to create a naive - datetime from an aware datetime with no conversion of date and time - data. - - This is reimplemented in ``_DatetimeWithFold`` because pypy3 will - return a ``datetime.datetime`` even if ``fold`` is unchanged. - """ - argnames = ( - 'year', 'month', 'day', 'hour', 'minute', 'second', - 'microsecond', 'tzinfo' - ) - - for arg, argname in zip(args, argnames): - if argname in kwargs: - raise TypeError('Duplicate argument: {}'.format(argname)) - - kwargs[argname] = arg - - for argname in argnames: - if argname not in kwargs: - kwargs[argname] = getattr(self, argname) - - dt_class = self.__class__ if kwargs.get('fold', 1) else datetime - - return dt_class(**kwargs) - - @property - def fold(self): - return 1 - - def enfold(dt, fold=1): - """ - Provides a unified interface for assigning the ``fold`` attribute to - datetimes both before and after the implementation of PEP-495. - - :param fold: - The value for the ``fold`` attribute in the returned datetime. This - should be either 0 or 1. - - :return: - Returns an object for which ``getattr(dt, 'fold', 0)`` returns - ``fold`` for all versions of Python. In versions prior to - Python 3.6, this is a ``_DatetimeWithFold`` object, which is a - subclass of :py:class:`datetime.datetime` with the ``fold`` - attribute added, if ``fold`` is 1. - - .. versionadded:: 2.6.0 - """ - if getattr(dt, 'fold', 0) == fold: - return dt - - args = dt.timetuple()[:6] - args += (dt.microsecond, dt.tzinfo) - - if fold: - return _DatetimeWithFold(*args) - else: - return datetime(*args) - - -def _validate_fromutc_inputs(f): - """ - The CPython version of ``fromutc`` checks that the input is a ``datetime`` - object and that ``self`` is attached as its ``tzinfo``. - """ - @wraps(f) - def fromutc(self, dt): - if not isinstance(dt, datetime): - raise TypeError("fromutc() requires a datetime argument") - if dt.tzinfo is not self: - raise ValueError("dt.tzinfo is not self") - - return f(self, dt) - - return fromutc - - -class _tzinfo(tzinfo): - """ - Base class for all ``dateutil`` ``tzinfo`` objects. - """ - - def is_ambiguous(self, dt): - """ - Whether or not the "wall time" of a given datetime is ambiguous in this - zone. - - :param dt: - A :py:class:`datetime.datetime`, naive or time zone aware. - - - :return: - Returns ``True`` if ambiguous, ``False`` otherwise. - - .. versionadded:: 2.6.0 - """ - - dt = dt.replace(tzinfo=self) - - wall_0 = enfold(dt, fold=0) - wall_1 = enfold(dt, fold=1) - - same_offset = wall_0.utcoffset() == wall_1.utcoffset() - same_dt = wall_0.replace(tzinfo=None) == wall_1.replace(tzinfo=None) - - return same_dt and not same_offset - - def _fold_status(self, dt_utc, dt_wall): - """ - Determine the fold status of a "wall" datetime, given a representation - of the same datetime as a (naive) UTC datetime. This is calculated based - on the assumption that ``dt.utcoffset() - dt.dst()`` is constant for all - datetimes, and that this offset is the actual number of hours separating - ``dt_utc`` and ``dt_wall``. - - :param dt_utc: - Representation of the datetime as UTC - - :param dt_wall: - Representation of the datetime as "wall time". This parameter must - either have a `fold` attribute or have a fold-naive - :class:`datetime.tzinfo` attached, otherwise the calculation may - fail. - """ - if self.is_ambiguous(dt_wall): - delta_wall = dt_wall - dt_utc - _fold = int(delta_wall == (dt_utc.utcoffset() - dt_utc.dst())) - else: - _fold = 0 - - return _fold - - def _fold(self, dt): - return getattr(dt, 'fold', 0) - - def _fromutc(self, dt): - """ - Given a timezone-aware datetime in a given timezone, calculates a - timezone-aware datetime in a new timezone. - - Since this is the one time that we *know* we have an unambiguous - datetime object, we take this opportunity to determine whether the - datetime is ambiguous and in a "fold" state (e.g. if it's the first - occurrence, chronologically, of the ambiguous datetime). - - :param dt: - A timezone-aware :class:`datetime.datetime` object. - """ - - # Re-implement the algorithm from Python's datetime.py - dtoff = dt.utcoffset() - if dtoff is None: - raise ValueError("fromutc() requires a non-None utcoffset() " - "result") - - # The original datetime.py code assumes that `dst()` defaults to - # zero during ambiguous times. PEP 495 inverts this presumption, so - # for pre-PEP 495 versions of python, we need to tweak the algorithm. - dtdst = dt.dst() - if dtdst is None: - raise ValueError("fromutc() requires a non-None dst() result") - delta = dtoff - dtdst - - dt += delta - # Set fold=1 so we can default to being in the fold for - # ambiguous dates. - dtdst = enfold(dt, fold=1).dst() - if dtdst is None: - raise ValueError("fromutc(): dt.dst gave inconsistent " - "results; cannot convert") - return dt + dtdst - - @_validate_fromutc_inputs - def fromutc(self, dt): - """ - Given a timezone-aware datetime in a given timezone, calculates a - timezone-aware datetime in a new timezone. - - Since this is the one time that we *know* we have an unambiguous - datetime object, we take this opportunity to determine whether the - datetime is ambiguous and in a "fold" state (e.g. if it's the first - occurrence, chronologically, of the ambiguous datetime). - - :param dt: - A timezone-aware :class:`datetime.datetime` object. - """ - dt_wall = self._fromutc(dt) - - # Calculate the fold status given the two datetimes. - _fold = self._fold_status(dt, dt_wall) - - # Set the default fold value for ambiguous dates - return enfold(dt_wall, fold=_fold) - - -class tzrangebase(_tzinfo): - """ - This is an abstract base class for time zones represented by an annual - transition into and out of DST. Child classes should implement the following - methods: - - * ``__init__(self, *args, **kwargs)`` - * ``transitions(self, year)`` - this is expected to return a tuple of - datetimes representing the DST on and off transitions in standard - time. - - A fully initialized ``tzrangebase`` subclass should also provide the - following attributes: - * ``hasdst``: Boolean whether or not the zone uses DST. - * ``_dst_offset`` / ``_std_offset``: :class:`datetime.timedelta` objects - representing the respective UTC offsets. - * ``_dst_abbr`` / ``_std_abbr``: Strings representing the timezone short - abbreviations in DST and STD, respectively. - * ``_hasdst``: Whether or not the zone has DST. - - .. versionadded:: 2.6.0 - """ - def __init__(self): - raise NotImplementedError('tzrangebase is an abstract base class') - - def utcoffset(self, dt): - isdst = self._isdst(dt) - - if isdst is None: - return None - elif isdst: - return self._dst_offset - else: - return self._std_offset - - def dst(self, dt): - isdst = self._isdst(dt) - - if isdst is None: - return None - elif isdst: - return self._dst_base_offset - else: - return ZERO - - @tzname_in_python2 - def tzname(self, dt): - if self._isdst(dt): - return self._dst_abbr - else: - return self._std_abbr - - def fromutc(self, dt): - """ Given a datetime in UTC, return local time """ - if not isinstance(dt, datetime): - raise TypeError("fromutc() requires a datetime argument") - - if dt.tzinfo is not self: - raise ValueError("dt.tzinfo is not self") - - # Get transitions - if there are none, fixed offset - transitions = self.transitions(dt.year) - if transitions is None: - return dt + self.utcoffset(dt) - - # Get the transition times in UTC - dston, dstoff = transitions - - dston -= self._std_offset - dstoff -= self._std_offset - - utc_transitions = (dston, dstoff) - dt_utc = dt.replace(tzinfo=None) - - isdst = self._naive_isdst(dt_utc, utc_transitions) - - if isdst: - dt_wall = dt + self._dst_offset - else: - dt_wall = dt + self._std_offset - - _fold = int(not isdst and self.is_ambiguous(dt_wall)) - - return enfold(dt_wall, fold=_fold) - - def is_ambiguous(self, dt): - """ - Whether or not the "wall time" of a given datetime is ambiguous in this - zone. - - :param dt: - A :py:class:`datetime.datetime`, naive or time zone aware. - - - :return: - Returns ``True`` if ambiguous, ``False`` otherwise. - - .. versionadded:: 2.6.0 - """ - if not self.hasdst: - return False - - start, end = self.transitions(dt.year) - - dt = dt.replace(tzinfo=None) - return (end <= dt < end + self._dst_base_offset) - - def _isdst(self, dt): - if not self.hasdst: - return False - elif dt is None: - return None - - transitions = self.transitions(dt.year) - - if transitions is None: - return False - - dt = dt.replace(tzinfo=None) - - isdst = self._naive_isdst(dt, transitions) - - # Handle ambiguous dates - if not isdst and self.is_ambiguous(dt): - return not self._fold(dt) - else: - return isdst - - def _naive_isdst(self, dt, transitions): - dston, dstoff = transitions - - dt = dt.replace(tzinfo=None) - - if dston < dstoff: - isdst = dston <= dt < dstoff - else: - isdst = not dstoff <= dt < dston - - return isdst - - @property - def _dst_base_offset(self): - return self._dst_offset - self._std_offset - - __hash__ = None - - def __ne__(self, other): - return not (self == other) - - def __repr__(self): - return "%s(...)" % self.__class__.__name__ - - __reduce__ = object.__reduce__ diff --git a/.venv/Lib/site-packages/dateutil/tz/_factories.py b/.venv/Lib/site-packages/dateutil/tz/_factories.py deleted file mode 100644 index f8a6589..0000000 --- a/.venv/Lib/site-packages/dateutil/tz/_factories.py +++ /dev/null @@ -1,80 +0,0 @@ -from datetime import timedelta -import weakref -from collections import OrderedDict - -from six.moves import _thread - - -class _TzSingleton(type): - def __init__(cls, *args, **kwargs): - cls.__instance = None - super(_TzSingleton, cls).__init__(*args, **kwargs) - - def __call__(cls): - if cls.__instance is None: - cls.__instance = super(_TzSingleton, cls).__call__() - return cls.__instance - - -class _TzFactory(type): - def instance(cls, *args, **kwargs): - """Alternate constructor that returns a fresh instance""" - return type.__call__(cls, *args, **kwargs) - - -class _TzOffsetFactory(_TzFactory): - def __init__(cls, *args, **kwargs): - cls.__instances = weakref.WeakValueDictionary() - cls.__strong_cache = OrderedDict() - cls.__strong_cache_size = 8 - - cls._cache_lock = _thread.allocate_lock() - - def __call__(cls, name, offset): - if isinstance(offset, timedelta): - key = (name, offset.total_seconds()) - else: - key = (name, offset) - - instance = cls.__instances.get(key, None) - if instance is None: - instance = cls.__instances.setdefault(key, - cls.instance(name, offset)) - - # This lock may not be necessary in Python 3. See GH issue #901 - with cls._cache_lock: - cls.__strong_cache[key] = cls.__strong_cache.pop(key, instance) - - # Remove an item if the strong cache is overpopulated - if len(cls.__strong_cache) > cls.__strong_cache_size: - cls.__strong_cache.popitem(last=False) - - return instance - - -class _TzStrFactory(_TzFactory): - def __init__(cls, *args, **kwargs): - cls.__instances = weakref.WeakValueDictionary() - cls.__strong_cache = OrderedDict() - cls.__strong_cache_size = 8 - - cls.__cache_lock = _thread.allocate_lock() - - def __call__(cls, s, posix_offset=False): - key = (s, posix_offset) - instance = cls.__instances.get(key, None) - - if instance is None: - instance = cls.__instances.setdefault(key, - cls.instance(s, posix_offset)) - - # This lock may not be necessary in Python 3. See GH issue #901 - with cls.__cache_lock: - cls.__strong_cache[key] = cls.__strong_cache.pop(key, instance) - - # Remove an item if the strong cache is overpopulated - if len(cls.__strong_cache) > cls.__strong_cache_size: - cls.__strong_cache.popitem(last=False) - - return instance - diff --git a/.venv/Lib/site-packages/dateutil/tz/tz.py b/.venv/Lib/site-packages/dateutil/tz/tz.py deleted file mode 100644 index c67f56d..0000000 --- a/.venv/Lib/site-packages/dateutil/tz/tz.py +++ /dev/null @@ -1,1849 +0,0 @@ -# -*- coding: utf-8 -*- -""" -This module offers timezone implementations subclassing the abstract -:py:class:`datetime.tzinfo` type. There are classes to handle tzfile format -files (usually are in :file:`/etc/localtime`, :file:`/usr/share/zoneinfo`, -etc), TZ environment string (in all known formats), given ranges (with help -from relative deltas), local machine timezone, fixed offset timezone, and UTC -timezone. -""" -import datetime -import struct -import time -import sys -import os -import bisect -import weakref -from collections import OrderedDict - -import six -from six import string_types -from six.moves import _thread -from ._common import tzname_in_python2, _tzinfo -from ._common import tzrangebase, enfold -from ._common import _validate_fromutc_inputs - -from ._factories import _TzSingleton, _TzOffsetFactory -from ._factories import _TzStrFactory -try: - from .win import tzwin, tzwinlocal -except ImportError: - tzwin = tzwinlocal = None - -# For warning about rounding tzinfo -from warnings import warn - -ZERO = datetime.timedelta(0) -EPOCH = datetime.datetime.utcfromtimestamp(0) -EPOCHORDINAL = EPOCH.toordinal() - - -@six.add_metaclass(_TzSingleton) -class tzutc(datetime.tzinfo): - """ - This is a tzinfo object that represents the UTC time zone. - - **Examples:** - - .. doctest:: - - >>> from datetime import * - >>> from dateutil.tz import * - - >>> datetime.now() - datetime.datetime(2003, 9, 27, 9, 40, 1, 521290) - - >>> datetime.now(tzutc()) - datetime.datetime(2003, 9, 27, 12, 40, 12, 156379, tzinfo=tzutc()) - - >>> datetime.now(tzutc()).tzname() - 'UTC' - - .. versionchanged:: 2.7.0 - ``tzutc()`` is now a singleton, so the result of ``tzutc()`` will - always return the same object. - - .. doctest:: - - >>> from dateutil.tz import tzutc, UTC - >>> tzutc() is tzutc() - True - >>> tzutc() is UTC - True - """ - def utcoffset(self, dt): - return ZERO - - def dst(self, dt): - return ZERO - - @tzname_in_python2 - def tzname(self, dt): - return "UTC" - - def is_ambiguous(self, dt): - """ - Whether or not the "wall time" of a given datetime is ambiguous in this - zone. - - :param dt: - A :py:class:`datetime.datetime`, naive or time zone aware. - - - :return: - Returns ``True`` if ambiguous, ``False`` otherwise. - - .. versionadded:: 2.6.0 - """ - return False - - @_validate_fromutc_inputs - def fromutc(self, dt): - """ - Fast track version of fromutc() returns the original ``dt`` object for - any valid :py:class:`datetime.datetime` object. - """ - return dt - - def __eq__(self, other): - if not isinstance(other, (tzutc, tzoffset)): - return NotImplemented - - return (isinstance(other, tzutc) or - (isinstance(other, tzoffset) and other._offset == ZERO)) - - __hash__ = None - - def __ne__(self, other): - return not (self == other) - - def __repr__(self): - return "%s()" % self.__class__.__name__ - - __reduce__ = object.__reduce__ - - -#: Convenience constant providing a :class:`tzutc()` instance -#: -#: .. versionadded:: 2.7.0 -UTC = tzutc() - - -@six.add_metaclass(_TzOffsetFactory) -class tzoffset(datetime.tzinfo): - """ - A simple class for representing a fixed offset from UTC. - - :param name: - The timezone name, to be returned when ``tzname()`` is called. - :param offset: - The time zone offset in seconds, or (since version 2.6.0, represented - as a :py:class:`datetime.timedelta` object). - """ - def __init__(self, name, offset): - self._name = name - - try: - # Allow a timedelta - offset = offset.total_seconds() - except (TypeError, AttributeError): - pass - - self._offset = datetime.timedelta(seconds=_get_supported_offset(offset)) - - def utcoffset(self, dt): - return self._offset - - def dst(self, dt): - return ZERO - - @tzname_in_python2 - def tzname(self, dt): - return self._name - - @_validate_fromutc_inputs - def fromutc(self, dt): - return dt + self._offset - - def is_ambiguous(self, dt): - """ - Whether or not the "wall time" of a given datetime is ambiguous in this - zone. - - :param dt: - A :py:class:`datetime.datetime`, naive or time zone aware. - :return: - Returns ``True`` if ambiguous, ``False`` otherwise. - - .. versionadded:: 2.6.0 - """ - return False - - def __eq__(self, other): - if not isinstance(other, tzoffset): - return NotImplemented - - return self._offset == other._offset - - __hash__ = None - - def __ne__(self, other): - return not (self == other) - - def __repr__(self): - return "%s(%s, %s)" % (self.__class__.__name__, - repr(self._name), - int(self._offset.total_seconds())) - - __reduce__ = object.__reduce__ - - -class tzlocal(_tzinfo): - """ - A :class:`tzinfo` subclass built around the ``time`` timezone functions. - """ - def __init__(self): - super(tzlocal, self).__init__() - - self._std_offset = datetime.timedelta(seconds=-time.timezone) - if time.daylight: - self._dst_offset = datetime.timedelta(seconds=-time.altzone) - else: - self._dst_offset = self._std_offset - - self._dst_saved = self._dst_offset - self._std_offset - self._hasdst = bool(self._dst_saved) - self._tznames = tuple(time.tzname) - - def utcoffset(self, dt): - if dt is None and self._hasdst: - return None - - if self._isdst(dt): - return self._dst_offset - else: - return self._std_offset - - def dst(self, dt): - if dt is None and self._hasdst: - return None - - if self._isdst(dt): - return self._dst_offset - self._std_offset - else: - return ZERO - - @tzname_in_python2 - def tzname(self, dt): - return self._tznames[self._isdst(dt)] - - def is_ambiguous(self, dt): - """ - Whether or not the "wall time" of a given datetime is ambiguous in this - zone. - - :param dt: - A :py:class:`datetime.datetime`, naive or time zone aware. - - - :return: - Returns ``True`` if ambiguous, ``False`` otherwise. - - .. versionadded:: 2.6.0 - """ - naive_dst = self._naive_is_dst(dt) - return (not naive_dst and - (naive_dst != self._naive_is_dst(dt - self._dst_saved))) - - def _naive_is_dst(self, dt): - timestamp = _datetime_to_timestamp(dt) - return time.localtime(timestamp + time.timezone).tm_isdst - - def _isdst(self, dt, fold_naive=True): - # We can't use mktime here. It is unstable when deciding if - # the hour near to a change is DST or not. - # - # timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour, - # dt.minute, dt.second, dt.weekday(), 0, -1)) - # return time.localtime(timestamp).tm_isdst - # - # The code above yields the following result: - # - # >>> import tz, datetime - # >>> t = tz.tzlocal() - # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() - # 'BRDT' - # >>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname() - # 'BRST' - # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() - # 'BRST' - # >>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname() - # 'BRDT' - # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname() - # 'BRDT' - # - # Here is a more stable implementation: - # - if not self._hasdst: - return False - - # Check for ambiguous times: - dstval = self._naive_is_dst(dt) - fold = getattr(dt, 'fold', None) - - if self.is_ambiguous(dt): - if fold is not None: - return not self._fold(dt) - else: - return True - - return dstval - - def __eq__(self, other): - if isinstance(other, tzlocal): - return (self._std_offset == other._std_offset and - self._dst_offset == other._dst_offset) - elif isinstance(other, tzutc): - return (not self._hasdst and - self._tznames[0] in {'UTC', 'GMT'} and - self._std_offset == ZERO) - elif isinstance(other, tzoffset): - return (not self._hasdst and - self._tznames[0] == other._name and - self._std_offset == other._offset) - else: - return NotImplemented - - __hash__ = None - - def __ne__(self, other): - return not (self == other) - - def __repr__(self): - return "%s()" % self.__class__.__name__ - - __reduce__ = object.__reduce__ - - -class _ttinfo(object): - __slots__ = ["offset", "delta", "isdst", "abbr", - "isstd", "isgmt", "dstoffset"] - - def __init__(self): - for attr in self.__slots__: - setattr(self, attr, None) - - def __repr__(self): - l = [] - for attr in self.__slots__: - value = getattr(self, attr) - if value is not None: - l.append("%s=%s" % (attr, repr(value))) - return "%s(%s)" % (self.__class__.__name__, ", ".join(l)) - - def __eq__(self, other): - if not isinstance(other, _ttinfo): - return NotImplemented - - return (self.offset == other.offset and - self.delta == other.delta and - self.isdst == other.isdst and - self.abbr == other.abbr and - self.isstd == other.isstd and - self.isgmt == other.isgmt and - self.dstoffset == other.dstoffset) - - __hash__ = None - - def __ne__(self, other): - return not (self == other) - - def __getstate__(self): - state = {} - for name in self.__slots__: - state[name] = getattr(self, name, None) - return state - - def __setstate__(self, state): - for name in self.__slots__: - if name in state: - setattr(self, name, state[name]) - - -class _tzfile(object): - """ - Lightweight class for holding the relevant transition and time zone - information read from binary tzfiles. - """ - attrs = ['trans_list', 'trans_list_utc', 'trans_idx', 'ttinfo_list', - 'ttinfo_std', 'ttinfo_dst', 'ttinfo_before', 'ttinfo_first'] - - def __init__(self, **kwargs): - for attr in self.attrs: - setattr(self, attr, kwargs.get(attr, None)) - - -class tzfile(_tzinfo): - """ - This is a ``tzinfo`` subclass that allows one to use the ``tzfile(5)`` - format timezone files to extract current and historical zone information. - - :param fileobj: - This can be an opened file stream or a file name that the time zone - information can be read from. - - :param filename: - This is an optional parameter specifying the source of the time zone - information in the event that ``fileobj`` is a file object. If omitted - and ``fileobj`` is a file stream, this parameter will be set either to - ``fileobj``'s ``name`` attribute or to ``repr(fileobj)``. - - See `Sources for Time Zone and Daylight Saving Time Data - `_ for more information. - Time zone files can be compiled from the `IANA Time Zone database files - `_ with the `zic time zone compiler - `_ - - .. note:: - - Only construct a ``tzfile`` directly if you have a specific timezone - file on disk that you want to read into a Python ``tzinfo`` object. - If you want to get a ``tzfile`` representing a specific IANA zone, - (e.g. ``'America/New_York'``), you should call - :func:`dateutil.tz.gettz` with the zone identifier. - - - **Examples:** - - Using the US Eastern time zone as an example, we can see that a ``tzfile`` - provides time zone information for the standard Daylight Saving offsets: - - .. testsetup:: tzfile - - from dateutil.tz import gettz - from datetime import datetime - - .. doctest:: tzfile - - >>> NYC = gettz('America/New_York') - >>> NYC - tzfile('/usr/share/zoneinfo/America/New_York') - - >>> print(datetime(2016, 1, 3, tzinfo=NYC)) # EST - 2016-01-03 00:00:00-05:00 - - >>> print(datetime(2016, 7, 7, tzinfo=NYC)) # EDT - 2016-07-07 00:00:00-04:00 - - - The ``tzfile`` structure contains a fully history of the time zone, - so historical dates will also have the right offsets. For example, before - the adoption of the UTC standards, New York used local solar mean time: - - .. doctest:: tzfile - - >>> print(datetime(1901, 4, 12, tzinfo=NYC)) # LMT - 1901-04-12 00:00:00-04:56 - - And during World War II, New York was on "Eastern War Time", which was a - state of permanent daylight saving time: - - .. doctest:: tzfile - - >>> print(datetime(1944, 2, 7, tzinfo=NYC)) # EWT - 1944-02-07 00:00:00-04:00 - - """ - - def __init__(self, fileobj, filename=None): - super(tzfile, self).__init__() - - file_opened_here = False - if isinstance(fileobj, string_types): - self._filename = fileobj - fileobj = open(fileobj, 'rb') - file_opened_here = True - elif filename is not None: - self._filename = filename - elif hasattr(fileobj, "name"): - self._filename = fileobj.name - else: - self._filename = repr(fileobj) - - if fileobj is not None: - if not file_opened_here: - fileobj = _nullcontext(fileobj) - - with fileobj as file_stream: - tzobj = self._read_tzfile(file_stream) - - self._set_tzdata(tzobj) - - def _set_tzdata(self, tzobj): - """ Set the time zone data of this object from a _tzfile object """ - # Copy the relevant attributes over as private attributes - for attr in _tzfile.attrs: - setattr(self, '_' + attr, getattr(tzobj, attr)) - - def _read_tzfile(self, fileobj): - out = _tzfile() - - # From tzfile(5): - # - # The time zone information files used by tzset(3) - # begin with the magic characters "TZif" to identify - # them as time zone information files, followed by - # sixteen bytes reserved for future use, followed by - # six four-byte values of type long, written in a - # ``standard'' byte order (the high-order byte - # of the value is written first). - if fileobj.read(4).decode() != "TZif": - raise ValueError("magic not found") - - fileobj.read(16) - - ( - # The number of UTC/local indicators stored in the file. - ttisgmtcnt, - - # The number of standard/wall indicators stored in the file. - ttisstdcnt, - - # The number of leap seconds for which data is - # stored in the file. - leapcnt, - - # The number of "transition times" for which data - # is stored in the file. - timecnt, - - # The number of "local time types" for which data - # is stored in the file (must not be zero). - typecnt, - - # The number of characters of "time zone - # abbreviation strings" stored in the file. - charcnt, - - ) = struct.unpack(">6l", fileobj.read(24)) - - # The above header is followed by tzh_timecnt four-byte - # values of type long, sorted in ascending order. - # These values are written in ``standard'' byte order. - # Each is used as a transition time (as returned by - # time(2)) at which the rules for computing local time - # change. - - if timecnt: - out.trans_list_utc = list(struct.unpack(">%dl" % timecnt, - fileobj.read(timecnt*4))) - else: - out.trans_list_utc = [] - - # Next come tzh_timecnt one-byte values of type unsigned - # char; each one tells which of the different types of - # ``local time'' types described in the file is associated - # with the same-indexed transition time. These values - # serve as indices into an array of ttinfo structures that - # appears next in the file. - - if timecnt: - out.trans_idx = struct.unpack(">%dB" % timecnt, - fileobj.read(timecnt)) - else: - out.trans_idx = [] - - # Each ttinfo structure is written as a four-byte value - # for tt_gmtoff of type long, in a standard byte - # order, followed by a one-byte value for tt_isdst - # and a one-byte value for tt_abbrind. In each - # structure, tt_gmtoff gives the number of - # seconds to be added to UTC, tt_isdst tells whether - # tm_isdst should be set by localtime(3), and - # tt_abbrind serves as an index into the array of - # time zone abbreviation characters that follow the - # ttinfo structure(s) in the file. - - ttinfo = [] - - for i in range(typecnt): - ttinfo.append(struct.unpack(">lbb", fileobj.read(6))) - - abbr = fileobj.read(charcnt).decode() - - # Then there are tzh_leapcnt pairs of four-byte - # values, written in standard byte order; the - # first value of each pair gives the time (as - # returned by time(2)) at which a leap second - # occurs; the second gives the total number of - # leap seconds to be applied after the given time. - # The pairs of values are sorted in ascending order - # by time. - - # Not used, for now (but seek for correct file position) - if leapcnt: - fileobj.seek(leapcnt * 8, os.SEEK_CUR) - - # Then there are tzh_ttisstdcnt standard/wall - # indicators, each stored as a one-byte value; - # they tell whether the transition times associated - # with local time types were specified as standard - # time or wall clock time, and are used when - # a time zone file is used in handling POSIX-style - # time zone environment variables. - - if ttisstdcnt: - isstd = struct.unpack(">%db" % ttisstdcnt, - fileobj.read(ttisstdcnt)) - - # Finally, there are tzh_ttisgmtcnt UTC/local - # indicators, each stored as a one-byte value; - # they tell whether the transition times associated - # with local time types were specified as UTC or - # local time, and are used when a time zone file - # is used in handling POSIX-style time zone envi- - # ronment variables. - - if ttisgmtcnt: - isgmt = struct.unpack(">%db" % ttisgmtcnt, - fileobj.read(ttisgmtcnt)) - - # Build ttinfo list - out.ttinfo_list = [] - for i in range(typecnt): - gmtoff, isdst, abbrind = ttinfo[i] - gmtoff = _get_supported_offset(gmtoff) - tti = _ttinfo() - tti.offset = gmtoff - tti.dstoffset = datetime.timedelta(0) - tti.delta = datetime.timedelta(seconds=gmtoff) - tti.isdst = isdst - tti.abbr = abbr[abbrind:abbr.find('\x00', abbrind)] - tti.isstd = (ttisstdcnt > i and isstd[i] != 0) - tti.isgmt = (ttisgmtcnt > i and isgmt[i] != 0) - out.ttinfo_list.append(tti) - - # Replace ttinfo indexes for ttinfo objects. - out.trans_idx = [out.ttinfo_list[idx] for idx in out.trans_idx] - - # Set standard, dst, and before ttinfos. before will be - # used when a given time is before any transitions, - # and will be set to the first non-dst ttinfo, or to - # the first dst, if all of them are dst. - out.ttinfo_std = None - out.ttinfo_dst = None - out.ttinfo_before = None - if out.ttinfo_list: - if not out.trans_list_utc: - out.ttinfo_std = out.ttinfo_first = out.ttinfo_list[0] - else: - for i in range(timecnt-1, -1, -1): - tti = out.trans_idx[i] - if not out.ttinfo_std and not tti.isdst: - out.ttinfo_std = tti - elif not out.ttinfo_dst and tti.isdst: - out.ttinfo_dst = tti - - if out.ttinfo_std and out.ttinfo_dst: - break - else: - if out.ttinfo_dst and not out.ttinfo_std: - out.ttinfo_std = out.ttinfo_dst - - for tti in out.ttinfo_list: - if not tti.isdst: - out.ttinfo_before = tti - break - else: - out.ttinfo_before = out.ttinfo_list[0] - - # Now fix transition times to become relative to wall time. - # - # I'm not sure about this. In my tests, the tz source file - # is setup to wall time, and in the binary file isstd and - # isgmt are off, so it should be in wall time. OTOH, it's - # always in gmt time. Let me know if you have comments - # about this. - lastdst = None - lastoffset = None - lastdstoffset = None - lastbaseoffset = None - out.trans_list = [] - - for i, tti in enumerate(out.trans_idx): - offset = tti.offset - dstoffset = 0 - - if lastdst is not None: - if tti.isdst: - if not lastdst: - dstoffset = offset - lastoffset - - if not dstoffset and lastdstoffset: - dstoffset = lastdstoffset - - tti.dstoffset = datetime.timedelta(seconds=dstoffset) - lastdstoffset = dstoffset - - # If a time zone changes its base offset during a DST transition, - # then you need to adjust by the previous base offset to get the - # transition time in local time. Otherwise you use the current - # base offset. Ideally, I would have some mathematical proof of - # why this is true, but I haven't really thought about it enough. - baseoffset = offset - dstoffset - adjustment = baseoffset - if (lastbaseoffset is not None and baseoffset != lastbaseoffset - and tti.isdst != lastdst): - # The base DST has changed - adjustment = lastbaseoffset - - lastdst = tti.isdst - lastoffset = offset - lastbaseoffset = baseoffset - - out.trans_list.append(out.trans_list_utc[i] + adjustment) - - out.trans_idx = tuple(out.trans_idx) - out.trans_list = tuple(out.trans_list) - out.trans_list_utc = tuple(out.trans_list_utc) - - return out - - def _find_last_transition(self, dt, in_utc=False): - # If there's no list, there are no transitions to find - if not self._trans_list: - return None - - timestamp = _datetime_to_timestamp(dt) - - # Find where the timestamp fits in the transition list - if the - # timestamp is a transition time, it's part of the "after" period. - trans_list = self._trans_list_utc if in_utc else self._trans_list - idx = bisect.bisect_right(trans_list, timestamp) - - # We want to know when the previous transition was, so subtract off 1 - return idx - 1 - - def _get_ttinfo(self, idx): - # For no list or after the last transition, default to _ttinfo_std - if idx is None or (idx + 1) >= len(self._trans_list): - return self._ttinfo_std - - # If there is a list and the time is before it, return _ttinfo_before - if idx < 0: - return self._ttinfo_before - - return self._trans_idx[idx] - - def _find_ttinfo(self, dt): - idx = self._resolve_ambiguous_time(dt) - - return self._get_ttinfo(idx) - - def fromutc(self, dt): - """ - The ``tzfile`` implementation of :py:func:`datetime.tzinfo.fromutc`. - - :param dt: - A :py:class:`datetime.datetime` object. - - :raises TypeError: - Raised if ``dt`` is not a :py:class:`datetime.datetime` object. - - :raises ValueError: - Raised if this is called with a ``dt`` which does not have this - ``tzinfo`` attached. - - :return: - Returns a :py:class:`datetime.datetime` object representing the - wall time in ``self``'s time zone. - """ - # These isinstance checks are in datetime.tzinfo, so we'll preserve - # them, even if we don't care about duck typing. - if not isinstance(dt, datetime.datetime): - raise TypeError("fromutc() requires a datetime argument") - - if dt.tzinfo is not self: - raise ValueError("dt.tzinfo is not self") - - # First treat UTC as wall time and get the transition we're in. - idx = self._find_last_transition(dt, in_utc=True) - tti = self._get_ttinfo(idx) - - dt_out = dt + datetime.timedelta(seconds=tti.offset) - - fold = self.is_ambiguous(dt_out, idx=idx) - - return enfold(dt_out, fold=int(fold)) - - def is_ambiguous(self, dt, idx=None): - """ - Whether or not the "wall time" of a given datetime is ambiguous in this - zone. - - :param dt: - A :py:class:`datetime.datetime`, naive or time zone aware. - - - :return: - Returns ``True`` if ambiguous, ``False`` otherwise. - - .. versionadded:: 2.6.0 - """ - if idx is None: - idx = self._find_last_transition(dt) - - # Calculate the difference in offsets from current to previous - timestamp = _datetime_to_timestamp(dt) - tti = self._get_ttinfo(idx) - - if idx is None or idx <= 0: - return False - - od = self._get_ttinfo(idx - 1).offset - tti.offset - tt = self._trans_list[idx] # Transition time - - return timestamp < tt + od - - def _resolve_ambiguous_time(self, dt): - idx = self._find_last_transition(dt) - - # If we have no transitions, return the index - _fold = self._fold(dt) - if idx is None or idx == 0: - return idx - - # If it's ambiguous and we're in a fold, shift to a different index. - idx_offset = int(not _fold and self.is_ambiguous(dt, idx)) - - return idx - idx_offset - - def utcoffset(self, dt): - if dt is None: - return None - - if not self._ttinfo_std: - return ZERO - - return self._find_ttinfo(dt).delta - - def dst(self, dt): - if dt is None: - return None - - if not self._ttinfo_dst: - return ZERO - - tti = self._find_ttinfo(dt) - - if not tti.isdst: - return ZERO - - # The documentation says that utcoffset()-dst() must - # be constant for every dt. - return tti.dstoffset - - @tzname_in_python2 - def tzname(self, dt): - if not self._ttinfo_std or dt is None: - return None - return self._find_ttinfo(dt).abbr - - def __eq__(self, other): - if not isinstance(other, tzfile): - return NotImplemented - return (self._trans_list == other._trans_list and - self._trans_idx == other._trans_idx and - self._ttinfo_list == other._ttinfo_list) - - __hash__ = None - - def __ne__(self, other): - return not (self == other) - - def __repr__(self): - return "%s(%s)" % (self.__class__.__name__, repr(self._filename)) - - def __reduce__(self): - return self.__reduce_ex__(None) - - def __reduce_ex__(self, protocol): - return (self.__class__, (None, self._filename), self.__dict__) - - -class tzrange(tzrangebase): - """ - The ``tzrange`` object is a time zone specified by a set of offsets and - abbreviations, equivalent to the way the ``TZ`` variable can be specified - in POSIX-like systems, but using Python delta objects to specify DST - start, end and offsets. - - :param stdabbr: - The abbreviation for standard time (e.g. ``'EST'``). - - :param stdoffset: - An integer or :class:`datetime.timedelta` object or equivalent - specifying the base offset from UTC. - - If unspecified, +00:00 is used. - - :param dstabbr: - The abbreviation for DST / "Summer" time (e.g. ``'EDT'``). - - If specified, with no other DST information, DST is assumed to occur - and the default behavior or ``dstoffset``, ``start`` and ``end`` is - used. If unspecified and no other DST information is specified, it - is assumed that this zone has no DST. - - If this is unspecified and other DST information is *is* specified, - DST occurs in the zone but the time zone abbreviation is left - unchanged. - - :param dstoffset: - A an integer or :class:`datetime.timedelta` object or equivalent - specifying the UTC offset during DST. If unspecified and any other DST - information is specified, it is assumed to be the STD offset +1 hour. - - :param start: - A :class:`relativedelta.relativedelta` object or equivalent specifying - the time and time of year that daylight savings time starts. To - specify, for example, that DST starts at 2AM on the 2nd Sunday in - March, pass: - - ``relativedelta(hours=2, month=3, day=1, weekday=SU(+2))`` - - If unspecified and any other DST information is specified, the default - value is 2 AM on the first Sunday in April. - - :param end: - A :class:`relativedelta.relativedelta` object or equivalent - representing the time and time of year that daylight savings time - ends, with the same specification method as in ``start``. One note is - that this should point to the first time in the *standard* zone, so if - a transition occurs at 2AM in the DST zone and the clocks are set back - 1 hour to 1AM, set the ``hours`` parameter to +1. - - - **Examples:** - - .. testsetup:: tzrange - - from dateutil.tz import tzrange, tzstr - - .. doctest:: tzrange - - >>> tzstr('EST5EDT') == tzrange("EST", -18000, "EDT") - True - - >>> from dateutil.relativedelta import * - >>> range1 = tzrange("EST", -18000, "EDT") - >>> range2 = tzrange("EST", -18000, "EDT", -14400, - ... relativedelta(hours=+2, month=4, day=1, - ... weekday=SU(+1)), - ... relativedelta(hours=+1, month=10, day=31, - ... weekday=SU(-1))) - >>> tzstr('EST5EDT') == range1 == range2 - True - - """ - def __init__(self, stdabbr, stdoffset=None, - dstabbr=None, dstoffset=None, - start=None, end=None): - - global relativedelta - from dateutil import relativedelta - - self._std_abbr = stdabbr - self._dst_abbr = dstabbr - - try: - stdoffset = stdoffset.total_seconds() - except (TypeError, AttributeError): - pass - - try: - dstoffset = dstoffset.total_seconds() - except (TypeError, AttributeError): - pass - - if stdoffset is not None: - self._std_offset = datetime.timedelta(seconds=stdoffset) - else: - self._std_offset = ZERO - - if dstoffset is not None: - self._dst_offset = datetime.timedelta(seconds=dstoffset) - elif dstabbr and stdoffset is not None: - self._dst_offset = self._std_offset + datetime.timedelta(hours=+1) - else: - self._dst_offset = ZERO - - if dstabbr and start is None: - self._start_delta = relativedelta.relativedelta( - hours=+2, month=4, day=1, weekday=relativedelta.SU(+1)) - else: - self._start_delta = start - - if dstabbr and end is None: - self._end_delta = relativedelta.relativedelta( - hours=+1, month=10, day=31, weekday=relativedelta.SU(-1)) - else: - self._end_delta = end - - self._dst_base_offset_ = self._dst_offset - self._std_offset - self.hasdst = bool(self._start_delta) - - def transitions(self, year): - """ - For a given year, get the DST on and off transition times, expressed - always on the standard time side. For zones with no transitions, this - function returns ``None``. - - :param year: - The year whose transitions you would like to query. - - :return: - Returns a :class:`tuple` of :class:`datetime.datetime` objects, - ``(dston, dstoff)`` for zones with an annual DST transition, or - ``None`` for fixed offset zones. - """ - if not self.hasdst: - return None - - base_year = datetime.datetime(year, 1, 1) - - start = base_year + self._start_delta - end = base_year + self._end_delta - - return (start, end) - - def __eq__(self, other): - if not isinstance(other, tzrange): - return NotImplemented - - return (self._std_abbr == other._std_abbr and - self._dst_abbr == other._dst_abbr and - self._std_offset == other._std_offset and - self._dst_offset == other._dst_offset and - self._start_delta == other._start_delta and - self._end_delta == other._end_delta) - - @property - def _dst_base_offset(self): - return self._dst_base_offset_ - - -@six.add_metaclass(_TzStrFactory) -class tzstr(tzrange): - """ - ``tzstr`` objects are time zone objects specified by a time-zone string as - it would be passed to a ``TZ`` variable on POSIX-style systems (see - the `GNU C Library: TZ Variable`_ for more details). - - There is one notable exception, which is that POSIX-style time zones use an - inverted offset format, so normally ``GMT+3`` would be parsed as an offset - 3 hours *behind* GMT. The ``tzstr`` time zone object will parse this as an - offset 3 hours *ahead* of GMT. If you would like to maintain the POSIX - behavior, pass a ``True`` value to ``posix_offset``. - - The :class:`tzrange` object provides the same functionality, but is - specified using :class:`relativedelta.relativedelta` objects. rather than - strings. - - :param s: - A time zone string in ``TZ`` variable format. This can be a - :class:`bytes` (2.x: :class:`str`), :class:`str` (2.x: - :class:`unicode`) or a stream emitting unicode characters - (e.g. :class:`StringIO`). - - :param posix_offset: - Optional. If set to ``True``, interpret strings such as ``GMT+3`` or - ``UTC+3`` as being 3 hours *behind* UTC rather than ahead, per the - POSIX standard. - - .. caution:: - - Prior to version 2.7.0, this function also supported time zones - in the format: - - * ``EST5EDT,4,0,6,7200,10,0,26,7200,3600`` - * ``EST5EDT,4,1,0,7200,10,-1,0,7200,3600`` - - This format is non-standard and has been deprecated; this function - will raise a :class:`DeprecatedTZFormatWarning` until - support is removed in a future version. - - .. _`GNU C Library: TZ Variable`: - https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html - """ - def __init__(self, s, posix_offset=False): - global parser - from dateutil.parser import _parser as parser - - self._s = s - - res = parser._parsetz(s) - if res is None or res.any_unused_tokens: - raise ValueError("unknown string format") - - # Here we break the compatibility with the TZ variable handling. - # GMT-3 actually *means* the timezone -3. - if res.stdabbr in ("GMT", "UTC") and not posix_offset: - res.stdoffset *= -1 - - # We must initialize it first, since _delta() needs - # _std_offset and _dst_offset set. Use False in start/end - # to avoid building it two times. - tzrange.__init__(self, res.stdabbr, res.stdoffset, - res.dstabbr, res.dstoffset, - start=False, end=False) - - if not res.dstabbr: - self._start_delta = None - self._end_delta = None - else: - self._start_delta = self._delta(res.start) - if self._start_delta: - self._end_delta = self._delta(res.end, isend=1) - - self.hasdst = bool(self._start_delta) - - def _delta(self, x, isend=0): - from dateutil import relativedelta - kwargs = {} - if x.month is not None: - kwargs["month"] = x.month - if x.weekday is not None: - kwargs["weekday"] = relativedelta.weekday(x.weekday, x.week) - if x.week > 0: - kwargs["day"] = 1 - else: - kwargs["day"] = 31 - elif x.day: - kwargs["day"] = x.day - elif x.yday is not None: - kwargs["yearday"] = x.yday - elif x.jyday is not None: - kwargs["nlyearday"] = x.jyday - if not kwargs: - # Default is to start on first sunday of april, and end - # on last sunday of october. - if not isend: - kwargs["month"] = 4 - kwargs["day"] = 1 - kwargs["weekday"] = relativedelta.SU(+1) - else: - kwargs["month"] = 10 - kwargs["day"] = 31 - kwargs["weekday"] = relativedelta.SU(-1) - if x.time is not None: - kwargs["seconds"] = x.time - else: - # Default is 2AM. - kwargs["seconds"] = 7200 - if isend: - # Convert to standard time, to follow the documented way - # of working with the extra hour. See the documentation - # of the tzinfo class. - delta = self._dst_offset - self._std_offset - kwargs["seconds"] -= delta.seconds + delta.days * 86400 - return relativedelta.relativedelta(**kwargs) - - def __repr__(self): - return "%s(%s)" % (self.__class__.__name__, repr(self._s)) - - -class _tzicalvtzcomp(object): - def __init__(self, tzoffsetfrom, tzoffsetto, isdst, - tzname=None, rrule=None): - self.tzoffsetfrom = datetime.timedelta(seconds=tzoffsetfrom) - self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto) - self.tzoffsetdiff = self.tzoffsetto - self.tzoffsetfrom - self.isdst = isdst - self.tzname = tzname - self.rrule = rrule - - -class _tzicalvtz(_tzinfo): - def __init__(self, tzid, comps=[]): - super(_tzicalvtz, self).__init__() - - self._tzid = tzid - self._comps = comps - self._cachedate = [] - self._cachecomp = [] - self._cache_lock = _thread.allocate_lock() - - def _find_comp(self, dt): - if len(self._comps) == 1: - return self._comps[0] - - dt = dt.replace(tzinfo=None) - - try: - with self._cache_lock: - return self._cachecomp[self._cachedate.index( - (dt, self._fold(dt)))] - except ValueError: - pass - - lastcompdt = None - lastcomp = None - - for comp in self._comps: - compdt = self._find_compdt(comp, dt) - - if compdt and (not lastcompdt or lastcompdt < compdt): - lastcompdt = compdt - lastcomp = comp - - if not lastcomp: - # RFC says nothing about what to do when a given - # time is before the first onset date. We'll look for the - # first standard component, or the first component, if - # none is found. - for comp in self._comps: - if not comp.isdst: - lastcomp = comp - break - else: - lastcomp = comp[0] - - with self._cache_lock: - self._cachedate.insert(0, (dt, self._fold(dt))) - self._cachecomp.insert(0, lastcomp) - - if len(self._cachedate) > 10: - self._cachedate.pop() - self._cachecomp.pop() - - return lastcomp - - def _find_compdt(self, comp, dt): - if comp.tzoffsetdiff < ZERO and self._fold(dt): - dt -= comp.tzoffsetdiff - - compdt = comp.rrule.before(dt, inc=True) - - return compdt - - def utcoffset(self, dt): - if dt is None: - return None - - return self._find_comp(dt).tzoffsetto - - def dst(self, dt): - comp = self._find_comp(dt) - if comp.isdst: - return comp.tzoffsetdiff - else: - return ZERO - - @tzname_in_python2 - def tzname(self, dt): - return self._find_comp(dt).tzname - - def __repr__(self): - return "" % repr(self._tzid) - - __reduce__ = object.__reduce__ - - -class tzical(object): - """ - This object is designed to parse an iCalendar-style ``VTIMEZONE`` structure - as set out in `RFC 5545`_ Section 4.6.5 into one or more `tzinfo` objects. - - :param `fileobj`: - A file or stream in iCalendar format, which should be UTF-8 encoded - with CRLF endings. - - .. _`RFC 5545`: https://tools.ietf.org/html/rfc5545 - """ - def __init__(self, fileobj): - global rrule - from dateutil import rrule - - if isinstance(fileobj, string_types): - self._s = fileobj - # ical should be encoded in UTF-8 with CRLF - fileobj = open(fileobj, 'r') - else: - self._s = getattr(fileobj, 'name', repr(fileobj)) - fileobj = _nullcontext(fileobj) - - self._vtz = {} - - with fileobj as fobj: - self._parse_rfc(fobj.read()) - - def keys(self): - """ - Retrieves the available time zones as a list. - """ - return list(self._vtz.keys()) - - def get(self, tzid=None): - """ - Retrieve a :py:class:`datetime.tzinfo` object by its ``tzid``. - - :param tzid: - If there is exactly one time zone available, omitting ``tzid`` - or passing :py:const:`None` value returns it. Otherwise a valid - key (which can be retrieved from :func:`keys`) is required. - - :raises ValueError: - Raised if ``tzid`` is not specified but there are either more - or fewer than 1 zone defined. - - :returns: - Returns either a :py:class:`datetime.tzinfo` object representing - the relevant time zone or :py:const:`None` if the ``tzid`` was - not found. - """ - if tzid is None: - if len(self._vtz) == 0: - raise ValueError("no timezones defined") - elif len(self._vtz) > 1: - raise ValueError("more than one timezone available") - tzid = next(iter(self._vtz)) - - return self._vtz.get(tzid) - - def _parse_offset(self, s): - s = s.strip() - if not s: - raise ValueError("empty offset") - if s[0] in ('+', '-'): - signal = (-1, +1)[s[0] == '+'] - s = s[1:] - else: - signal = +1 - if len(s) == 4: - return (int(s[:2]) * 3600 + int(s[2:]) * 60) * signal - elif len(s) == 6: - return (int(s[:2]) * 3600 + int(s[2:4]) * 60 + int(s[4:])) * signal - else: - raise ValueError("invalid offset: " + s) - - def _parse_rfc(self, s): - lines = s.splitlines() - if not lines: - raise ValueError("empty string") - - # Unfold - i = 0 - while i < len(lines): - line = lines[i].rstrip() - if not line: - del lines[i] - elif i > 0 and line[0] == " ": - lines[i-1] += line[1:] - del lines[i] - else: - i += 1 - - tzid = None - comps = [] - invtz = False - comptype = None - for line in lines: - if not line: - continue - name, value = line.split(':', 1) - parms = name.split(';') - if not parms: - raise ValueError("empty property name") - name = parms[0].upper() - parms = parms[1:] - if invtz: - if name == "BEGIN": - if value in ("STANDARD", "DAYLIGHT"): - # Process component - pass - else: - raise ValueError("unknown component: "+value) - comptype = value - founddtstart = False - tzoffsetfrom = None - tzoffsetto = None - rrulelines = [] - tzname = None - elif name == "END": - if value == "VTIMEZONE": - if comptype: - raise ValueError("component not closed: "+comptype) - if not tzid: - raise ValueError("mandatory TZID not found") - if not comps: - raise ValueError( - "at least one component is needed") - # Process vtimezone - self._vtz[tzid] = _tzicalvtz(tzid, comps) - invtz = False - elif value == comptype: - if not founddtstart: - raise ValueError("mandatory DTSTART not found") - if tzoffsetfrom is None: - raise ValueError( - "mandatory TZOFFSETFROM not found") - if tzoffsetto is None: - raise ValueError( - "mandatory TZOFFSETFROM not found") - # Process component - rr = None - if rrulelines: - rr = rrule.rrulestr("\n".join(rrulelines), - compatible=True, - ignoretz=True, - cache=True) - comp = _tzicalvtzcomp(tzoffsetfrom, tzoffsetto, - (comptype == "DAYLIGHT"), - tzname, rr) - comps.append(comp) - comptype = None - else: - raise ValueError("invalid component end: "+value) - elif comptype: - if name == "DTSTART": - # DTSTART in VTIMEZONE takes a subset of valid RRULE - # values under RFC 5545. - for parm in parms: - if parm != 'VALUE=DATE-TIME': - msg = ('Unsupported DTSTART param in ' + - 'VTIMEZONE: ' + parm) - raise ValueError(msg) - rrulelines.append(line) - founddtstart = True - elif name in ("RRULE", "RDATE", "EXRULE", "EXDATE"): - rrulelines.append(line) - elif name == "TZOFFSETFROM": - if parms: - raise ValueError( - "unsupported %s parm: %s " % (name, parms[0])) - tzoffsetfrom = self._parse_offset(value) - elif name == "TZOFFSETTO": - if parms: - raise ValueError( - "unsupported TZOFFSETTO parm: "+parms[0]) - tzoffsetto = self._parse_offset(value) - elif name == "TZNAME": - if parms: - raise ValueError( - "unsupported TZNAME parm: "+parms[0]) - tzname = value - elif name == "COMMENT": - pass - else: - raise ValueError("unsupported property: "+name) - else: - if name == "TZID": - if parms: - raise ValueError( - "unsupported TZID parm: "+parms[0]) - tzid = value - elif name in ("TZURL", "LAST-MODIFIED", "COMMENT"): - pass - else: - raise ValueError("unsupported property: "+name) - elif name == "BEGIN" and value == "VTIMEZONE": - tzid = None - comps = [] - invtz = True - - def __repr__(self): - return "%s(%s)" % (self.__class__.__name__, repr(self._s)) - - -if sys.platform != "win32": - TZFILES = ["/etc/localtime", "localtime"] - TZPATHS = ["/usr/share/zoneinfo", - "/usr/lib/zoneinfo", - "/usr/share/lib/zoneinfo", - "/etc/zoneinfo"] -else: - TZFILES = [] - TZPATHS = [] - - -def __get_gettz(): - tzlocal_classes = (tzlocal,) - if tzwinlocal is not None: - tzlocal_classes += (tzwinlocal,) - - class GettzFunc(object): - """ - Retrieve a time zone object from a string representation - - This function is intended to retrieve the :py:class:`tzinfo` subclass - that best represents the time zone that would be used if a POSIX - `TZ variable`_ were set to the same value. - - If no argument or an empty string is passed to ``gettz``, local time - is returned: - - .. code-block:: python3 - - >>> gettz() - tzfile('/etc/localtime') - - This function is also the preferred way to map IANA tz database keys - to :class:`tzfile` objects: - - .. code-block:: python3 - - >>> gettz('Pacific/Kiritimati') - tzfile('/usr/share/zoneinfo/Pacific/Kiritimati') - - On Windows, the standard is extended to include the Windows-specific - zone names provided by the operating system: - - .. code-block:: python3 - - >>> gettz('Egypt Standard Time') - tzwin('Egypt Standard Time') - - Passing a GNU ``TZ`` style string time zone specification returns a - :class:`tzstr` object: - - .. code-block:: python3 - - >>> gettz('AEST-10AEDT-11,M10.1.0/2,M4.1.0/3') - tzstr('AEST-10AEDT-11,M10.1.0/2,M4.1.0/3') - - :param name: - A time zone name (IANA, or, on Windows, Windows keys), location of - a ``tzfile(5)`` zoneinfo file or ``TZ`` variable style time zone - specifier. An empty string, no argument or ``None`` is interpreted - as local time. - - :return: - Returns an instance of one of ``dateutil``'s :py:class:`tzinfo` - subclasses. - - .. versionchanged:: 2.7.0 - - After version 2.7.0, any two calls to ``gettz`` using the same - input strings will return the same object: - - .. code-block:: python3 - - >>> tz.gettz('America/Chicago') is tz.gettz('America/Chicago') - True - - In addition to improving performance, this ensures that - `"same zone" semantics`_ are used for datetimes in the same zone. - - - .. _`TZ variable`: - https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html - - .. _`"same zone" semantics`: - https://blog.ganssle.io/articles/2018/02/aware-datetime-arithmetic.html - """ - def __init__(self): - - self.__instances = weakref.WeakValueDictionary() - self.__strong_cache_size = 8 - self.__strong_cache = OrderedDict() - self._cache_lock = _thread.allocate_lock() - - def __call__(self, name=None): - with self._cache_lock: - rv = self.__instances.get(name, None) - - if rv is None: - rv = self.nocache(name=name) - if not (name is None - or isinstance(rv, tzlocal_classes) - or rv is None): - # tzlocal is slightly more complicated than the other - # time zone providers because it depends on environment - # at construction time, so don't cache that. - # - # We also cannot store weak references to None, so we - # will also not store that. - self.__instances[name] = rv - else: - # No need for strong caching, return immediately - return rv - - self.__strong_cache[name] = self.__strong_cache.pop(name, rv) - - if len(self.__strong_cache) > self.__strong_cache_size: - self.__strong_cache.popitem(last=False) - - return rv - - def set_cache_size(self, size): - with self._cache_lock: - self.__strong_cache_size = size - while len(self.__strong_cache) > size: - self.__strong_cache.popitem(last=False) - - def cache_clear(self): - with self._cache_lock: - self.__instances = weakref.WeakValueDictionary() - self.__strong_cache.clear() - - @staticmethod - def nocache(name=None): - """A non-cached version of gettz""" - tz = None - if not name: - try: - name = os.environ["TZ"] - except KeyError: - pass - if name is None or name in ("", ":"): - for filepath in TZFILES: - if not os.path.isabs(filepath): - filename = filepath - for path in TZPATHS: - filepath = os.path.join(path, filename) - if os.path.isfile(filepath): - break - else: - continue - if os.path.isfile(filepath): - try: - tz = tzfile(filepath) - break - except (IOError, OSError, ValueError): - pass - else: - tz = tzlocal() - else: - try: - if name.startswith(":"): - name = name[1:] - except TypeError as e: - if isinstance(name, bytes): - new_msg = "gettz argument should be str, not bytes" - six.raise_from(TypeError(new_msg), e) - else: - raise - if os.path.isabs(name): - if os.path.isfile(name): - tz = tzfile(name) - else: - tz = None - else: - for path in TZPATHS: - filepath = os.path.join(path, name) - if not os.path.isfile(filepath): - filepath = filepath.replace(' ', '_') - if not os.path.isfile(filepath): - continue - try: - tz = tzfile(filepath) - break - except (IOError, OSError, ValueError): - pass - else: - tz = None - if tzwin is not None: - try: - tz = tzwin(name) - except (WindowsError, UnicodeEncodeError): - # UnicodeEncodeError is for Python 2.7 compat - tz = None - - if not tz: - from dateutil.zoneinfo import get_zonefile_instance - tz = get_zonefile_instance().get(name) - - if not tz: - for c in name: - # name is not a tzstr unless it has at least - # one offset. For short values of "name", an - # explicit for loop seems to be the fastest way - # To determine if a string contains a digit - if c in "0123456789": - try: - tz = tzstr(name) - except ValueError: - pass - break - else: - if name in ("GMT", "UTC"): - tz = UTC - elif name in time.tzname: - tz = tzlocal() - return tz - - return GettzFunc() - - -gettz = __get_gettz() -del __get_gettz - - -def datetime_exists(dt, tz=None): - """ - Given a datetime and a time zone, determine whether or not a given datetime - would fall in a gap. - - :param dt: - A :class:`datetime.datetime` (whose time zone will be ignored if ``tz`` - is provided.) - - :param tz: - A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If - ``None`` or not provided, the datetime's own time zone will be used. - - :return: - Returns a boolean value whether or not the "wall time" exists in - ``tz``. - - .. versionadded:: 2.7.0 - """ - if tz is None: - if dt.tzinfo is None: - raise ValueError('Datetime is naive and no time zone provided.') - tz = dt.tzinfo - - dt = dt.replace(tzinfo=None) - - # This is essentially a test of whether or not the datetime can survive - # a round trip to UTC. - dt_rt = dt.replace(tzinfo=tz).astimezone(UTC).astimezone(tz) - dt_rt = dt_rt.replace(tzinfo=None) - - return dt == dt_rt - - -def datetime_ambiguous(dt, tz=None): - """ - Given a datetime and a time zone, determine whether or not a given datetime - is ambiguous (i.e if there are two times differentiated only by their DST - status). - - :param dt: - A :class:`datetime.datetime` (whose time zone will be ignored if ``tz`` - is provided.) - - :param tz: - A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If - ``None`` or not provided, the datetime's own time zone will be used. - - :return: - Returns a boolean value whether or not the "wall time" is ambiguous in - ``tz``. - - .. versionadded:: 2.6.0 - """ - if tz is None: - if dt.tzinfo is None: - raise ValueError('Datetime is naive and no time zone provided.') - - tz = dt.tzinfo - - # If a time zone defines its own "is_ambiguous" function, we'll use that. - is_ambiguous_fn = getattr(tz, 'is_ambiguous', None) - if is_ambiguous_fn is not None: - try: - return tz.is_ambiguous(dt) - except Exception: - pass - - # If it doesn't come out and tell us it's ambiguous, we'll just check if - # the fold attribute has any effect on this particular date and time. - dt = dt.replace(tzinfo=tz) - wall_0 = enfold(dt, fold=0) - wall_1 = enfold(dt, fold=1) - - same_offset = wall_0.utcoffset() == wall_1.utcoffset() - same_dst = wall_0.dst() == wall_1.dst() - - return not (same_offset and same_dst) - - -def resolve_imaginary(dt): - """ - Given a datetime that may be imaginary, return an existing datetime. - - This function assumes that an imaginary datetime represents what the - wall time would be in a zone had the offset transition not occurred, so - it will always fall forward by the transition's change in offset. - - .. doctest:: - - >>> from dateutil import tz - >>> from datetime import datetime - >>> NYC = tz.gettz('America/New_York') - >>> print(tz.resolve_imaginary(datetime(2017, 3, 12, 2, 30, tzinfo=NYC))) - 2017-03-12 03:30:00-04:00 - - >>> KIR = tz.gettz('Pacific/Kiritimati') - >>> print(tz.resolve_imaginary(datetime(1995, 1, 1, 12, 30, tzinfo=KIR))) - 1995-01-02 12:30:00+14:00 - - As a note, :func:`datetime.astimezone` is guaranteed to produce a valid, - existing datetime, so a round-trip to and from UTC is sufficient to get - an extant datetime, however, this generally "falls back" to an earlier time - rather than falling forward to the STD side (though no guarantees are made - about this behavior). - - :param dt: - A :class:`datetime.datetime` which may or may not exist. - - :return: - Returns an existing :class:`datetime.datetime`. If ``dt`` was not - imaginary, the datetime returned is guaranteed to be the same object - passed to the function. - - .. versionadded:: 2.7.0 - """ - if dt.tzinfo is not None and not datetime_exists(dt): - - curr_offset = (dt + datetime.timedelta(hours=24)).utcoffset() - old_offset = (dt - datetime.timedelta(hours=24)).utcoffset() - - dt += curr_offset - old_offset - - return dt - - -def _datetime_to_timestamp(dt): - """ - Convert a :class:`datetime.datetime` object to an epoch timestamp in - seconds since January 1, 1970, ignoring the time zone. - """ - return (dt.replace(tzinfo=None) - EPOCH).total_seconds() - - -if sys.version_info >= (3, 6): - def _get_supported_offset(second_offset): - return second_offset -else: - def _get_supported_offset(second_offset): - # For python pre-3.6, round to full-minutes if that's not the case. - # Python's datetime doesn't accept sub-minute timezones. Check - # http://python.org/sf/1447945 or https://bugs.python.org/issue5288 - # for some information. - old_offset = second_offset - calculated_offset = 60 * ((second_offset + 30) // 60) - return calculated_offset - - -try: - # Python 3.7 feature - from contextlib import nullcontext as _nullcontext -except ImportError: - class _nullcontext(object): - """ - Class for wrapping contexts so that they are passed through in a - with statement. - """ - def __init__(self, context): - self.context = context - - def __enter__(self): - return self.context - - def __exit__(*args, **kwargs): - pass - -# vim:ts=4:sw=4:et diff --git a/.venv/Lib/site-packages/dateutil/tz/win.py b/.venv/Lib/site-packages/dateutil/tz/win.py deleted file mode 100644 index cde07ba..0000000 --- a/.venv/Lib/site-packages/dateutil/tz/win.py +++ /dev/null @@ -1,370 +0,0 @@ -# -*- coding: utf-8 -*- -""" -This module provides an interface to the native time zone data on Windows, -including :py:class:`datetime.tzinfo` implementations. - -Attempting to import this module on a non-Windows platform will raise an -:py:obj:`ImportError`. -""" -# This code was originally contributed by Jeffrey Harris. -import datetime -import struct - -from six.moves import winreg -from six import text_type - -try: - import ctypes - from ctypes import wintypes -except ValueError: - # ValueError is raised on non-Windows systems for some horrible reason. - raise ImportError("Running tzwin on non-Windows system") - -from ._common import tzrangebase - -__all__ = ["tzwin", "tzwinlocal", "tzres"] - -ONEWEEK = datetime.timedelta(7) - -TZKEYNAMENT = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones" -TZKEYNAME9X = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Time Zones" -TZLOCALKEYNAME = r"SYSTEM\CurrentControlSet\Control\TimeZoneInformation" - - -def _settzkeyname(): - handle = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) - try: - winreg.OpenKey(handle, TZKEYNAMENT).Close() - TZKEYNAME = TZKEYNAMENT - except WindowsError: - TZKEYNAME = TZKEYNAME9X - handle.Close() - return TZKEYNAME - - -TZKEYNAME = _settzkeyname() - - -class tzres(object): - """ - Class for accessing ``tzres.dll``, which contains timezone name related - resources. - - .. versionadded:: 2.5.0 - """ - p_wchar = ctypes.POINTER(wintypes.WCHAR) # Pointer to a wide char - - def __init__(self, tzres_loc='tzres.dll'): - # Load the user32 DLL so we can load strings from tzres - user32 = ctypes.WinDLL('user32') - - # Specify the LoadStringW function - user32.LoadStringW.argtypes = (wintypes.HINSTANCE, - wintypes.UINT, - wintypes.LPWSTR, - ctypes.c_int) - - self.LoadStringW = user32.LoadStringW - self._tzres = ctypes.WinDLL(tzres_loc) - self.tzres_loc = tzres_loc - - def load_name(self, offset): - """ - Load a timezone name from a DLL offset (integer). - - >>> from dateutil.tzwin import tzres - >>> tzr = tzres() - >>> print(tzr.load_name(112)) - 'Eastern Standard Time' - - :param offset: - A positive integer value referring to a string from the tzres dll. - - .. note:: - - Offsets found in the registry are generally of the form - ``@tzres.dll,-114``. The offset in this case is 114, not -114. - - """ - resource = self.p_wchar() - lpBuffer = ctypes.cast(ctypes.byref(resource), wintypes.LPWSTR) - nchar = self.LoadStringW(self._tzres._handle, offset, lpBuffer, 0) - return resource[:nchar] - - def name_from_string(self, tzname_str): - """ - Parse strings as returned from the Windows registry into the time zone - name as defined in the registry. - - >>> from dateutil.tzwin import tzres - >>> tzr = tzres() - >>> print(tzr.name_from_string('@tzres.dll,-251')) - 'Dateline Daylight Time' - >>> print(tzr.name_from_string('Eastern Standard Time')) - 'Eastern Standard Time' - - :param tzname_str: - A timezone name string as returned from a Windows registry key. - - :return: - Returns the localized timezone string from tzres.dll if the string - is of the form `@tzres.dll,-offset`, else returns the input string. - """ - if not tzname_str.startswith('@'): - return tzname_str - - name_splt = tzname_str.split(',-') - try: - offset = int(name_splt[1]) - except: - raise ValueError("Malformed timezone string.") - - return self.load_name(offset) - - -class tzwinbase(tzrangebase): - """tzinfo class based on win32's timezones available in the registry.""" - def __init__(self): - raise NotImplementedError('tzwinbase is an abstract base class') - - def __eq__(self, other): - # Compare on all relevant dimensions, including name. - if not isinstance(other, tzwinbase): - return NotImplemented - - return (self._std_offset == other._std_offset and - self._dst_offset == other._dst_offset and - self._stddayofweek == other._stddayofweek and - self._dstdayofweek == other._dstdayofweek and - self._stdweeknumber == other._stdweeknumber and - self._dstweeknumber == other._dstweeknumber and - self._stdhour == other._stdhour and - self._dsthour == other._dsthour and - self._stdminute == other._stdminute and - self._dstminute == other._dstminute and - self._std_abbr == other._std_abbr and - self._dst_abbr == other._dst_abbr) - - @staticmethod - def list(): - """Return a list of all time zones known to the system.""" - with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle: - with winreg.OpenKey(handle, TZKEYNAME) as tzkey: - result = [winreg.EnumKey(tzkey, i) - for i in range(winreg.QueryInfoKey(tzkey)[0])] - return result - - def display(self): - """ - Return the display name of the time zone. - """ - return self._display - - def transitions(self, year): - """ - For a given year, get the DST on and off transition times, expressed - always on the standard time side. For zones with no transitions, this - function returns ``None``. - - :param year: - The year whose transitions you would like to query. - - :return: - Returns a :class:`tuple` of :class:`datetime.datetime` objects, - ``(dston, dstoff)`` for zones with an annual DST transition, or - ``None`` for fixed offset zones. - """ - - if not self.hasdst: - return None - - dston = picknthweekday(year, self._dstmonth, self._dstdayofweek, - self._dsthour, self._dstminute, - self._dstweeknumber) - - dstoff = picknthweekday(year, self._stdmonth, self._stddayofweek, - self._stdhour, self._stdminute, - self._stdweeknumber) - - # Ambiguous dates default to the STD side - dstoff -= self._dst_base_offset - - return dston, dstoff - - def _get_hasdst(self): - return self._dstmonth != 0 - - @property - def _dst_base_offset(self): - return self._dst_base_offset_ - - -class tzwin(tzwinbase): - """ - Time zone object created from the zone info in the Windows registry - - These are similar to :py:class:`dateutil.tz.tzrange` objects in that - the time zone data is provided in the format of a single offset rule - for either 0 or 2 time zone transitions per year. - - :param: name - The name of a Windows time zone key, e.g. "Eastern Standard Time". - The full list of keys can be retrieved with :func:`tzwin.list`. - """ - - def __init__(self, name): - self._name = name - - with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle: - tzkeyname = text_type("{kn}\\{name}").format(kn=TZKEYNAME, name=name) - with winreg.OpenKey(handle, tzkeyname) as tzkey: - keydict = valuestodict(tzkey) - - self._std_abbr = keydict["Std"] - self._dst_abbr = keydict["Dlt"] - - self._display = keydict["Display"] - - # See http://ww_winreg.jsiinc.com/SUBA/tip0300/rh0398.htm - tup = struct.unpack("=3l16h", keydict["TZI"]) - stdoffset = -tup[0]-tup[1] # Bias + StandardBias * -1 - dstoffset = stdoffset-tup[2] # + DaylightBias * -1 - self._std_offset = datetime.timedelta(minutes=stdoffset) - self._dst_offset = datetime.timedelta(minutes=dstoffset) - - # for the meaning see the win32 TIME_ZONE_INFORMATION structure docs - # http://msdn.microsoft.com/en-us/library/windows/desktop/ms725481(v=vs.85).aspx - (self._stdmonth, - self._stddayofweek, # Sunday = 0 - self._stdweeknumber, # Last = 5 - self._stdhour, - self._stdminute) = tup[4:9] - - (self._dstmonth, - self._dstdayofweek, # Sunday = 0 - self._dstweeknumber, # Last = 5 - self._dsthour, - self._dstminute) = tup[12:17] - - self._dst_base_offset_ = self._dst_offset - self._std_offset - self.hasdst = self._get_hasdst() - - def __repr__(self): - return "tzwin(%s)" % repr(self._name) - - def __reduce__(self): - return (self.__class__, (self._name,)) - - -class tzwinlocal(tzwinbase): - """ - Class representing the local time zone information in the Windows registry - - While :class:`dateutil.tz.tzlocal` makes system calls (via the :mod:`time` - module) to retrieve time zone information, ``tzwinlocal`` retrieves the - rules directly from the Windows registry and creates an object like - :class:`dateutil.tz.tzwin`. - - Because Windows does not have an equivalent of :func:`time.tzset`, on - Windows, :class:`dateutil.tz.tzlocal` instances will always reflect the - time zone settings *at the time that the process was started*, meaning - changes to the machine's time zone settings during the run of a program - on Windows will **not** be reflected by :class:`dateutil.tz.tzlocal`. - Because ``tzwinlocal`` reads the registry directly, it is unaffected by - this issue. - """ - def __init__(self): - with winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE) as handle: - with winreg.OpenKey(handle, TZLOCALKEYNAME) as tzlocalkey: - keydict = valuestodict(tzlocalkey) - - self._std_abbr = keydict["StandardName"] - self._dst_abbr = keydict["DaylightName"] - - try: - tzkeyname = text_type('{kn}\\{sn}').format(kn=TZKEYNAME, - sn=self._std_abbr) - with winreg.OpenKey(handle, tzkeyname) as tzkey: - _keydict = valuestodict(tzkey) - self._display = _keydict["Display"] - except OSError: - self._display = None - - stdoffset = -keydict["Bias"]-keydict["StandardBias"] - dstoffset = stdoffset-keydict["DaylightBias"] - - self._std_offset = datetime.timedelta(minutes=stdoffset) - self._dst_offset = datetime.timedelta(minutes=dstoffset) - - # For reasons unclear, in this particular key, the day of week has been - # moved to the END of the SYSTEMTIME structure. - tup = struct.unpack("=8h", keydict["StandardStart"]) - - (self._stdmonth, - self._stdweeknumber, # Last = 5 - self._stdhour, - self._stdminute) = tup[1:5] - - self._stddayofweek = tup[7] - - tup = struct.unpack("=8h", keydict["DaylightStart"]) - - (self._dstmonth, - self._dstweeknumber, # Last = 5 - self._dsthour, - self._dstminute) = tup[1:5] - - self._dstdayofweek = tup[7] - - self._dst_base_offset_ = self._dst_offset - self._std_offset - self.hasdst = self._get_hasdst() - - def __repr__(self): - return "tzwinlocal()" - - def __str__(self): - # str will return the standard name, not the daylight name. - return "tzwinlocal(%s)" % repr(self._std_abbr) - - def __reduce__(self): - return (self.__class__, ()) - - -def picknthweekday(year, month, dayofweek, hour, minute, whichweek): - """ dayofweek == 0 means Sunday, whichweek 5 means last instance """ - first = datetime.datetime(year, month, 1, hour, minute) - - # This will work if dayofweek is ISO weekday (1-7) or Microsoft-style (0-6), - # Because 7 % 7 = 0 - weekdayone = first.replace(day=((dayofweek - first.isoweekday()) % 7) + 1) - wd = weekdayone + ((whichweek - 1) * ONEWEEK) - if (wd.month != month): - wd -= ONEWEEK - - return wd - - -def valuestodict(key): - """Convert a registry key's values to a dictionary.""" - dout = {} - size = winreg.QueryInfoKey(key)[1] - tz_res = None - - for i in range(size): - key_name, value, dtype = winreg.EnumValue(key, i) - if dtype == winreg.REG_DWORD or dtype == winreg.REG_DWORD_LITTLE_ENDIAN: - # If it's a DWORD (32-bit integer), it's stored as unsigned - convert - # that to a proper signed integer - if value & (1 << 31): - value = value - (1 << 32) - elif dtype == winreg.REG_SZ: - # If it's a reference to the tzres DLL, load the actual string - if value.startswith('@tzres'): - tz_res = tz_res or tzres() - value = tz_res.name_from_string(value) - - value = value.rstrip('\x00') # Remove trailing nulls - - dout[key_name] = value - - return dout diff --git a/.venv/Lib/site-packages/dateutil/tzwin.py b/.venv/Lib/site-packages/dateutil/tzwin.py deleted file mode 100644 index cebc673..0000000 --- a/.venv/Lib/site-packages/dateutil/tzwin.py +++ /dev/null @@ -1,2 +0,0 @@ -# tzwin has moved to dateutil.tz.win -from .tz.win import * diff --git a/.venv/Lib/site-packages/dateutil/utils.py b/.venv/Lib/site-packages/dateutil/utils.py deleted file mode 100644 index dd2d245..0000000 --- a/.venv/Lib/site-packages/dateutil/utils.py +++ /dev/null @@ -1,71 +0,0 @@ -# -*- coding: utf-8 -*- -""" -This module offers general convenience and utility functions for dealing with -datetimes. - -.. versionadded:: 2.7.0 -""" -from __future__ import unicode_literals - -from datetime import datetime, time - - -def today(tzinfo=None): - """ - Returns a :py:class:`datetime` representing the current day at midnight - - :param tzinfo: - The time zone to attach (also used to determine the current day). - - :return: - A :py:class:`datetime.datetime` object representing the current day - at midnight. - """ - - dt = datetime.now(tzinfo) - return datetime.combine(dt.date(), time(0, tzinfo=tzinfo)) - - -def default_tzinfo(dt, tzinfo): - """ - Sets the ``tzinfo`` parameter on naive datetimes only - - This is useful for example when you are provided a datetime that may have - either an implicit or explicit time zone, such as when parsing a time zone - string. - - .. doctest:: - - >>> from dateutil.tz import tzoffset - >>> from dateutil.parser import parse - >>> from dateutil.utils import default_tzinfo - >>> dflt_tz = tzoffset("EST", -18000) - >>> print(default_tzinfo(parse('2014-01-01 12:30 UTC'), dflt_tz)) - 2014-01-01 12:30:00+00:00 - >>> print(default_tzinfo(parse('2014-01-01 12:30'), dflt_tz)) - 2014-01-01 12:30:00-05:00 - - :param dt: - The datetime on which to replace the time zone - - :param tzinfo: - The :py:class:`datetime.tzinfo` subclass instance to assign to - ``dt`` if (and only if) it is naive. - - :return: - Returns an aware :py:class:`datetime.datetime`. - """ - if dt.tzinfo is not None: - return dt - else: - return dt.replace(tzinfo=tzinfo) - - -def within_delta(dt1, dt2, delta): - """ - Useful for comparing two datetimes that may have a negligible difference - to be considered equal. - """ - delta = abs(delta) - difference = dt1 - dt2 - return -delta <= difference <= delta diff --git a/.venv/Lib/site-packages/dateutil/zoneinfo/__init__.py b/.venv/Lib/site-packages/dateutil/zoneinfo/__init__.py deleted file mode 100644 index 34f11ad..0000000 --- a/.venv/Lib/site-packages/dateutil/zoneinfo/__init__.py +++ /dev/null @@ -1,167 +0,0 @@ -# -*- coding: utf-8 -*- -import warnings -import json - -from tarfile import TarFile -from pkgutil import get_data -from io import BytesIO - -from dateutil.tz import tzfile as _tzfile - -__all__ = ["get_zonefile_instance", "gettz", "gettz_db_metadata"] - -ZONEFILENAME = "dateutil-zoneinfo.tar.gz" -METADATA_FN = 'METADATA' - - -class tzfile(_tzfile): - def __reduce__(self): - return (gettz, (self._filename,)) - - -def getzoneinfofile_stream(): - try: - return BytesIO(get_data(__name__, ZONEFILENAME)) - except IOError as e: # TODO switch to FileNotFoundError? - warnings.warn("I/O error({0}): {1}".format(e.errno, e.strerror)) - return None - - -class ZoneInfoFile(object): - def __init__(self, zonefile_stream=None): - if zonefile_stream is not None: - with TarFile.open(fileobj=zonefile_stream) as tf: - self.zones = {zf.name: tzfile(tf.extractfile(zf), filename=zf.name) - for zf in tf.getmembers() - if zf.isfile() and zf.name != METADATA_FN} - # deal with links: They'll point to their parent object. Less - # waste of memory - links = {zl.name: self.zones[zl.linkname] - for zl in tf.getmembers() if - zl.islnk() or zl.issym()} - self.zones.update(links) - try: - metadata_json = tf.extractfile(tf.getmember(METADATA_FN)) - metadata_str = metadata_json.read().decode('UTF-8') - self.metadata = json.loads(metadata_str) - except KeyError: - # no metadata in tar file - self.metadata = None - else: - self.zones = {} - self.metadata = None - - def get(self, name, default=None): - """ - Wrapper for :func:`ZoneInfoFile.zones.get`. This is a convenience method - for retrieving zones from the zone dictionary. - - :param name: - The name of the zone to retrieve. (Generally IANA zone names) - - :param default: - The value to return in the event of a missing key. - - .. versionadded:: 2.6.0 - - """ - return self.zones.get(name, default) - - -# The current API has gettz as a module function, although in fact it taps into -# a stateful class. So as a workaround for now, without changing the API, we -# will create a new "global" class instance the first time a user requests a -# timezone. Ugly, but adheres to the api. -# -# TODO: Remove after deprecation period. -_CLASS_ZONE_INSTANCE = [] - - -def get_zonefile_instance(new_instance=False): - """ - This is a convenience function which provides a :class:`ZoneInfoFile` - instance using the data provided by the ``dateutil`` package. By default, it - caches a single instance of the ZoneInfoFile object and returns that. - - :param new_instance: - If ``True``, a new instance of :class:`ZoneInfoFile` is instantiated and - used as the cached instance for the next call. Otherwise, new instances - are created only as necessary. - - :return: - Returns a :class:`ZoneInfoFile` object. - - .. versionadded:: 2.6 - """ - if new_instance: - zif = None - else: - zif = getattr(get_zonefile_instance, '_cached_instance', None) - - if zif is None: - zif = ZoneInfoFile(getzoneinfofile_stream()) - - get_zonefile_instance._cached_instance = zif - - return zif - - -def gettz(name): - """ - This retrieves a time zone from the local zoneinfo tarball that is packaged - with dateutil. - - :param name: - An IANA-style time zone name, as found in the zoneinfo file. - - :return: - Returns a :class:`dateutil.tz.tzfile` time zone object. - - .. warning:: - It is generally inadvisable to use this function, and it is only - provided for API compatibility with earlier versions. This is *not* - equivalent to ``dateutil.tz.gettz()``, which selects an appropriate - time zone based on the inputs, favoring system zoneinfo. This is ONLY - for accessing the dateutil-specific zoneinfo (which may be out of - date compared to the system zoneinfo). - - .. deprecated:: 2.6 - If you need to use a specific zoneinfofile over the system zoneinfo, - instantiate a :class:`dateutil.zoneinfo.ZoneInfoFile` object and call - :func:`dateutil.zoneinfo.ZoneInfoFile.get(name)` instead. - - Use :func:`get_zonefile_instance` to retrieve an instance of the - dateutil-provided zoneinfo. - """ - warnings.warn("zoneinfo.gettz() will be removed in future versions, " - "to use the dateutil-provided zoneinfo files, instantiate a " - "ZoneInfoFile object and use ZoneInfoFile.zones.get() " - "instead. See the documentation for details.", - DeprecationWarning) - - if len(_CLASS_ZONE_INSTANCE) == 0: - _CLASS_ZONE_INSTANCE.append(ZoneInfoFile(getzoneinfofile_stream())) - return _CLASS_ZONE_INSTANCE[0].zones.get(name) - - -def gettz_db_metadata(): - """ Get the zonefile metadata - - See `zonefile_metadata`_ - - :returns: - A dictionary with the database metadata - - .. deprecated:: 2.6 - See deprecation warning in :func:`zoneinfo.gettz`. To get metadata, - query the attribute ``zoneinfo.ZoneInfoFile.metadata``. - """ - warnings.warn("zoneinfo.gettz_db_metadata() will be removed in future " - "versions, to use the dateutil-provided zoneinfo files, " - "ZoneInfoFile object and query the 'metadata' attribute " - "instead. See the documentation for details.", - DeprecationWarning) - - if len(_CLASS_ZONE_INSTANCE) == 0: - _CLASS_ZONE_INSTANCE.append(ZoneInfoFile(getzoneinfofile_stream())) - return _CLASS_ZONE_INSTANCE[0].metadata diff --git a/.venv/Lib/site-packages/dateutil/zoneinfo/__pycache__/__init__.cpython-38.pyc b/.venv/Lib/site-packages/dateutil/zoneinfo/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index 0d92d5c..0000000 Binary files a/.venv/Lib/site-packages/dateutil/zoneinfo/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/dateutil/zoneinfo/__pycache__/rebuild.cpython-38.pyc b/.venv/Lib/site-packages/dateutil/zoneinfo/__pycache__/rebuild.cpython-38.pyc deleted file mode 100644 index dc9c6bc..0000000 Binary files a/.venv/Lib/site-packages/dateutil/zoneinfo/__pycache__/rebuild.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/dateutil/zoneinfo/dateutil-zoneinfo.tar.gz b/.venv/Lib/site-packages/dateutil/zoneinfo/dateutil-zoneinfo.tar.gz deleted file mode 100644 index 524c48e..0000000 Binary files a/.venv/Lib/site-packages/dateutil/zoneinfo/dateutil-zoneinfo.tar.gz and /dev/null differ diff --git a/.venv/Lib/site-packages/dateutil/zoneinfo/rebuild.py b/.venv/Lib/site-packages/dateutil/zoneinfo/rebuild.py deleted file mode 100644 index 684c658..0000000 --- a/.venv/Lib/site-packages/dateutil/zoneinfo/rebuild.py +++ /dev/null @@ -1,75 +0,0 @@ -import logging -import os -import tempfile -import shutil -import json -from subprocess import check_call, check_output -from tarfile import TarFile - -from dateutil.zoneinfo import METADATA_FN, ZONEFILENAME - - -def rebuild(filename, tag=None, format="gz", zonegroups=[], metadata=None): - """Rebuild the internal timezone info in dateutil/zoneinfo/zoneinfo*tar* - - filename is the timezone tarball from ``ftp.iana.org/tz``. - - """ - tmpdir = tempfile.mkdtemp() - zonedir = os.path.join(tmpdir, "zoneinfo") - moduledir = os.path.dirname(__file__) - try: - with TarFile.open(filename) as tf: - for name in zonegroups: - tf.extract(name, tmpdir) - filepaths = [os.path.join(tmpdir, n) for n in zonegroups] - - _run_zic(zonedir, filepaths) - - # write metadata file - with open(os.path.join(zonedir, METADATA_FN), 'w') as f: - json.dump(metadata, f, indent=4, sort_keys=True) - target = os.path.join(moduledir, ZONEFILENAME) - with TarFile.open(target, "w:%s" % format) as tf: - for entry in os.listdir(zonedir): - entrypath = os.path.join(zonedir, entry) - tf.add(entrypath, entry) - finally: - shutil.rmtree(tmpdir) - - -def _run_zic(zonedir, filepaths): - """Calls the ``zic`` compiler in a compatible way to get a "fat" binary. - - Recent versions of ``zic`` default to ``-b slim``, while older versions - don't even have the ``-b`` option (but default to "fat" binaries). The - current version of dateutil does not support Version 2+ TZif files, which - causes problems when used in conjunction with "slim" binaries, so this - function is used to ensure that we always get a "fat" binary. - """ - - try: - help_text = check_output(["zic", "--help"]) - except OSError as e: - _print_on_nosuchfile(e) - raise - - if b"-b " in help_text: - bloat_args = ["-b", "fat"] - else: - bloat_args = [] - - check_call(["zic"] + bloat_args + ["-d", zonedir] + filepaths) - - -def _print_on_nosuchfile(e): - """Print helpful troubleshooting message - - e is an exception raised by subprocess.check_call() - - """ - if e.errno == 2: - logging.error( - "Could not find zic. Perhaps you need to install " - "libc-bin or some other package that provides it, " - "or it's not in your PATH?") diff --git a/.venv/Lib/site-packages/discord-2.0.0.dist-info/INSTALLER b/.venv/Lib/site-packages/discord-2.0.0.dist-info/INSTALLER deleted file mode 100644 index a1b589e..0000000 --- a/.venv/Lib/site-packages/discord-2.0.0.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/.venv/Lib/site-packages/discord-2.0.0.dist-info/METADATA b/.venv/Lib/site-packages/discord-2.0.0.dist-info/METADATA deleted file mode 100644 index 4265415..0000000 --- a/.venv/Lib/site-packages/discord-2.0.0.dist-info/METADATA +++ /dev/null @@ -1,16 +0,0 @@ -Metadata-Version: 2.1 -Name: discord -Version: 2.0.0 -Summary: A mirror package for discord.py. Please install that instead. -Home-page: https://github.com/Rapptz/discord.py -Author: Rapptz -License: UNKNOWN -Platform: UNKNOWN -Description-Content-Type: text/markdown -Requires-Dist: discord.py (>=2.0.0) - -### This is a mirror package! - -It is recommended to install `discord.py` instead. - - diff --git a/.venv/Lib/site-packages/discord-2.0.0.dist-info/RECORD b/.venv/Lib/site-packages/discord-2.0.0.dist-info/RECORD deleted file mode 100644 index 378127f..0000000 --- a/.venv/Lib/site-packages/discord-2.0.0.dist-info/RECORD +++ /dev/null @@ -1,6 +0,0 @@ -discord-2.0.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -discord-2.0.0.dist-info/METADATA,sha256=CyOiXiFd1qwUt1pTOVoRgm_4EqwJk6yeRkTZ7oboB_w,381 -discord-2.0.0.dist-info/RECORD,, -discord-2.0.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -discord-2.0.0.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92 -discord-2.0.0.dist-info/top_level.txt,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 diff --git a/.venv/Lib/site-packages/discord-2.0.0.dist-info/REQUESTED b/.venv/Lib/site-packages/discord-2.0.0.dist-info/REQUESTED deleted file mode 100644 index e69de29..0000000 diff --git a/.venv/Lib/site-packages/discord-2.0.0.dist-info/WHEEL b/.venv/Lib/site-packages/discord-2.0.0.dist-info/WHEEL deleted file mode 100644 index becc9a6..0000000 --- a/.venv/Lib/site-packages/discord-2.0.0.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: bdist_wheel (0.37.1) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/.venv/Lib/site-packages/discord-2.0.0.dist-info/top_level.txt b/.venv/Lib/site-packages/discord-2.0.0.dist-info/top_level.txt deleted file mode 100644 index 8b13789..0000000 --- a/.venv/Lib/site-packages/discord-2.0.0.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/.venv/Lib/site-packages/discord.py-2.0.1.dist-info/INSTALLER b/.venv/Lib/site-packages/discord.py-2.0.1.dist-info/INSTALLER deleted file mode 100644 index a1b589e..0000000 --- a/.venv/Lib/site-packages/discord.py-2.0.1.dist-info/INSTALLER +++ /dev/null @@ -1 +0,0 @@ -pip diff --git a/.venv/Lib/site-packages/discord.py-2.0.1.dist-info/LICENSE b/.venv/Lib/site-packages/discord.py-2.0.1.dist-info/LICENSE deleted file mode 100644 index 700c21b..0000000 --- a/.venv/Lib/site-packages/discord.py-2.0.1.dist-info/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/.venv/Lib/site-packages/discord.py-2.0.1.dist-info/METADATA b/.venv/Lib/site-packages/discord.py-2.0.1.dist-info/METADATA deleted file mode 100644 index 3b096b2..0000000 --- a/.venv/Lib/site-packages/discord.py-2.0.1.dist-info/METADATA +++ /dev/null @@ -1,166 +0,0 @@ -Metadata-Version: 2.1 -Name: discord.py -Version: 2.0.1 -Summary: A Python wrapper for the Discord API -Home-page: https://github.com/Rapptz/discord.py -Author: Rapptz -License: MIT -Project-URL: Documentation, https://discordpy.readthedocs.io/en/latest/ -Project-URL: Issue tracker, https://github.com/Rapptz/discord.py/issues -Platform: UNKNOWN -Classifier: Development Status :: 5 - Production/Stable -Classifier: License :: OSI Approved :: MIT License -Classifier: Intended Audience :: Developers -Classifier: Natural Language :: English -Classifier: Operating System :: OS Independent -Classifier: Programming Language :: Python :: 3.8 -Classifier: Programming Language :: Python :: 3.9 -Classifier: Programming Language :: Python :: 3.10 -Classifier: Topic :: Internet -Classifier: Topic :: Software Development :: Libraries -Classifier: Topic :: Software Development :: Libraries :: Python Modules -Classifier: Topic :: Utilities -Classifier: Typing :: Typed -Requires-Python: >=3.8.0 -Description-Content-Type: text/x-rst -License-File: LICENSE -Requires-Dist: aiohttp (<4,>=3.7.4) -Provides-Extra: docs -Requires-Dist: sphinx (==4.4.0) ; extra == 'docs' -Requires-Dist: sphinxcontrib-trio (==1.1.2) ; extra == 'docs' -Requires-Dist: sphinxcontrib-websupport ; extra == 'docs' -Requires-Dist: typing-extensions (<5,>=4.3) ; extra == 'docs' -Provides-Extra: speed -Requires-Dist: orjson (>=3.5.4) ; extra == 'speed' -Requires-Dist: aiodns (>=1.1) ; extra == 'speed' -Requires-Dist: Brotli ; extra == 'speed' -Requires-Dist: cchardet (==2.1.7) ; (python_version < "3.10") and extra == 'speed' -Provides-Extra: test -Requires-Dist: coverage[toml] ; extra == 'test' -Requires-Dist: pytest ; extra == 'test' -Requires-Dist: pytest-asyncio ; extra == 'test' -Requires-Dist: pytest-cov ; extra == 'test' -Requires-Dist: pytest-mock ; extra == 'test' -Requires-Dist: typing-extensions (<5,>=4.3) ; extra == 'test' -Provides-Extra: voice -Requires-Dist: PyNaCl (<1.6,>=1.3.0) ; extra == 'voice' - -discord.py -========== - -.. image:: https://discord.com/api/guilds/336642139381301249/embed.png - :target: https://discord.gg/r3sSKJJ - :alt: Discord server invite -.. image:: https://img.shields.io/pypi/v/discord.py.svg - :target: https://pypi.python.org/pypi/discord.py - :alt: PyPI version info -.. image:: https://img.shields.io/pypi/pyversions/discord.py.svg - :target: https://pypi.python.org/pypi/discord.py - :alt: PyPI supported Python versions - -A modern, easy to use, feature-rich, and async ready API wrapper for Discord written in Python. - -Key Features -------------- - -- Modern Pythonic API using ``async`` and ``await``. -- Proper rate limit handling. -- Optimised in both speed and memory. - -Installing ----------- - -**Python 3.8 or higher is required** - -To install the library without full voice support, you can just run the following command: - -.. code:: sh - - # Linux/macOS - python3 -m pip install -U discord.py - - # Windows - py -3 -m pip install -U discord.py - -Otherwise to get voice support you should run the following command: - -.. code:: sh - - # Linux/macOS - python3 -m pip install -U "discord.py[voice]" - - # Windows - py -3 -m pip install -U discord.py[voice] - - -To install the development version, do the following: - -.. code:: sh - - $ git clone https://github.com/Rapptz/discord.py - $ cd discord.py - $ python3 -m pip install -U .[voice] - - -Optional Packages -~~~~~~~~~~~~~~~~~~ - -* `PyNaCl `__ (for voice support) - -Please note that when installing voice support on Linux, you must install the following packages via your favourite package manager (e.g. ``apt``, ``dnf``, etc) before running the above commands: - -* libffi-dev (or ``libffi-devel`` on some systems) -* python-dev (e.g. ``python3.8-dev`` for Python 3.8) - -Quick Example --------------- - -.. code:: py - - import discord - - class MyClient(discord.Client): - async def on_ready(self): - print('Logged on as', self.user) - - async def on_message(self, message): - # don't respond to ourselves - if message.author == self.user: - return - - if message.content == 'ping': - await message.channel.send('pong') - - intents = discord.Intents.default() - intents.message_content = True - client = MyClient(intents=intents) - client.run('token') - -Bot Example -~~~~~~~~~~~~~ - -.. code:: py - - import discord - from discord.ext import commands - - intents = discord.Intents.default() - intents.message_content = True - bot = commands.Bot(command_prefix='>', intents=intents) - - @bot.command() - async def ping(ctx): - await ctx.send('pong') - - bot.run('token') - -You can find more examples in the examples directory. - -Links ------- - -- `Documentation `_ -- `Official Discord Server `_ -- `Discord API `_ - - diff --git a/.venv/Lib/site-packages/discord.py-2.0.1.dist-info/RECORD b/.venv/Lib/site-packages/discord.py-2.0.1.dist-info/RECORD deleted file mode 100644 index f4b73d4..0000000 --- a/.venv/Lib/site-packages/discord.py-2.0.1.dist-info/RECORD +++ /dev/null @@ -1,239 +0,0 @@ -discord.py-2.0.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 -discord.py-2.0.1.dist-info/LICENSE,sha256=IRr8eHptwl13Oez9dujx-pRmN028VYOGiW2Yzf7lEn0,1081 -discord.py-2.0.1.dist-info/METADATA,sha256=lM-OaObD1h1WPSUkC_SbXzCMpANuXHRgDhUoNm8EwPo,4897 -discord.py-2.0.1.dist-info/RECORD,, -discord.py-2.0.1.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92 -discord.py-2.0.1.dist-info/top_level.txt,sha256=fJkrNbR-_8ubMBUcDEJBcfkpECrvSEmMrNKgvLlQFoM,8 -discord/__init__.py,sha256=EdW8LQxeIwXUMh_R5cDwj0qkC5KnRHMnfAT0U6PvP4s,1886 -discord/__main__.py,sha256=DEe4CqYJGe53oxJsZAQVXNRQUEUILXpo1r5iwp5wIW8,11051 -discord/__pycache__/__init__.cpython-38.pyc,, -discord/__pycache__/__main__.cpython-38.pyc,, -discord/__pycache__/abc.cpython-38.pyc,, -discord/__pycache__/activity.cpython-38.pyc,, -discord/__pycache__/appinfo.cpython-38.pyc,, -discord/__pycache__/asset.cpython-38.pyc,, -discord/__pycache__/audit_logs.cpython-38.pyc,, -discord/__pycache__/automod.cpython-38.pyc,, -discord/__pycache__/backoff.cpython-38.pyc,, -discord/__pycache__/channel.cpython-38.pyc,, -discord/__pycache__/client.cpython-38.pyc,, -discord/__pycache__/colour.cpython-38.pyc,, -discord/__pycache__/components.cpython-38.pyc,, -discord/__pycache__/context_managers.cpython-38.pyc,, -discord/__pycache__/embeds.cpython-38.pyc,, -discord/__pycache__/emoji.cpython-38.pyc,, -discord/__pycache__/enums.cpython-38.pyc,, -discord/__pycache__/errors.cpython-38.pyc,, -discord/__pycache__/file.cpython-38.pyc,, -discord/__pycache__/flags.cpython-38.pyc,, -discord/__pycache__/gateway.cpython-38.pyc,, -discord/__pycache__/guild.cpython-38.pyc,, -discord/__pycache__/http.cpython-38.pyc,, -discord/__pycache__/integrations.cpython-38.pyc,, -discord/__pycache__/interactions.cpython-38.pyc,, -discord/__pycache__/invite.cpython-38.pyc,, -discord/__pycache__/member.cpython-38.pyc,, -discord/__pycache__/mentions.cpython-38.pyc,, -discord/__pycache__/message.cpython-38.pyc,, -discord/__pycache__/mixins.cpython-38.pyc,, -discord/__pycache__/object.cpython-38.pyc,, -discord/__pycache__/oggparse.cpython-38.pyc,, -discord/__pycache__/opus.cpython-38.pyc,, -discord/__pycache__/partial_emoji.cpython-38.pyc,, -discord/__pycache__/permissions.cpython-38.pyc,, -discord/__pycache__/player.cpython-38.pyc,, -discord/__pycache__/raw_models.cpython-38.pyc,, -discord/__pycache__/reaction.cpython-38.pyc,, -discord/__pycache__/role.cpython-38.pyc,, -discord/__pycache__/scheduled_event.cpython-38.pyc,, -discord/__pycache__/shard.cpython-38.pyc,, -discord/__pycache__/stage_instance.cpython-38.pyc,, -discord/__pycache__/state.cpython-38.pyc,, -discord/__pycache__/sticker.cpython-38.pyc,, -discord/__pycache__/team.cpython-38.pyc,, -discord/__pycache__/template.cpython-38.pyc,, -discord/__pycache__/threads.cpython-38.pyc,, -discord/__pycache__/user.cpython-38.pyc,, -discord/__pycache__/utils.cpython-38.pyc,, -discord/__pycache__/voice_client.cpython-38.pyc,, -discord/__pycache__/welcome_screen.cpython-38.pyc,, -discord/__pycache__/widget.cpython-38.pyc,, -discord/abc.py,sha256=QuVHNg3fe0u7x0CEYnFfq095xuHvSyK68UNSUj0KbLI,64890 -discord/activity.py,sha256=cz9uCNNECyS0KKF3qfjEux5Hb6vu0fPk0Lya3EwZKSM,26864 -discord/app_commands/__init__.py,sha256=xaANFF28sifxXO__x6eSd7r5r7UjpO-tMQirjaKiNSc,424 -discord/app_commands/__pycache__/__init__.cpython-38.pyc,, -discord/app_commands/__pycache__/checks.cpython-38.pyc,, -discord/app_commands/__pycache__/commands.cpython-38.pyc,, -discord/app_commands/__pycache__/errors.cpython-38.pyc,, -discord/app_commands/__pycache__/models.cpython-38.pyc,, -discord/app_commands/__pycache__/namespace.cpython-38.pyc,, -discord/app_commands/__pycache__/transformers.cpython-38.pyc,, -discord/app_commands/__pycache__/translator.cpython-38.pyc,, -discord/app_commands/__pycache__/tree.cpython-38.pyc,, -discord/app_commands/checks.py,sha256=StiwzVre5UJFyxA8v6lPV6Ww9rOvkpAc6hmUlDWVlDs,18067 -discord/app_commands/commands.py,sha256=78trKnwbq14Oe0-ol7fRHh32S118Pg4QacWSxScBTJ4,95518 -discord/app_commands/errors.py,sha256=6Y9ZNwnQGlGo6v2zSt5_sbdpMRAFirjFTR6G2iBO4GA,18649 -discord/app_commands/models.py,sha256=fXKPuveZsXDZUSDouqx2e9-uU8wCHKdZPiCFgaaPuoU,38427 -discord/app_commands/namespace.py,sha256=cy8tjG_6EPD_XTR5tkEPN1UDwZz_lX76Etav3nyraEg,12929 -discord/app_commands/transformers.py,sha256=oHVFWLffQ6bbD2S0WKE3LbDB2vb7OQ4irsjiTQhqBjQ,32137 -discord/app_commands/translator.py,sha256=m9ENDO7GGCJXiSuhCCvXi1jW4ccHOBEM0Hk9qomS6I0,10686 -discord/app_commands/tree.py,sha256=LX4Zmf5sAc7HliE9g-uCFlgVFFD0qbbg4_PycbJ3ux4,47763 -discord/appinfo.py,sha256=lOeC9UKG5mJW0VGAoqH62Y4acVtEuOjIbws8xnJRLUs,10504 -discord/asset.py,sha256=SuZBQ9mgz092zUpXem2gco0WOOAOiW9pJpWpbfJtsUI,15837 -discord/audit_logs.py,sha256=-6EXQyH13GH43ZAie4gsfY7Ey9N_GBda0912IGm3Pio,30936 -discord/automod.py,sha256=1d_AlvA077OWDyimQvMHnApOg0pA562mu9Wmu77dV3M,21151 -discord/backoff.py,sha256=3yQ0uJbQ3ij7Tmdzv7GdhqfHjbNVO4eTB3Eu0VCxuvM,3751 -discord/bin/libopus-0.x64.dll,sha256=yE2oNujZJCGsMFhCz-WnJImO0J00DUaxKeIQvclEgTE,441856 -discord/bin/libopus-0.x86.dll,sha256=O1v-EpUPNQQ-110rb6kCyTbWelBxYL92NY1nx2wdveg,366080 -discord/channel.py,sha256=2LGmfbOMVlB1rrZvwfT7XEiG1EDvaeQaCnKDzVsGQok,98359 -discord/client.py,sha256=swA5TOBMPqWhlRLikiNOKKVtxSO10AOXXrEG_84Q6qU,66619 -discord/colour.py,sha256=SuXXAS3EfPFQC8-qDmrTD7l-__prZNUB2SkzZcB4gYM,12306 -discord/components.py,sha256=Hb93_kgw4nl02DWcqoZBn-sHKgq9iWzh0xJLkKZncDE,16416 -discord/context_managers.py,sha256=hloaEAAhLcDB-QfyoCPEpH_vsc3y4WLs1Ujs352tLbQ,3032 -discord/embeds.py,sha256=sijnFNm84KCoo_IUPUUC1bzX1IWyMfPcBPFXFocq50g,22722 -discord/emoji.py,sha256=Wov7TktazUyDVbnnUXw8o6x0c06uU_kWV_Ou5DKqmhA,8627 -discord/enums.py,sha256=gf8mCPvLG5fKvrClX_CqkvNFrV1zgYTCHia0Rg7n8sc,21355 -discord/errors.py,sha256=h0BHhp-UjoWTvoxqlLjtOziM9nxVFR8qMHZmEt8m5oc,8952 -discord/ext/commands/__init__.py,sha256=ZQPvApylgqC07qrj80DDkT4Dbd7j_OVy5Xw4RiYZJRc,437 -discord/ext/commands/__pycache__/__init__.cpython-38.pyc,, -discord/ext/commands/__pycache__/_types.cpython-38.pyc,, -discord/ext/commands/__pycache__/bot.cpython-38.pyc,, -discord/ext/commands/__pycache__/cog.cpython-38.pyc,, -discord/ext/commands/__pycache__/context.cpython-38.pyc,, -discord/ext/commands/__pycache__/converter.cpython-38.pyc,, -discord/ext/commands/__pycache__/cooldowns.cpython-38.pyc,, -discord/ext/commands/__pycache__/core.cpython-38.pyc,, -discord/ext/commands/__pycache__/errors.cpython-38.pyc,, -discord/ext/commands/__pycache__/flags.cpython-38.pyc,, -discord/ext/commands/__pycache__/help.cpython-38.pyc,, -discord/ext/commands/__pycache__/hybrid.cpython-38.pyc,, -discord/ext/commands/__pycache__/parameters.cpython-38.pyc,, -discord/ext/commands/__pycache__/view.cpython-38.pyc,, -discord/ext/commands/_types.py,sha256=ULLyGU6nLcITfnS-yTrlRU0N3e0zXETo2w8dBWKMrf4,2638 -discord/ext/commands/bot.py,sha256=e9d3ASPWxyP9iz5SA8szPC3mgbKtn2HgO6vZ1Nij78s,51674 -discord/ext/commands/cog.py,sha256=v0-Eqfe8E3sCpW6HUFbp_zOF6PqRLCV4BL9Z2EvR3MU,28650 -discord/ext/commands/context.py,sha256=9ILOPVb_GdTmZnTdUVGK2u7iyfgwONr0WLmUBJVazfE,34232 -discord/ext/commands/converter.py,sha256=cW87gMOfug7fee2qi-AXmdYQSpgJ1ok9hYYOni6lszQ,44592 -discord/ext/commands/cooldowns.py,sha256=0TrIBTDYLz2PhVx7yE9RDNoCENFRlLDEw1e8nvabm1k,9716 -discord/ext/commands/core.py,sha256=ss-j3b-dmQncfoWLunycmeK9IhjGMSkPqvH59KxJ2Mw,87933 -discord/ext/commands/errors.py,sha256=1dnfxbweQJ7VW7Wtm0cMtI5V4zl8MsJU4gp8wJOWgKQ,36151 -discord/ext/commands/flags.py,sha256=sNpJlJ8Q9959Esrvx1IRXjcpyzJna7KCTT5RL-i9Fs0,22324 -discord/ext/commands/help.py,sha256=4_i3CSfckbRt2YkE15skQ0MQuqMq4_tAOsPaOEjDK4s,57412 -discord/ext/commands/hybrid.py,sha256=bEVdP9Efi9tkv5C_0Ha7R1cbclgrlMYNQgmj5uQR0II,36161 -discord/ext/commands/parameters.py,sha256=tgWZMa3Zw7DH_nbe9Hp3Zhiul6psaw7dILeOnPECPm0,8344 -discord/ext/commands/view.py,sha256=lwRVmdXEkTIyzLLacr7Wz6jFY0s7KEbzuFgzx8Wgjog,6247 -discord/ext/tasks/__init__.py,sha256=60L9gRLI-Bip_EPS_U959jNgAh6M7Sh8jCIUNJUkXDw,29153 -discord/ext/tasks/__pycache__/__init__.cpython-38.pyc,, -discord/file.py,sha256=qZ9uJPn0SIQpT7NR_luyGAWC3HMH4YnL37JnAdPOZy4,5438 -discord/flags.py,sha256=kBx_cqy_-HbQxJwvVAXlAtTLwKa4iR5ne0X_6OtI2qs,48309 -discord/gateway.py,sha256=314HVjxAm5SmfGXo5fWpTpgESVzuFBnTTGQ02XaSTmE,34879 -discord/guild.py,sha256=grFnq088q6pAPqIkCXdtXrpfNHTujZSUNC_PxkiU2XE,137757 -discord/http.py,sha256=FQKPICAV_DbLgjPFo0nygA0x570IJuKl_TWLGJDcbQ0,89059 -discord/integrations.py,sha256=YEg76wjlp_l55H-mOBBghbJqlz1XZGFW1i5PhIOCZR0,13403 -discord/interactions.py,sha256=CNM7gE7FzV60WM0vq5tdCy_aR5dxcncT0tWk6sTAQTM,39900 -discord/invite.py,sha256=dA2npDEeeH-9HG-OEwAgglmxA16qvyB5xJv2io3-Q9o,20564 -discord/member.py,sha256=jboLS0PDEbd-xFNIilOnumNtrvTXrtu_DL8M3jCbDe0,39605 -discord/mentions.py,sha256=2DZE_Uh2sDIoext6-bAXkdyWAjRVSAV3GrMYxKFIL14,5592 -discord/message.py,sha256=8DLQiP9XmVNm6dpwqxf4b-iv0M-sDYrb8EW7zdn_0Lg,78313 -discord/mixins.py,sha256=_mKBOfdhQKNwlVx2m4jbJmOvtWxkuWSBEbnhxNDd4qo,1485 -discord/object.py,sha256=H2M4THLbeH5Kbi0ZodHDGp1k1qQZc2bTfBvNsDVDb9Y,3695 -discord/oggparse.py,sha256=F_wjGRC2TWeq0tMltNukivWSP-YUdP8WAIOy-oVqNmU,3646 -discord/opus.py,sha256=zo1FUdkAp1xbZXXBiDlk2Nrw68fMNTzUFkhmnRzohgg,15065 -discord/partial_emoji.py,sha256=ybHYXLIv6kUCw_YXFFLMFNO_hLvwGI8TTJ6ErX8aYHQ,7634 -discord/permissions.py,sha256=kGqBVd64cMnGMrEJZkdmnAExTBc_nU4oOoSvDi8KCtY,28151 -discord/player.py,sha256=RDn3VwzAA_ixPk5b4qBnDnkG9QELwq17VZK3mU4ZrCU,26456 -discord/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 -discord/raw_models.py,sha256=fZfp5OKQb31IutyW2OyyOBU_WLdnTfiD-mvQmLR-erA,16822 -discord/reaction.py,sha256=wFaaxPn7CXiM8axCpy3f3pfAFe5KohQuUP9tJRJK0GM,8255 -discord/role.py,sha256=3e0chFAUbC1CvSBDtfsMi_uY7VY76BJLbbhqgN77EA0,17038 -discord/scheduled_event.py,sha256=m0VGD7RcIy7iLg-vWGaZ-jideJsMYuTXTX4iHwf3IRw,20717 -discord/shard.py,sha256=tGmBD1mJKtUybeC2dgAwwqftEZVFHqXfEIqL-_N4c20,20061 -discord/stage_instance.py,sha256=nddKhrkcjA4M_YjxpnblCfVBbY0E27QCeoCe2iKaSC0,6546 -discord/state.py,sha256=L8gP-7-Lsz-pmiDfPUyuhdPnXqciEfpJWPwGv0qkEyk,72733 -discord/sticker.py,sha256=hdCSl2j4ettxJiJECJCukrQTmAvpNkX5mkIEot15QT8,16063 -discord/team.py,sha256=elrIodKl_OcyOBt6iaqYq-T-FhtvU2xHB0pJG6Qn0v8,4607 -discord/template.py,sha256=yzlrlL2hrPUSDLyT6N0DDxYdLqKudRw3jYma8T1Bym0,9581 -discord/threads.py,sha256=llT7ZmmfaKN0xreQtxNQsCN4r3uvIc4zDQn4-Ar7ecA,28293 -discord/types/__init__.py,sha256=7kT6hLaDiMVwuJvp4Os08kxqu9bxX3Yr9FFcOGYd6YQ,149 -discord/types/__pycache__/__init__.cpython-38.pyc,, -discord/types/__pycache__/activity.cpython-38.pyc,, -discord/types/__pycache__/appinfo.cpython-38.pyc,, -discord/types/__pycache__/audit_log.cpython-38.pyc,, -discord/types/__pycache__/automod.cpython-38.pyc,, -discord/types/__pycache__/channel.cpython-38.pyc,, -discord/types/__pycache__/command.cpython-38.pyc,, -discord/types/__pycache__/components.cpython-38.pyc,, -discord/types/__pycache__/embed.cpython-38.pyc,, -discord/types/__pycache__/emoji.cpython-38.pyc,, -discord/types/__pycache__/gateway.cpython-38.pyc,, -discord/types/__pycache__/guild.cpython-38.pyc,, -discord/types/__pycache__/integration.cpython-38.pyc,, -discord/types/__pycache__/interactions.cpython-38.pyc,, -discord/types/__pycache__/invite.cpython-38.pyc,, -discord/types/__pycache__/member.cpython-38.pyc,, -discord/types/__pycache__/message.cpython-38.pyc,, -discord/types/__pycache__/role.cpython-38.pyc,, -discord/types/__pycache__/scheduled_event.cpython-38.pyc,, -discord/types/__pycache__/snowflake.cpython-38.pyc,, -discord/types/__pycache__/sticker.cpython-38.pyc,, -discord/types/__pycache__/team.cpython-38.pyc,, -discord/types/__pycache__/template.cpython-38.pyc,, -discord/types/__pycache__/threads.cpython-38.pyc,, -discord/types/__pycache__/user.cpython-38.pyc,, -discord/types/__pycache__/voice.cpython-38.pyc,, -discord/types/__pycache__/webhook.cpython-38.pyc,, -discord/types/__pycache__/welcome_screen.cpython-38.pyc,, -discord/types/__pycache__/widget.cpython-38.pyc,, -discord/types/activity.py,sha256=k7tqp11m_t77Lu9D5T8pAMw1dnQcs7CtLJ5NV-4CgzQ,2707 -discord/types/appinfo.py,sha256=APP2OKoT1VvUX_OO7oZe4HuLeGZBGShGn9KVWQG4dt0,2330 -discord/types/audit_log.py,sha256=8ceXkxHhUlZrlooAgHC0_VqCnA9KZYPPl2yZ0YmcJ0g,7468 -discord/types/automod.py,sha256=O5AZiZn9Cz5RE8NzAO6Kte6HZaijWUxcN-r9e5jAtqc,3842 -discord/types/channel.py,sha256=9X2XxyevV8U58pUJEv32umfyqeVKAbPKm8cl0YKlres,4012 -discord/types/command.py,sha256=1hcNoTUcJmpQy29ILcevQSxT8X2nxCngwubshVdgtyI,6266 -discord/types/components.py,sha256=jLxNOpxIFLSqM5ne1qg6f96lLs8UDy1EsVj4CSnQUZg,2465 -discord/types/embed.py,sha256=VnYSZqjPIYXAGA87P-JhjXs_mGhswaMpOd81mzF5iPc,2329 -discord/types/emoji.py,sha256=JfwRzhcs7KRLKVtl8bCrvbgBTl9Ww8MboNoUcEf2EkM,1528 -discord/types/gateway.py,sha256=s99Fs9jUT5wRZF2egtQOZ984iAhgKZQaWwFCgMRo5BQ,8328 -discord/types/guild.py,sha256=HRsRBXna0z-DCRojbyMtDZHPeREVsQ70BhRjZtp2bX8,4944 -discord/types/integration.py,sha256=COkepHL3jhihFBFVkKn8h54LNRfObQC81uGVwESER30,2266 -discord/types/interactions.py,sha256=jVbOrL860jcnrbeGfjhwm35bVJf8OR9tzLxrLgoqsjg,6871 -discord/types/invite.py,sha256=sLmvX0Imw5qtV-h78BYVf928Q0YIfGWVuz9XxY8Ctqg,2704 -discord/types/member.py,sha256=2rieSLJfsCImyrD1AnXuds5ELuBJHWgdjOaWidH_bh8,1883 -discord/types/message.py,sha256=7GApqs0wSSgMyLzTHt9UtJtNvLVp9ZuJXsnXED9lVH8,3881 -discord/types/role.py,sha256=jg_P1LBnxmQ70L2ukAYjVjgcH5a3dCCHGSliMFbUwxA,1646 -discord/types/scheduled_event.py,sha256=WwSiBISWsOD81CVxBc2dwfnLSCaRPsZUdYFWyW8ouJI,3294 -discord/types/snowflake.py,sha256=x_L3OXauewQagDr6jPzj7uCw1MNqijsy-Uo9vvkwvF0,1182 -discord/types/sticker.py,sha256=cT717cduRvGAvjF5NFwR6vDkaHLDij6xgwYxs4jUdGA,2244 -discord/types/team.py,sha256=rOgj3_h4UGMTSx9dgyBrYTX-1MQZdvPqpJgZKtnOOF4,1499 -discord/types/template.py,sha256=EO4tA2WypntCGQ9sWud5VS_uI8n12iVVHVPcNgCtZvM,1609 -discord/types/threads.py,sha256=h8BRUDGXMEYX1OhjewbaLmWwnJxzOk2AAgTRe--bH4E,2407 -discord/types/user.py,sha256=fmJShIs-vFsqyuGnnse_0WSJyw7QVk1RnVIwEQMt84Q,1540 -discord/types/voice.py,sha256=wFQLiPZaQuXBKE1dM_bdWNpkglpGFC7kEtghwCHBDQM,2268 -discord/types/webhook.py,sha256=iqBUgbz38o0_mWp-gcVI0_urpgZ_dq2EfOOXACg47u8,1978 -discord/types/welcome_screen.py,sha256=ukQMefZLHpgyg0_5IoAzN0UX40VayhF2vnJzNJNMZzA,1460 -discord/types/widget.py,sha256=YRkhDoBHbCEtkmYTVOSoHM8Y3mH9GIdowthoz8ISJYU,1883 -discord/ui/__init__.py,sha256=zsTlMLSiy6RzXzNVl1i5WDiM5piE_bgzCTLYU93axYM,285 -discord/ui/__pycache__/__init__.cpython-38.pyc,, -discord/ui/__pycache__/button.cpython-38.pyc,, -discord/ui/__pycache__/item.cpython-38.pyc,, -discord/ui/__pycache__/modal.cpython-38.pyc,, -discord/ui/__pycache__/select.cpython-38.pyc,, -discord/ui/__pycache__/text_input.cpython-38.pyc,, -discord/ui/__pycache__/view.cpython-38.pyc,, -discord/ui/button.py,sha256=Q1R4gPQTJjzlnBn9Hi2Y5YpgR5gCgK8eLKomysL-7hc,10595 -discord/ui/item.py,sha256=lWH_s8Rw4Sn85ZmbwgFXFGXyfsFPkitq4KTI9rAjfkc,4298 -discord/ui/modal.py,sha256=X7FnvkJgu4FMqRacN80Q-Wl0iuRqCwuQT2vtv7gKHtg,6900 -discord/ui/select.py,sha256=9IP6MytrLXu6VOV3pe_jiUNjdj4rp_myDkLm1VME9SA,13057 -discord/ui/text_input.py,sha256=7pto9tAGJylFITQcxpFiY6D06h10fYShp54fJcgpzGk,7982 -discord/ui/view.py,sha256=Og2bqBZidoa1IndoOs17vA60lSQCM3L-O6nC8z-4Pkw,22744 -discord/user.py,sha256=fxkZMlFmGj_6el79aLLzFGJUj0bRgI9vpoVPUAvPKCg,15392 -discord/utils.py,sha256=JsJ8QoU78VGNKGiNYEyWzVizcguw4JExApwNKFtEnJ0,39409 -discord/voice_client.py,sha256=0dUM5VSzJZsOoNwhwzHkH4swIbSujkQhApIxYqhAOfY,24968 -discord/webhook/__init__.py,sha256=5lx7IcCFf9DAjdX7CVen3-8DjHAfGvS1rSDY3DyVnqM,182 -discord/webhook/__pycache__/__init__.cpython-38.pyc,, -discord/webhook/__pycache__/async_.cpython-38.pyc,, -discord/webhook/__pycache__/sync.cpython-38.pyc,, -discord/webhook/async_.py,sha256=PhKmzTiVAkUo9r2AxNMxz4xFZ6XsvSd2pXgtiou842s,66670 -discord/webhook/sync.py,sha256=zf5rUCobpk6R4wP91dMvhY2PXnXKHcJUEop5nRGtUws,42014 -discord/welcome_screen.py,sha256=PFqkBWbZBgD1bzjZgge7hjcjWU0qTwmDt2gOkw2K0To,7562 -discord/widget.py,sha256=RaDGOudb-3_lmusAxfi2pJWfZ0SuXOjscnHuBcIWvsQ,10160 diff --git a/.venv/Lib/site-packages/discord.py-2.0.1.dist-info/WHEEL b/.venv/Lib/site-packages/discord.py-2.0.1.dist-info/WHEEL deleted file mode 100644 index becc9a6..0000000 --- a/.venv/Lib/site-packages/discord.py-2.0.1.dist-info/WHEEL +++ /dev/null @@ -1,5 +0,0 @@ -Wheel-Version: 1.0 -Generator: bdist_wheel (0.37.1) -Root-Is-Purelib: true -Tag: py3-none-any - diff --git a/.venv/Lib/site-packages/discord.py-2.0.1.dist-info/top_level.txt b/.venv/Lib/site-packages/discord.py-2.0.1.dist-info/top_level.txt deleted file mode 100644 index e46fba2..0000000 --- a/.venv/Lib/site-packages/discord.py-2.0.1.dist-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -discord diff --git a/.venv/Lib/site-packages/discord/__init__.py b/.venv/Lib/site-packages/discord/__init__.py deleted file mode 100644 index c48558c..0000000 --- a/.venv/Lib/site-packages/discord/__init__.py +++ /dev/null @@ -1,85 +0,0 @@ -""" -Discord API Wrapper -~~~~~~~~~~~~~~~~~~~ - -A basic wrapper for the Discord API. - -:copyright: (c) 2015-present Rapptz -:license: MIT, see LICENSE for more details. - -""" - -__title__ = 'discord' -__author__ = 'Rapptz' -__license__ = 'MIT' -__copyright__ = 'Copyright 2015-present Rapptz' -__version__ = '2.0.1' - -__path__ = __import__('pkgutil').extend_path(__path__, __name__) - -import logging -from typing import NamedTuple, Literal - -from .client import * -from .appinfo import * -from .user import * -from .emoji import * -from .partial_emoji import * -from .activity import * -from .channel import * -from .guild import * -from .flags import * -from .member import * -from .message import * -from .asset import * -from .errors import * -from .permissions import * -from .role import * -from .file import * -from .colour import * -from .integrations import * -from .invite import * -from .template import * -from .welcome_screen import * -from .widget import * -from .object import * -from .reaction import * -from . import ( - utils as utils, - opus as opus, - abc as abc, - ui as ui, - app_commands as app_commands, -) -from .enums import * -from .embeds import * -from .mentions import * -from .shard import * -from .player import * -from .webhook import * -from .voice_client import * -from .audit_logs import * -from .raw_models import * -from .team import * -from .sticker import * -from .stage_instance import * -from .scheduled_event import * -from .interactions import * -from .components import * -from .threads import * -from .automod import * - - -class VersionInfo(NamedTuple): - major: int - minor: int - micro: int - releaselevel: Literal["alpha", "beta", "candidate", "final"] - serial: int - - -version_info: VersionInfo = VersionInfo(major=2, minor=0, micro=1, releaselevel='final', serial=0) - -logging.getLogger(__name__).addHandler(logging.NullHandler()) - -del logging, NamedTuple, Literal, VersionInfo diff --git a/.venv/Lib/site-packages/discord/__main__.py b/.venv/Lib/site-packages/discord/__main__.py deleted file mode 100644 index 6e34be5..0000000 --- a/.venv/Lib/site-packages/discord/__main__.py +++ /dev/null @@ -1,351 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations - -from typing import Optional, Tuple, Dict - -import argparse -import sys -from pathlib import Path - -import discord -import importlib.metadata -import aiohttp -import platform - - -def show_version() -> None: - entries = [] - - entries.append('- Python v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(sys.version_info)) - version_info = discord.version_info - entries.append('- discord.py v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}'.format(version_info)) - if version_info.releaselevel != 'final': - version = importlib.metadata.version('discord.py') - if version: - entries.append(f' - discord.py metadata: v{version}') - - entries.append(f'- aiohttp v{aiohttp.__version__}') - uname = platform.uname() - entries.append('- system info: {0.system} {0.release} {0.version}'.format(uname)) - print('\n'.join(entries)) - - -def core(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None: - if args.version: - show_version() - else: - parser.print_help() - - -_bot_template = """#!/usr/bin/env python3 - -from discord.ext import commands -import discord -import config - -class Bot(commands.{base}): - def __init__(self, intents: discord.Intents, **kwargs): - super().__init__(command_prefix=commands.when_mentioned_or('{prefix}'), intents=intents, **kwargs) - - async def setup_hook(self): - for cog in config.cogs: - try: - await self.load_extension(cog) - except Exception as exc: - print(f'Could not load extension {{cog}} due to {{exc.__class__.__name__}}: {{exc}}') - - async def on_ready(self): - print(f'Logged on as {{self.user}} (ID: {{self.user.id}})') - - -intents = discord.Intents.default() -intents.message_content = True -bot = Bot(intents=intents) - -# write general commands here - -bot.run(config.token) -""" - -_gitignore_template = """# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -env/ -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -*.egg-info/ -.installed.cfg -*.egg - -# Our configuration files -config.py -""" - -_cog_template = '''from discord.ext import commands -import discord - -class {name}(commands.Cog{attrs}): - """The description for {name} goes here.""" - - def __init__(self, bot): - self.bot = bot -{extra} -async def setup(bot): - await bot.add_cog({name}(bot)) -''' - -_cog_extras = ''' - async def cog_load(self): - # loading logic goes here - pass - - async def cog_unload(self): - # clean up logic goes here - pass - - async def cog_check(self, ctx): - # checks that apply to every command in here - return True - - async def bot_check(self, ctx): - # checks that apply to every command to the bot - return True - - async def bot_check_once(self, ctx): - # check that apply to every command but is guaranteed to be called only once - return True - - async def cog_command_error(self, ctx, error): - # error handling to every command in here - pass - - async def cog_app_command_error(self, interaction, error): - # error handling to every application command in here - pass - - async def cog_before_invoke(self, ctx): - # called before a command is called here - pass - - async def cog_after_invoke(self, ctx): - # called after a command is called here - pass - -''' - - -# certain file names and directory names are forbidden -# see: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx -# although some of this doesn't apply to Linux, we might as well be consistent -_base_table: Dict[str, Optional[str]] = { - '<': '-', - '>': '-', - ':': '-', - '"': '-', - # '/': '-', these are fine - # '\\': '-', - '|': '-', - '?': '-', - '*': '-', -} - -# NUL (0) and 1-31 are disallowed -_base_table.update((chr(i), None) for i in range(32)) - -_translation_table = str.maketrans(_base_table) - - -def to_path(parser: argparse.ArgumentParser, name: str, *, replace_spaces: bool = False) -> Path: - if isinstance(name, Path): - return name - - if sys.platform == 'win32': - forbidden = ( - 'CON', - 'PRN', - 'AUX', - 'NUL', - 'COM1', - 'COM2', - 'COM3', - 'COM4', - 'COM5', - 'COM6', - 'COM7', - 'COM8', - 'COM9', - 'LPT1', - 'LPT2', - 'LPT3', - 'LPT4', - 'LPT5', - 'LPT6', - 'LPT7', - 'LPT8', - 'LPT9', - ) - if len(name) <= 4 and name.upper() in forbidden: - parser.error('invalid directory name given, use a different one') - - name = name.translate(_translation_table) - if replace_spaces: - name = name.replace(' ', '-') - return Path(name) - - -def newbot(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None: - new_directory = to_path(parser, args.directory) / to_path(parser, args.name) - - # as a note exist_ok for Path is a 3.5+ only feature - # since we already checked above that we're >3.5 - try: - new_directory.mkdir(exist_ok=True, parents=True) - except OSError as exc: - parser.error(f'could not create our bot directory ({exc})') - - cogs = new_directory / 'cogs' - - try: - cogs.mkdir(exist_ok=True) - init = cogs / '__init__.py' - init.touch() - except OSError as exc: - print(f'warning: could not create cogs directory ({exc})') - - try: - with open(str(new_directory / 'config.py'), 'w', encoding='utf-8') as fp: - fp.write('token = "place your token here"\ncogs = []\n') - except OSError as exc: - parser.error(f'could not create config file ({exc})') - - try: - with open(str(new_directory / 'bot.py'), 'w', encoding='utf-8') as fp: - base = 'Bot' if not args.sharded else 'AutoShardedBot' - fp.write(_bot_template.format(base=base, prefix=args.prefix)) - except OSError as exc: - parser.error(f'could not create bot file ({exc})') - - if not args.no_git: - try: - with open(str(new_directory / '.gitignore'), 'w', encoding='utf-8') as fp: - fp.write(_gitignore_template) - except OSError as exc: - print(f'warning: could not create .gitignore file ({exc})') - - print('successfully made bot at', new_directory) - - -def newcog(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None: - cog_dir = to_path(parser, args.directory) - try: - cog_dir.mkdir(exist_ok=True) - except OSError as exc: - print(f'warning: could not create cogs directory ({exc})') - - directory = cog_dir / to_path(parser, args.name) - directory = directory.with_suffix('.py') - try: - with open(str(directory), 'w', encoding='utf-8') as fp: - attrs = '' - extra = _cog_extras if args.full else '' - if args.class_name: - name = args.class_name - else: - name = str(directory.stem) - if '-' in name or '_' in name: - translation = str.maketrans('-_', ' ') - name = name.translate(translation).title().replace(' ', '') - else: - name = name.title() - - if args.display_name: - attrs += f', name="{args.display_name}"' - if args.hide_commands: - attrs += ', command_attrs=dict(hidden=True)' - fp.write(_cog_template.format(name=name, extra=extra, attrs=attrs)) - except OSError as exc: - parser.error(f'could not create cog file ({exc})') - else: - print('successfully made cog at', directory) - - -def add_newbot_args(subparser: argparse._SubParsersAction[argparse.ArgumentParser]) -> None: - parser = subparser.add_parser('newbot', help='creates a command bot project quickly') - parser.set_defaults(func=newbot) - - parser.add_argument('name', help='the bot project name') - parser.add_argument('directory', help='the directory to place it in (default: .)', nargs='?', default=Path.cwd()) - parser.add_argument('--prefix', help='the bot prefix (default: $)', default='$', metavar='') - parser.add_argument('--sharded', help='whether to use AutoShardedBot', action='store_true') - parser.add_argument('--no-git', help='do not create a .gitignore file', action='store_true', dest='no_git') - - -def add_newcog_args(subparser: argparse._SubParsersAction[argparse.ArgumentParser]) -> None: - parser = subparser.add_parser('newcog', help='creates a new cog template quickly') - parser.set_defaults(func=newcog) - - parser.add_argument('name', help='the cog name') - parser.add_argument('directory', help='the directory to place it in (default: cogs)', nargs='?', default=Path('cogs')) - parser.add_argument('--class-name', help='the class name of the cog (default: )', dest='class_name') - parser.add_argument('--display-name', help='the cog name (default: )') - parser.add_argument('--hide-commands', help='whether to hide all commands in the cog', action='store_true') - parser.add_argument('--full', help='add all special methods as well', action='store_true') - - -def parse_args() -> Tuple[argparse.ArgumentParser, argparse.Namespace]: - parser = argparse.ArgumentParser(prog='discord', description='Tools for helping with discord.py') - parser.add_argument('-v', '--version', action='store_true', help='shows the library version') - parser.set_defaults(func=core) - - subparser = parser.add_subparsers(dest='subcommand', title='subcommands') - add_newbot_args(subparser) - add_newcog_args(subparser) - return parser, parser.parse_args() - - -def main() -> None: - parser, args = parse_args() - args.func(parser, args) - - -if __name__ == '__main__': - main() diff --git a/.venv/Lib/site-packages/discord/__pycache__/__init__.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index 50be9b0..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/__main__.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/__main__.cpython-38.pyc deleted file mode 100644 index c1d353e..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/__main__.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/abc.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/abc.cpython-38.pyc deleted file mode 100644 index d02e022..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/abc.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/activity.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/activity.cpython-38.pyc deleted file mode 100644 index 95763de..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/activity.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/appinfo.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/appinfo.cpython-38.pyc deleted file mode 100644 index d965315..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/appinfo.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/asset.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/asset.cpython-38.pyc deleted file mode 100644 index bd4cba6..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/asset.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/audit_logs.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/audit_logs.cpython-38.pyc deleted file mode 100644 index c04e811..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/audit_logs.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/automod.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/automod.cpython-38.pyc deleted file mode 100644 index f7b8ec7..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/automod.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/backoff.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/backoff.cpython-38.pyc deleted file mode 100644 index 96c151c..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/backoff.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/channel.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/channel.cpython-38.pyc deleted file mode 100644 index e9353c0..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/channel.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/client.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/client.cpython-38.pyc deleted file mode 100644 index 7eb2bff..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/client.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/colour.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/colour.cpython-38.pyc deleted file mode 100644 index 5ca12c3..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/colour.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/components.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/components.cpython-38.pyc deleted file mode 100644 index 04d8951..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/components.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/context_managers.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/context_managers.cpython-38.pyc deleted file mode 100644 index 1b3dce7..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/context_managers.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/embeds.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/embeds.cpython-38.pyc deleted file mode 100644 index 8b23bfa..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/embeds.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/emoji.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/emoji.cpython-38.pyc deleted file mode 100644 index 76a82b1..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/emoji.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/enums.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/enums.cpython-38.pyc deleted file mode 100644 index 4a147c1..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/enums.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/errors.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/errors.cpython-38.pyc deleted file mode 100644 index aa2c743..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/errors.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/file.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/file.cpython-38.pyc deleted file mode 100644 index 7212d6d..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/file.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/flags.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/flags.cpython-38.pyc deleted file mode 100644 index 89fae89..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/flags.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/gateway.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/gateway.cpython-38.pyc deleted file mode 100644 index 4fc6d2d..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/gateway.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/guild.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/guild.cpython-38.pyc deleted file mode 100644 index ef32504..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/guild.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/http.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/http.cpython-38.pyc deleted file mode 100644 index 352c216..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/http.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/integrations.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/integrations.cpython-38.pyc deleted file mode 100644 index d3bfc01..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/integrations.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/interactions.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/interactions.cpython-38.pyc deleted file mode 100644 index f5f5149..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/interactions.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/invite.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/invite.cpython-38.pyc deleted file mode 100644 index 9777546..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/invite.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/member.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/member.cpython-38.pyc deleted file mode 100644 index c67ffec..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/member.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/mentions.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/mentions.cpython-38.pyc deleted file mode 100644 index 42c1c87..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/mentions.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/message.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/message.cpython-38.pyc deleted file mode 100644 index c18ecc4..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/message.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/mixins.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/mixins.cpython-38.pyc deleted file mode 100644 index e9888b8..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/mixins.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/object.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/object.cpython-38.pyc deleted file mode 100644 index 5af1389..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/object.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/oggparse.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/oggparse.cpython-38.pyc deleted file mode 100644 index 20c916c..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/oggparse.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/opus.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/opus.cpython-38.pyc deleted file mode 100644 index 6c5f714..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/opus.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/partial_emoji.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/partial_emoji.cpython-38.pyc deleted file mode 100644 index 0aa2912..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/partial_emoji.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/permissions.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/permissions.cpython-38.pyc deleted file mode 100644 index e237eea..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/permissions.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/player.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/player.cpython-38.pyc deleted file mode 100644 index 1699943..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/player.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/raw_models.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/raw_models.cpython-38.pyc deleted file mode 100644 index 4679594..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/raw_models.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/reaction.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/reaction.cpython-38.pyc deleted file mode 100644 index 2e848c2..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/reaction.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/role.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/role.cpython-38.pyc deleted file mode 100644 index 316be44..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/role.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/scheduled_event.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/scheduled_event.cpython-38.pyc deleted file mode 100644 index 3b7ac7d..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/scheduled_event.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/shard.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/shard.cpython-38.pyc deleted file mode 100644 index e1ef25c..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/shard.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/stage_instance.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/stage_instance.cpython-38.pyc deleted file mode 100644 index fe2306f..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/stage_instance.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/state.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/state.cpython-38.pyc deleted file mode 100644 index ce71b8f..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/state.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/sticker.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/sticker.cpython-38.pyc deleted file mode 100644 index ff587cf..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/sticker.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/team.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/team.cpython-38.pyc deleted file mode 100644 index b53f60d..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/team.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/template.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/template.cpython-38.pyc deleted file mode 100644 index ad09c71..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/template.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/threads.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/threads.cpython-38.pyc deleted file mode 100644 index a8b1864..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/threads.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/user.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/user.cpython-38.pyc deleted file mode 100644 index 1d6a980..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/user.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/utils.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/utils.cpython-38.pyc deleted file mode 100644 index 88f1b36..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/utils.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/voice_client.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/voice_client.cpython-38.pyc deleted file mode 100644 index 6800966..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/voice_client.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/welcome_screen.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/welcome_screen.cpython-38.pyc deleted file mode 100644 index 05d53dd..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/welcome_screen.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/__pycache__/widget.cpython-38.pyc b/.venv/Lib/site-packages/discord/__pycache__/widget.cpython-38.pyc deleted file mode 100644 index fac2797..0000000 Binary files a/.venv/Lib/site-packages/discord/__pycache__/widget.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/abc.py b/.venv/Lib/site-packages/discord/abc.py deleted file mode 100644 index 5b0e7df..0000000 --- a/.venv/Lib/site-packages/discord/abc.py +++ /dev/null @@ -1,1888 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations - -import copy -import time -import asyncio -from datetime import datetime -from typing import ( - Any, - AsyncIterator, - Callable, - Dict, - Iterable, - List, - Optional, - TYPE_CHECKING, - Protocol, - Sequence, - Tuple, - TypeVar, - Union, - overload, - runtime_checkable, -) - -from .object import OLDEST_OBJECT, Object -from .context_managers import Typing -from .enums import ChannelType -from .errors import ClientException -from .mentions import AllowedMentions -from .permissions import PermissionOverwrite, Permissions -from .role import Role -from .invite import Invite -from .file import File -from .http import handle_message_parameters -from .voice_client import VoiceClient, VoiceProtocol -from .sticker import GuildSticker, StickerItem -from . import utils - -__all__ = ( - 'Snowflake', - 'User', - 'PrivateChannel', - 'GuildChannel', - 'Messageable', - 'Connectable', -) - -T = TypeVar('T', bound=VoiceProtocol) - -if TYPE_CHECKING: - from typing_extensions import Self - - from .client import Client - from .user import ClientUser - from .asset import Asset - from .state import ConnectionState - from .guild import Guild - from .member import Member - from .channel import CategoryChannel - from .embeds import Embed - from .message import Message, MessageReference, PartialMessage - from .channel import TextChannel, DMChannel, GroupChannel, PartialMessageable, VoiceChannel - from .threads import Thread - from .enums import InviteTarget - from .ui.view import View - from .types.channel import ( - PermissionOverwrite as PermissionOverwritePayload, - Channel as ChannelPayload, - GuildChannel as GuildChannelPayload, - OverwriteType, - ) - from .types.snowflake import ( - SnowflakeList, - ) - - PartialMessageableChannel = Union[TextChannel, VoiceChannel, Thread, DMChannel, PartialMessageable] - MessageableChannel = Union[PartialMessageableChannel, GroupChannel] - SnowflakeTime = Union["Snowflake", datetime] - -MISSING = utils.MISSING - - -class _Undefined: - def __repr__(self) -> str: - return 'see-below' - - -_undefined: Any = _Undefined() - - -async def _single_delete_strategy(messages: Iterable[Message], *, reason: Optional[str] = None): - for m in messages: - await m.delete() - - -async def _purge_helper( - channel: Union[Thread, TextChannel, VoiceChannel], - *, - limit: Optional[int] = 100, - check: Callable[[Message], bool] = MISSING, - before: Optional[SnowflakeTime] = None, - after: Optional[SnowflakeTime] = None, - around: Optional[SnowflakeTime] = None, - oldest_first: Optional[bool] = None, - bulk: bool = True, - reason: Optional[str] = None, -) -> List[Message]: - if check is MISSING: - check = lambda m: True - - iterator = channel.history(limit=limit, before=before, after=after, oldest_first=oldest_first, around=around) - ret: List[Message] = [] - count = 0 - - minimum_time = int((time.time() - 14 * 24 * 60 * 60) * 1000.0 - 1420070400000) << 22 - strategy = channel.delete_messages if bulk else _single_delete_strategy - - async for message in iterator: - if count == 100: - to_delete = ret[-100:] - await strategy(to_delete, reason=reason) - count = 0 - await asyncio.sleep(1) - - if not check(message): - continue - - if message.id < minimum_time: - # older than 14 days old - if count == 1: - await ret[-1].delete() - elif count >= 2: - to_delete = ret[-count:] - await strategy(to_delete, reason=reason) - - count = 0 - strategy = _single_delete_strategy - - count += 1 - ret.append(message) - - # Some messages remaining to poll - if count >= 2: - # more than 2 messages -> bulk delete - to_delete = ret[-count:] - await strategy(to_delete, reason=reason) - elif count == 1: - # delete a single message - await ret[-1].delete() - - return ret - - -@runtime_checkable -class Snowflake(Protocol): - """An ABC that details the common operations on a Discord model. - - Almost all :ref:`Discord models ` meet this - abstract base class. - - If you want to create a snowflake on your own, consider using - :class:`.Object`. - - Attributes - ----------- - id: :class:`int` - The model's unique ID. - """ - - id: int - - -@runtime_checkable -class User(Snowflake, Protocol): - """An ABC that details the common operations on a Discord user. - - The following implement this ABC: - - - :class:`~discord.User` - - :class:`~discord.ClientUser` - - :class:`~discord.Member` - - This ABC must also implement :class:`~discord.abc.Snowflake`. - - Attributes - ----------- - name: :class:`str` - The user's username. - discriminator: :class:`str` - The user's discriminator. - bot: :class:`bool` - If the user is a bot account. - system: :class:`bool` - If the user is a system account. - """ - - name: str - discriminator: str - bot: bool - system: bool - - @property - def display_name(self) -> str: - """:class:`str`: Returns the user's display name.""" - raise NotImplementedError - - @property - def mention(self) -> str: - """:class:`str`: Returns a string that allows you to mention the given user.""" - raise NotImplementedError - - @property - def avatar(self) -> Optional[Asset]: - """Optional[:class:`~discord.Asset`]: Returns an Asset that represents the user's avatar, if present.""" - raise NotImplementedError - - @property - def default_avatar(self) -> Asset: - """:class:`~discord.Asset`: Returns the default avatar for a given user. This is calculated by the user's discriminator.""" - raise NotImplementedError - - @property - def display_avatar(self) -> Asset: - """:class:`~discord.Asset`: Returns the user's display avatar. - - For regular users this is just their default avatar or uploaded avatar. - - .. versionadded:: 2.0 - """ - raise NotImplementedError - - def mentioned_in(self, message: Message) -> bool: - """Checks if the user is mentioned in the specified message. - - Parameters - ----------- - message: :class:`~discord.Message` - The message to check if you're mentioned in. - - Returns - ------- - :class:`bool` - Indicates if the user is mentioned in the message. - """ - raise NotImplementedError - - -class PrivateChannel: - """An ABC that details the common operations on a private Discord channel. - - The following implement this ABC: - - - :class:`~discord.DMChannel` - - :class:`~discord.GroupChannel` - - This ABC must also implement :class:`~discord.abc.Snowflake`. - - Attributes - ----------- - me: :class:`~discord.ClientUser` - The user presenting yourself. - """ - - __slots__ = () - - id: int - me: ClientUser - - -class _Overwrites: - __slots__ = ('id', 'allow', 'deny', 'type') - - ROLE = 0 - MEMBER = 1 - - def __init__(self, data: PermissionOverwritePayload) -> None: - self.id: int = int(data['id']) - self.allow: int = int(data.get('allow', 0)) - self.deny: int = int(data.get('deny', 0)) - self.type: OverwriteType = data['type'] - - def _asdict(self) -> PermissionOverwritePayload: - return { - 'id': self.id, - 'allow': str(self.allow), - 'deny': str(self.deny), - 'type': self.type, - } - - def is_role(self) -> bool: - return self.type == 0 - - def is_member(self) -> bool: - return self.type == 1 - - -class GuildChannel: - """An ABC that details the common operations on a Discord guild channel. - - The following implement this ABC: - - - :class:`~discord.TextChannel` - - :class:`~discord.VoiceChannel` - - :class:`~discord.CategoryChannel` - - :class:`~discord.StageChannel` - - :class:`~discord.ForumChannel` - - This ABC must also implement :class:`~discord.abc.Snowflake`. - - Attributes - ----------- - name: :class:`str` - The channel name. - guild: :class:`~discord.Guild` - The guild the channel belongs to. - position: :class:`int` - The position in the channel list. This is a number that starts at 0. - e.g. the top channel is position 0. - """ - - __slots__ = () - - id: int - name: str - guild: Guild - type: ChannelType - position: int - category_id: Optional[int] - _state: ConnectionState - _overwrites: List[_Overwrites] - - if TYPE_CHECKING: - - def __init__(self, *, state: ConnectionState, guild: Guild, data: GuildChannelPayload): - ... - - def __str__(self) -> str: - return self.name - - @property - def _sorting_bucket(self) -> int: - raise NotImplementedError - - def _update(self, guild: Guild, data: Dict[str, Any]) -> None: - raise NotImplementedError - - async def _move( - self, - position: int, - parent_id: Optional[Any] = None, - lock_permissions: bool = False, - *, - reason: Optional[str], - ) -> None: - if position < 0: - raise ValueError('Channel position cannot be less than 0.') - - http = self._state.http - bucket = self._sorting_bucket - channels: List[GuildChannel] = [c for c in self.guild.channels if c._sorting_bucket == bucket] - - channels.sort(key=lambda c: c.position) - - try: - # remove ourselves from the channel list - channels.remove(self) - except ValueError: - # not there somehow lol - return - else: - index = next((i for i, c in enumerate(channels) if c.position >= position), len(channels)) - # add ourselves at our designated position - channels.insert(index, self) - - payload = [] - for index, c in enumerate(channels): - d: Dict[str, Any] = {'id': c.id, 'position': index} - if parent_id is not _undefined and c.id == self.id: - d.update(parent_id=parent_id, lock_permissions=lock_permissions) - payload.append(d) - - await http.bulk_channel_update(self.guild.id, payload, reason=reason) - - async def _edit(self, options: Dict[str, Any], reason: Optional[str]) -> Optional[ChannelPayload]: - try: - parent = options.pop('category') - except KeyError: - parent_id = _undefined - else: - parent_id = parent and parent.id - - try: - options['rate_limit_per_user'] = options.pop('slowmode_delay') - except KeyError: - pass - - try: - rtc_region = options.pop('rtc_region') - except KeyError: - pass - else: - options['rtc_region'] = None if rtc_region is None else str(rtc_region) - - try: - video_quality_mode = options.pop('video_quality_mode') - except KeyError: - pass - else: - options['video_quality_mode'] = int(video_quality_mode) - - lock_permissions = options.pop('sync_permissions', False) - - try: - position = options.pop('position') - except KeyError: - if parent_id is not _undefined: - if lock_permissions: - category = self.guild.get_channel(parent_id) - if category: - options['permission_overwrites'] = [c._asdict() for c in category._overwrites] - options['parent_id'] = parent_id - elif lock_permissions and self.category_id is not None: - # if we're syncing permissions on a pre-existing channel category without changing it - # we need to update the permissions to point to the pre-existing category - category = self.guild.get_channel(self.category_id) - if category: - options['permission_overwrites'] = [c._asdict() for c in category._overwrites] - else: - await self._move(position, parent_id=parent_id, lock_permissions=lock_permissions, reason=reason) - - overwrites = options.get('overwrites', None) - if overwrites is not None: - perms = [] - for target, perm in overwrites.items(): - if not isinstance(perm, PermissionOverwrite): - raise TypeError(f'Expected PermissionOverwrite received {perm.__class__.__name__}') - - allow, deny = perm.pair() - payload = { - 'allow': allow.value, - 'deny': deny.value, - 'id': target.id, - } - - if isinstance(target, Role): - payload['type'] = _Overwrites.ROLE - elif isinstance(target, Object): - payload['type'] = _Overwrites.ROLE if target.type is Role else _Overwrites.MEMBER - else: - payload['type'] = _Overwrites.MEMBER - - perms.append(payload) - options['permission_overwrites'] = perms - - try: - ch_type = options['type'] - except KeyError: - pass - else: - if not isinstance(ch_type, ChannelType): - raise TypeError('type field must be of type ChannelType') - options['type'] = ch_type.value - - if options: - return await self._state.http.edit_channel(self.id, reason=reason, **options) - - def _fill_overwrites(self, data: GuildChannelPayload) -> None: - self._overwrites = [] - everyone_index = 0 - everyone_id = self.guild.id - - for index, overridden in enumerate(data.get('permission_overwrites', [])): - overwrite = _Overwrites(overridden) - self._overwrites.append(overwrite) - - if overwrite.type == _Overwrites.MEMBER: - continue - - if overwrite.id == everyone_id: - # the @everyone role is not guaranteed to be the first one - # in the list of permission overwrites, however the permission - # resolution code kind of requires that it is the first one in - # the list since it is special. So we need the index so we can - # swap it to be the first one. - everyone_index = index - - # do the swap - tmp = self._overwrites - if tmp: - tmp[everyone_index], tmp[0] = tmp[0], tmp[everyone_index] - - @property - def changed_roles(self) -> List[Role]: - """List[:class:`~discord.Role`]: Returns a list of roles that have been overridden from - their default values in the :attr:`~discord.Guild.roles` attribute.""" - ret = [] - g = self.guild - for overwrite in filter(lambda o: o.is_role(), self._overwrites): - role = g.get_role(overwrite.id) - if role is None: - continue - - role = copy.copy(role) - role.permissions.handle_overwrite(overwrite.allow, overwrite.deny) - ret.append(role) - return ret - - @property - def mention(self) -> str: - """:class:`str`: The string that allows you to mention the channel.""" - return f'<#{self.id}>' - - @property - def jump_url(self) -> str: - """:class:`str`: Returns a URL that allows the client to jump to the channel. - - .. versionadded:: 2.0 - """ - return f'https://discord.com/channels/{self.guild.id}/{self.id}' - - @property - def created_at(self) -> datetime: - """:class:`datetime.datetime`: Returns the channel's creation time in UTC.""" - return utils.snowflake_time(self.id) - - def overwrites_for(self, obj: Union[Role, User, Object]) -> PermissionOverwrite: - """Returns the channel-specific overwrites for a member or a role. - - Parameters - ----------- - obj: Union[:class:`~discord.Role`, :class:`~discord.abc.User`, :class:`~discord.Object`] - The role or user denoting whose overwrite to get. - - Returns - --------- - :class:`~discord.PermissionOverwrite` - The permission overwrites for this object. - """ - - if isinstance(obj, User): - predicate = lambda p: p.is_member() - elif isinstance(obj, Role): - predicate = lambda p: p.is_role() - else: - predicate = lambda p: True - - for overwrite in filter(predicate, self._overwrites): - if overwrite.id == obj.id: - allow = Permissions(overwrite.allow) - deny = Permissions(overwrite.deny) - return PermissionOverwrite.from_pair(allow, deny) - - return PermissionOverwrite() - - @property - def overwrites(self) -> Dict[Union[Role, Member, Object], PermissionOverwrite]: - """Returns all of the channel's overwrites. - - This is returned as a dictionary where the key contains the target which - can be either a :class:`~discord.Role` or a :class:`~discord.Member` and the value is the - overwrite as a :class:`~discord.PermissionOverwrite`. - - .. versionchanged:: 2.0 - Overwrites can now be type-aware :class:`~discord.Object` in case of cache lookup failure - - Returns - -------- - Dict[Union[:class:`~discord.Role`, :class:`~discord.Member`, :class:`~discord.Object`], :class:`~discord.PermissionOverwrite`] - The channel's permission overwrites. - """ - ret = {} - for ow in self._overwrites: - allow = Permissions(ow.allow) - deny = Permissions(ow.deny) - overwrite = PermissionOverwrite.from_pair(allow, deny) - target = None - - if ow.is_role(): - target = self.guild.get_role(ow.id) - elif ow.is_member(): - target = self.guild.get_member(ow.id) - - if target is None: - target_type = Role if ow.is_role() else User - target = Object(id=ow.id, type=target_type) # type: ignore - - ret[target] = overwrite - return ret - - @property - def category(self) -> Optional[CategoryChannel]: - """Optional[:class:`~discord.CategoryChannel`]: The category this channel belongs to. - - If there is no category then this is ``None``. - """ - return self.guild.get_channel(self.category_id) # type: ignore # These are coerced into CategoryChannel - - @property - def permissions_synced(self) -> bool: - """:class:`bool`: Whether or not the permissions for this channel are synced with the - category it belongs to. - - If there is no category then this is ``False``. - - .. versionadded:: 1.3 - """ - if self.category_id is None: - return False - - category = self.guild.get_channel(self.category_id) - return bool(category and category.overwrites == self.overwrites) - - def permissions_for(self, obj: Union[Member, Role], /) -> Permissions: - """Handles permission resolution for the :class:`~discord.Member` - or :class:`~discord.Role`. - - This function takes into consideration the following cases: - - - Guild owner - - Guild roles - - Channel overrides - - Member overrides - - Member timeout - - If a :class:`~discord.Role` is passed, then it checks the permissions - someone with that role would have, which is essentially: - - - The default role permissions - - The permissions of the role used as a parameter - - The default role permission overwrites - - The permission overwrites of the role used as a parameter - - .. versionchanged:: 2.0 - The object passed in can now be a role object. - - .. versionchanged:: 2.0 - ``obj`` parameter is now positional-only. - - Parameters - ---------- - obj: Union[:class:`~discord.Member`, :class:`~discord.Role`] - The object to resolve permissions for. This could be either - a member or a role. If it's a role then member overwrites - are not computed. - - Returns - ------- - :class:`~discord.Permissions` - The resolved permissions for the member or role. - """ - - # The current cases can be explained as: - # Guild owner get all permissions -- no questions asked. Otherwise... - # The @everyone role gets the first application. - # After that, the applied roles that the user has in the channel - # (or otherwise) are then OR'd together. - # After the role permissions are resolved, the member permissions - # have to take into effect. - # After all that is done.. you have to do the following: - - # If manage permissions is True, then all permissions are set to True. - - # The operation first takes into consideration the denied - # and then the allowed. - - if self.guild.owner_id == obj.id: - return Permissions.all() - - default = self.guild.default_role - base = Permissions(default.permissions.value) - - # Handle the role case first - if isinstance(obj, Role): - base.value |= obj._permissions - - if base.administrator: - return Permissions.all() - - # Apply @everyone allow/deny first since it's special - try: - maybe_everyone = self._overwrites[0] - if maybe_everyone.id == self.guild.id: - base.handle_overwrite(allow=maybe_everyone.allow, deny=maybe_everyone.deny) - except IndexError: - pass - - if obj.is_default(): - return base - - overwrite = utils.get(self._overwrites, type=_Overwrites.ROLE, id=obj.id) - if overwrite is not None: - base.handle_overwrite(overwrite.allow, overwrite.deny) - - return base - - roles = obj._roles - get_role = self.guild.get_role - - # Apply guild roles that the member has. - for role_id in roles: - role = get_role(role_id) - if role is not None: - base.value |= role._permissions - - # Guild-wide Administrator -> True for everything - # Bypass all channel-specific overrides - if base.administrator: - return Permissions.all() - - # Apply @everyone allow/deny first since it's special - try: - maybe_everyone = self._overwrites[0] - if maybe_everyone.id == self.guild.id: - base.handle_overwrite(allow=maybe_everyone.allow, deny=maybe_everyone.deny) - remaining_overwrites = self._overwrites[1:] - else: - remaining_overwrites = self._overwrites - except IndexError: - remaining_overwrites = self._overwrites - - denies = 0 - allows = 0 - - # Apply channel specific role permission overwrites - for overwrite in remaining_overwrites: - if overwrite.is_role() and roles.has(overwrite.id): - denies |= overwrite.deny - allows |= overwrite.allow - - base.handle_overwrite(allow=allows, deny=denies) - - # Apply member specific permission overwrites - for overwrite in remaining_overwrites: - if overwrite.is_member() and overwrite.id == obj.id: - base.handle_overwrite(allow=overwrite.allow, deny=overwrite.deny) - break - - # if you can't send a message in a channel then you can't have certain - # permissions as well - if not base.send_messages: - base.send_tts_messages = False - base.mention_everyone = False - base.embed_links = False - base.attach_files = False - - # if you can't read a channel then you have no permissions there - if not base.read_messages: - denied = Permissions.all_channel() - base.value &= ~denied.value - - if obj.is_timed_out(): - # Timeout leads to every permission except VIEW_CHANNEL and READ_MESSAGE_HISTORY - # being explicitly denied - # N.B.: This *must* come last, because it's a conclusive mask - base.value &= Permissions._timeout_mask() - - return base - - async def delete(self, *, reason: Optional[str] = None) -> None: - """|coro| - - Deletes the channel. - - You must have :attr:`~discord.Permissions.manage_channels` permission to use this. - - Parameters - ----------- - reason: Optional[:class:`str`] - The reason for deleting this channel. - Shows up on the audit log. - - Raises - ------- - ~discord.Forbidden - You do not have proper permissions to delete the channel. - ~discord.NotFound - The channel was not found or was already deleted. - ~discord.HTTPException - Deleting the channel failed. - """ - await self._state.http.delete_channel(self.id, reason=reason) - - @overload - async def set_permissions( - self, - target: Union[Member, Role], - *, - overwrite: Optional[Union[PermissionOverwrite, _Undefined]] = ..., - reason: Optional[str] = ..., - ) -> None: - ... - - @overload - async def set_permissions( - self, - target: Union[Member, Role], - *, - reason: Optional[str] = ..., - **permissions: Optional[bool], - ) -> None: - ... - - async def set_permissions( - self, - target: Union[Member, Role], - *, - overwrite: Any = _undefined, - reason: Optional[str] = None, - **permissions: Optional[bool], - ) -> None: - r"""|coro| - - Sets the channel specific permission overwrites for a target in the - channel. - - The ``target`` parameter should either be a :class:`~discord.Member` or a - :class:`~discord.Role` that belongs to guild. - - The ``overwrite`` parameter, if given, must either be ``None`` or - :class:`~discord.PermissionOverwrite`. For convenience, you can pass in - keyword arguments denoting :class:`~discord.Permissions` attributes. If this is - done, then you cannot mix the keyword arguments with the ``overwrite`` - parameter. - - If the ``overwrite`` parameter is ``None``, then the permission - overwrites are deleted. - - You must have the :attr:`~discord.Permissions.manage_roles` permission to use this. - - .. note:: - - This method *replaces* the old overwrites with the ones given. - - Examples - ---------- - - Setting allow and deny: :: - - await message.channel.set_permissions(message.author, read_messages=True, - send_messages=False) - - Deleting overwrites :: - - await channel.set_permissions(member, overwrite=None) - - Using :class:`~discord.PermissionOverwrite` :: - - overwrite = discord.PermissionOverwrite() - overwrite.send_messages = False - overwrite.read_messages = True - await channel.set_permissions(member, overwrite=overwrite) - - .. versionchanged:: 2.0 - This function will now raise :exc:`TypeError` instead of - ``InvalidArgument``. - - - Parameters - ----------- - target: Union[:class:`~discord.Member`, :class:`~discord.Role`] - The member or role to overwrite permissions for. - overwrite: Optional[:class:`~discord.PermissionOverwrite`] - The permissions to allow and deny to the target, or ``None`` to - delete the overwrite. - \*\*permissions - A keyword argument list of permissions to set for ease of use. - Cannot be mixed with ``overwrite``. - reason: Optional[:class:`str`] - The reason for doing this action. Shows up on the audit log. - - Raises - ------- - ~discord.Forbidden - You do not have permissions to edit channel specific permissions. - ~discord.HTTPException - Editing channel specific permissions failed. - ~discord.NotFound - The role or member being edited is not part of the guild. - TypeError - The ``overwrite`` parameter was invalid or the target type was not - :class:`~discord.Role` or :class:`~discord.Member`. - ValueError - The ``overwrite`` parameter and ``positions`` parameters were both - unset. - """ - - http = self._state.http - - if isinstance(target, User): - perm_type = _Overwrites.MEMBER - elif isinstance(target, Role): - perm_type = _Overwrites.ROLE - else: - raise ValueError('target parameter must be either Member or Role') - - if overwrite is _undefined: - if len(permissions) == 0: - raise ValueError('No overwrite provided.') - try: - overwrite = PermissionOverwrite(**permissions) - except (ValueError, TypeError): - raise TypeError('Invalid permissions given to keyword arguments.') - else: - if len(permissions) > 0: - raise TypeError('Cannot mix overwrite and keyword arguments.') - - # TODO: wait for event - - if overwrite is None: - await http.delete_channel_permissions(self.id, target.id, reason=reason) - elif isinstance(overwrite, PermissionOverwrite): - (allow, deny) = overwrite.pair() - await http.edit_channel_permissions( - self.id, target.id, str(allow.value), str(deny.value), perm_type, reason=reason - ) - else: - raise TypeError('Invalid overwrite type provided.') - - async def _clone_impl( - self, - base_attrs: Dict[str, Any], - *, - name: Optional[str] = None, - reason: Optional[str] = None, - ) -> Self: - base_attrs['permission_overwrites'] = [x._asdict() for x in self._overwrites] - base_attrs['parent_id'] = self.category_id - base_attrs['name'] = name or self.name - guild_id = self.guild.id - cls = self.__class__ - data = await self._state.http.create_channel(guild_id, self.type.value, reason=reason, **base_attrs) - obj = cls(state=self._state, guild=self.guild, data=data) - - # temporarily add it to the cache - self.guild._channels[obj.id] = obj # type: ignore # obj is a GuildChannel - return obj - - async def clone(self, *, name: Optional[str] = None, reason: Optional[str] = None) -> Self: - """|coro| - - Clones this channel. This creates a channel with the same properties - as this channel. - - You must have the :attr:`~discord.Permissions.manage_channels` permission to - do this. - - .. versionadded:: 1.1 - - Parameters - ------------ - name: Optional[:class:`str`] - The name of the new channel. If not provided, defaults to this - channel name. - reason: Optional[:class:`str`] - The reason for cloning this channel. Shows up on the audit log. - - Raises - ------- - ~discord.Forbidden - You do not have the proper permissions to create this channel. - ~discord.HTTPException - Creating the channel failed. - - Returns - -------- - :class:`.abc.GuildChannel` - The channel that was created. - """ - raise NotImplementedError - - @overload - async def move( - self, - *, - beginning: bool, - offset: int = MISSING, - category: Optional[Snowflake] = MISSING, - sync_permissions: bool = MISSING, - reason: Optional[str] = MISSING, - ) -> None: - ... - - @overload - async def move( - self, - *, - end: bool, - offset: int = MISSING, - category: Optional[Snowflake] = MISSING, - sync_permissions: bool = MISSING, - reason: str = MISSING, - ) -> None: - ... - - @overload - async def move( - self, - *, - before: Snowflake, - offset: int = MISSING, - category: Optional[Snowflake] = MISSING, - sync_permissions: bool = MISSING, - reason: str = MISSING, - ) -> None: - ... - - @overload - async def move( - self, - *, - after: Snowflake, - offset: int = MISSING, - category: Optional[Snowflake] = MISSING, - sync_permissions: bool = MISSING, - reason: str = MISSING, - ) -> None: - ... - - async def move(self, **kwargs: Any) -> None: - """|coro| - - A rich interface to help move a channel relative to other channels. - - If exact position movement is required, ``edit`` should be used instead. - - You must have the :attr:`~discord.Permissions.manage_channels` permission to - do this. - - .. note:: - - Voice channels will always be sorted below text channels. - This is a Discord limitation. - - .. versionadded:: 1.7 - - .. versionchanged:: 2.0 - This function will now raise :exc:`TypeError` or - :exc:`ValueError` instead of ``InvalidArgument``. - - Parameters - ------------ - beginning: :class:`bool` - Whether to move the channel to the beginning of the - channel list (or category if given). - This is mutually exclusive with ``end``, ``before``, and ``after``. - end: :class:`bool` - Whether to move the channel to the end of the - channel list (or category if given). - This is mutually exclusive with ``beginning``, ``before``, and ``after``. - before: :class:`~discord.abc.Snowflake` - The channel that should be before our current channel. - This is mutually exclusive with ``beginning``, ``end``, and ``after``. - after: :class:`~discord.abc.Snowflake` - The channel that should be after our current channel. - This is mutually exclusive with ``beginning``, ``end``, and ``before``. - offset: :class:`int` - The number of channels to offset the move by. For example, - an offset of ``2`` with ``beginning=True`` would move - it 2 after the beginning. A positive number moves it below - while a negative number moves it above. Note that this - number is relative and computed after the ``beginning``, - ``end``, ``before``, and ``after`` parameters. - category: Optional[:class:`~discord.abc.Snowflake`] - The category to move this channel under. - If ``None`` is given then it moves it out of the category. - This parameter is ignored if moving a category channel. - sync_permissions: :class:`bool` - Whether to sync the permissions with the category (if given). - reason: :class:`str` - The reason for the move. - - Raises - ------- - ValueError - An invalid position was given. - TypeError - A bad mix of arguments were passed. - Forbidden - You do not have permissions to move the channel. - HTTPException - Moving the channel failed. - """ - - if not kwargs: - return - - beginning, end = kwargs.get('beginning'), kwargs.get('end') - before, after = kwargs.get('before'), kwargs.get('after') - offset = kwargs.get('offset', 0) - if sum(bool(a) for a in (beginning, end, before, after)) > 1: - raise TypeError('Only one of [before, after, end, beginning] can be used.') - - bucket = self._sorting_bucket - parent_id = kwargs.get('category', MISSING) - # fmt: off - channels: List[GuildChannel] - if parent_id not in (MISSING, None): - parent_id = parent_id.id - channels = [ - ch - for ch in self.guild.channels - if ch._sorting_bucket == bucket - and ch.category_id == parent_id - ] - else: - channels = [ - ch - for ch in self.guild.channels - if ch._sorting_bucket == bucket - and ch.category_id == self.category_id - ] - # fmt: on - - channels.sort(key=lambda c: (c.position, c.id)) - - try: - # Try to remove ourselves from the channel list - channels.remove(self) - except ValueError: - # If we're not there then it's probably due to not being in the category - pass - - index = None - if beginning: - index = 0 - elif end: - index = len(channels) - elif before: - index = next((i for i, c in enumerate(channels) if c.id == before.id), None) - elif after: - index = next((i + 1 for i, c in enumerate(channels) if c.id == after.id), None) - - if index is None: - raise ValueError('Could not resolve appropriate move position') - - channels.insert(max((index + offset), 0), self) - payload = [] - lock_permissions = kwargs.get('sync_permissions', False) - reason = kwargs.get('reason') - for index, channel in enumerate(channels): - d = {'id': channel.id, 'position': index} - if parent_id is not MISSING and channel.id == self.id: - d.update(parent_id=parent_id, lock_permissions=lock_permissions) - payload.append(d) - - await self._state.http.bulk_channel_update(self.guild.id, payload, reason=reason) - - async def create_invite( - self, - *, - reason: Optional[str] = None, - max_age: int = 0, - max_uses: int = 0, - temporary: bool = False, - unique: bool = True, - target_type: Optional[InviteTarget] = None, - target_user: Optional[User] = None, - target_application_id: Optional[int] = None, - ) -> Invite: - """|coro| - - Creates an instant invite from a text or voice channel. - - You must have the :attr:`~discord.Permissions.create_instant_invite` permission to - do this. - - Parameters - ------------ - max_age: :class:`int` - How long the invite should last in seconds. If it's 0 then the invite - doesn't expire. Defaults to ``0``. - max_uses: :class:`int` - How many uses the invite could be used for. If it's 0 then there - are unlimited uses. Defaults to ``0``. - temporary: :class:`bool` - Denotes that the invite grants temporary membership - (i.e. they get kicked after they disconnect). Defaults to ``False``. - unique: :class:`bool` - Indicates if a unique invite URL should be created. Defaults to True. - If this is set to ``False`` then it will return a previously created - invite. - reason: Optional[:class:`str`] - The reason for creating this invite. Shows up on the audit log. - target_type: Optional[:class:`.InviteTarget`] - The type of target for the voice channel invite, if any. - - .. versionadded:: 2.0 - - target_user: Optional[:class:`User`] - The user whose stream to display for this invite, required if `target_type` is `TargetType.stream`. The user must be streaming in the channel. - - .. versionadded:: 2.0 - - target_application_id:: Optional[:class:`int`] - The id of the embedded application for the invite, required if `target_type` is `TargetType.embedded_application`. - - .. versionadded:: 2.0 - - Raises - ------- - ~discord.HTTPException - Invite creation failed. - - ~discord.NotFound - The channel that was passed is a category or an invalid channel. - - Returns - -------- - :class:`~discord.Invite` - The invite that was created. - """ - - data = await self._state.http.create_invite( - self.id, - reason=reason, - max_age=max_age, - max_uses=max_uses, - temporary=temporary, - unique=unique, - target_type=target_type.value if target_type else None, - target_user_id=target_user.id if target_user else None, - target_application_id=target_application_id, - ) - return Invite.from_incomplete(data=data, state=self._state) - - async def invites(self) -> List[Invite]: - """|coro| - - Returns a list of all active instant invites from this channel. - - You must have :attr:`~discord.Permissions.manage_channels` to get this information. - - Raises - ------- - ~discord.Forbidden - You do not have proper permissions to get the information. - ~discord.HTTPException - An error occurred while fetching the information. - - Returns - ------- - List[:class:`~discord.Invite`] - The list of invites that are currently active. - """ - - state = self._state - data = await state.http.invites_from_channel(self.id) - guild = self.guild - return [Invite(state=state, data=invite, channel=self, guild=guild) for invite in data] - - -class Messageable: - """An ABC that details the common operations on a model that can send messages. - - The following classes implement this ABC: - - - :class:`~discord.TextChannel` - - :class:`~discord.VoiceChannel` - - :class:`~discord.DMChannel` - - :class:`~discord.GroupChannel` - - :class:`~discord.PartialMessageable` - - :class:`~discord.User` - - :class:`~discord.Member` - - :class:`~discord.ext.commands.Context` - - :class:`~discord.Thread` - """ - - __slots__ = () - _state: ConnectionState - - async def _get_channel(self) -> MessageableChannel: - raise NotImplementedError - - @overload - async def send( - self, - content: Optional[str] = ..., - *, - tts: bool = ..., - embed: Embed = ..., - file: File = ..., - stickers: Sequence[Union[GuildSticker, StickerItem]] = ..., - delete_after: float = ..., - nonce: Union[str, int] = ..., - allowed_mentions: AllowedMentions = ..., - reference: Union[Message, MessageReference, PartialMessage] = ..., - mention_author: bool = ..., - view: View = ..., - suppress_embeds: bool = ..., - ) -> Message: - ... - - @overload - async def send( - self, - content: Optional[str] = ..., - *, - tts: bool = ..., - embed: Embed = ..., - files: Sequence[File] = ..., - stickers: Sequence[Union[GuildSticker, StickerItem]] = ..., - delete_after: float = ..., - nonce: Union[str, int] = ..., - allowed_mentions: AllowedMentions = ..., - reference: Union[Message, MessageReference, PartialMessage] = ..., - mention_author: bool = ..., - view: View = ..., - suppress_embeds: bool = ..., - ) -> Message: - ... - - @overload - async def send( - self, - content: Optional[str] = ..., - *, - tts: bool = ..., - embeds: Sequence[Embed] = ..., - file: File = ..., - stickers: Sequence[Union[GuildSticker, StickerItem]] = ..., - delete_after: float = ..., - nonce: Union[str, int] = ..., - allowed_mentions: AllowedMentions = ..., - reference: Union[Message, MessageReference, PartialMessage] = ..., - mention_author: bool = ..., - view: View = ..., - suppress_embeds: bool = ..., - ) -> Message: - ... - - @overload - async def send( - self, - content: Optional[str] = ..., - *, - tts: bool = ..., - embeds: Sequence[Embed] = ..., - files: Sequence[File] = ..., - stickers: Sequence[Union[GuildSticker, StickerItem]] = ..., - delete_after: float = ..., - nonce: Union[str, int] = ..., - allowed_mentions: AllowedMentions = ..., - reference: Union[Message, MessageReference, PartialMessage] = ..., - mention_author: bool = ..., - view: View = ..., - suppress_embeds: bool = ..., - ) -> Message: - ... - - async def send( - self, - content: Optional[str] = None, - *, - tts: bool = False, - embed: Optional[Embed] = None, - embeds: Optional[Sequence[Embed]] = None, - file: Optional[File] = None, - files: Optional[Sequence[File]] = None, - stickers: Optional[Sequence[Union[GuildSticker, StickerItem]]] = None, - delete_after: Optional[float] = None, - nonce: Optional[Union[str, int]] = None, - allowed_mentions: Optional[AllowedMentions] = None, - reference: Optional[Union[Message, MessageReference, PartialMessage]] = None, - mention_author: Optional[bool] = None, - view: Optional[View] = None, - suppress_embeds: bool = False, - ) -> Message: - """|coro| - - Sends a message to the destination with the content given. - - The content must be a type that can convert to a string through ``str(content)``. - If the content is set to ``None`` (the default), then the ``embed`` parameter must - be provided. - - To upload a single file, the ``file`` parameter should be used with a - single :class:`~discord.File` object. To upload multiple files, the ``files`` - parameter should be used with a :class:`list` of :class:`~discord.File` objects. - **Specifying both parameters will lead to an exception**. - - To upload a single embed, the ``embed`` parameter should be used with a - single :class:`~discord.Embed` object. To upload multiple embeds, the ``embeds`` - parameter should be used with a :class:`list` of :class:`~discord.Embed` objects. - **Specifying both parameters will lead to an exception**. - - .. versionchanged:: 2.0 - This function will now raise :exc:`TypeError` or - :exc:`ValueError` instead of ``InvalidArgument``. - - Parameters - ------------ - content: Optional[:class:`str`] - The content of the message to send. - tts: :class:`bool` - Indicates if the message should be sent using text-to-speech. - embed: :class:`~discord.Embed` - The rich embed for the content. - embeds: List[:class:`~discord.Embed`] - A list of embeds to upload. Must be a maximum of 10. - - .. versionadded:: 2.0 - file: :class:`~discord.File` - The file to upload. - files: List[:class:`~discord.File`] - A list of files to upload. Must be a maximum of 10. - nonce: :class:`int` - The nonce to use for sending this message. If the message was successfully sent, - then the message will have a nonce with this value. - delete_after: :class:`float` - If provided, the number of seconds to wait in the background - before deleting the message we just sent. If the deletion fails, - then it is silently ignored. - allowed_mentions: :class:`~discord.AllowedMentions` - Controls the mentions being processed in this message. If this is - passed, then the object is merged with :attr:`~discord.Client.allowed_mentions`. - The merging behaviour only overrides attributes that have been explicitly passed - to the object, otherwise it uses the attributes set in :attr:`~discord.Client.allowed_mentions`. - If no object is passed at all then the defaults given by :attr:`~discord.Client.allowed_mentions` - are used instead. - - .. versionadded:: 1.4 - - reference: Union[:class:`~discord.Message`, :class:`~discord.MessageReference`, :class:`~discord.PartialMessage`] - A reference to the :class:`~discord.Message` to which you are replying, this can be created using - :meth:`~discord.Message.to_reference` or passed directly as a :class:`~discord.Message`. You can control - whether this mentions the author of the referenced message using the :attr:`~discord.AllowedMentions.replied_user` - attribute of ``allowed_mentions`` or by setting ``mention_author``. - - .. versionadded:: 1.6 - - mention_author: Optional[:class:`bool`] - If set, overrides the :attr:`~discord.AllowedMentions.replied_user` attribute of ``allowed_mentions``. - - .. versionadded:: 1.6 - view: :class:`discord.ui.View` - A Discord UI View to add to the message. - - .. versionadded:: 2.0 - stickers: Sequence[Union[:class:`~discord.GuildSticker`, :class:`~discord.StickerItem`]] - A list of stickers to upload. Must be a maximum of 3. - - .. versionadded:: 2.0 - suppress_embeds: :class:`bool` - Whether to suppress embeds for the message. This sends the message without any embeds if set to ``True``. - - .. versionadded:: 2.0 - - Raises - -------- - ~discord.HTTPException - Sending the message failed. - ~discord.Forbidden - You do not have the proper permissions to send the message. - ValueError - The ``files`` or ``embeds`` list is not of the appropriate size. - TypeError - You specified both ``file`` and ``files``, - or you specified both ``embed`` and ``embeds``, - or the ``reference`` object is not a :class:`~discord.Message`, - :class:`~discord.MessageReference` or :class:`~discord.PartialMessage`. - - Returns - --------- - :class:`~discord.Message` - The message that was sent. - """ - - channel = await self._get_channel() - state = self._state - content = str(content) if content is not None else None - previous_allowed_mention = state.allowed_mentions - - if stickers is not None: - sticker_ids: SnowflakeList = [sticker.id for sticker in stickers] - else: - sticker_ids = MISSING - - if reference is not None: - try: - reference_dict = reference.to_message_reference_dict() - except AttributeError: - raise TypeError('reference parameter must be Message, MessageReference, or PartialMessage') from None - else: - reference_dict = MISSING - - if view and not hasattr(view, '__discord_ui_view__'): - raise TypeError(f'view parameter must be View not {view.__class__!r}') - - if suppress_embeds: - from .message import MessageFlags # circular import - - flags = MessageFlags._from_value(4) - else: - flags = MISSING - - with handle_message_parameters( - content=content, - tts=tts, - file=file if file is not None else MISSING, - files=files if files is not None else MISSING, - embed=embed if embed is not None else MISSING, - embeds=embeds if embeds is not None else MISSING, - nonce=nonce, - allowed_mentions=allowed_mentions, - message_reference=reference_dict, - previous_allowed_mentions=previous_allowed_mention, - mention_author=mention_author, - stickers=sticker_ids, - view=view, - flags=flags, - ) as params: - data = await state.http.send_message(channel.id, params=params) - - ret = state.create_message(channel=channel, data=data) - if view: - state.store_view(view, ret.id) - - if delete_after is not None: - await ret.delete(delay=delete_after) - return ret - - def typing(self) -> Typing: - """Returns an asynchronous context manager that allows you to send a typing indicator to - the destination for an indefinite period of time, or 10 seconds if the context manager - is called using ``await``. - - Example Usage: :: - - async with channel.typing(): - # simulate something heavy - await asyncio.sleep(20) - - await channel.send('Done!') - - Example Usage: :: - - await channel.typing() - # Do some computational magic for about 10 seconds - await channel.send('Done!') - - .. versionchanged:: 2.0 - This no longer works with the ``with`` syntax, ``async with`` must be used instead. - - .. versionchanged:: 2.0 - Added functionality to ``await`` the context manager to send a typing indicator for 10 seconds. - """ - return Typing(self) - - async def fetch_message(self, id: int, /) -> Message: - """|coro| - - Retrieves a single :class:`~discord.Message` from the destination. - - Parameters - ------------ - id: :class:`int` - The message ID to look for. - - Raises - -------- - ~discord.NotFound - The specified message was not found. - ~discord.Forbidden - You do not have the permissions required to get a message. - ~discord.HTTPException - Retrieving the message failed. - - Returns - -------- - :class:`~discord.Message` - The message asked for. - """ - - channel = await self._get_channel() - data = await self._state.http.get_message(channel.id, id) - return self._state.create_message(channel=channel, data=data) - - async def pins(self) -> List[Message]: - """|coro| - - Retrieves all messages that are currently pinned in the channel. - - .. note:: - - Due to a limitation with the Discord API, the :class:`.Message` - objects returned by this method do not contain complete - :attr:`.Message.reactions` data. - - Raises - ------- - ~discord.Forbidden - You do not have the permission to retrieve pinned messages. - ~discord.HTTPException - Retrieving the pinned messages failed. - - Returns - -------- - List[:class:`~discord.Message`] - The messages that are currently pinned. - """ - - channel = await self._get_channel() - state = self._state - data = await state.http.pins_from(channel.id) - return [state.create_message(channel=channel, data=m) for m in data] - - async def history( - self, - *, - limit: Optional[int] = 100, - before: Optional[SnowflakeTime] = None, - after: Optional[SnowflakeTime] = None, - around: Optional[SnowflakeTime] = None, - oldest_first: Optional[bool] = None, - ) -> AsyncIterator[Message]: - """Returns an :term:`asynchronous iterator` that enables receiving the destination's message history. - - You must have :attr:`~discord.Permissions.read_message_history` permissions to use this. - - Examples - --------- - - Usage :: - - counter = 0 - async for message in channel.history(limit=200): - if message.author == client.user: - counter += 1 - - Flattening into a list: :: - - messages = [message async for message in channel.history(limit=123)] - # messages is now a list of Message... - - All parameters are optional. - - Parameters - ----------- - limit: Optional[:class:`int`] - The number of messages to retrieve. - If ``None``, retrieves every message in the channel. Note, however, - that this would make it a slow operation. - before: Optional[Union[:class:`~discord.abc.Snowflake`, :class:`datetime.datetime`]] - Retrieve messages before this date or message. - If a datetime is provided, it is recommended to use a UTC aware datetime. - If the datetime is naive, it is assumed to be local time. - after: Optional[Union[:class:`~discord.abc.Snowflake`, :class:`datetime.datetime`]] - Retrieve messages after this date or message. - If a datetime is provided, it is recommended to use a UTC aware datetime. - If the datetime is naive, it is assumed to be local time. - around: Optional[Union[:class:`~discord.abc.Snowflake`, :class:`datetime.datetime`]] - Retrieve messages around this date or message. - If a datetime is provided, it is recommended to use a UTC aware datetime. - If the datetime is naive, it is assumed to be local time. - When using this argument, the maximum limit is 101. Note that if the limit is an - even number then this will return at most limit + 1 messages. - oldest_first: Optional[:class:`bool`] - If set to ``True``, return messages in oldest->newest order. Defaults to ``True`` if - ``after`` is specified, otherwise ``False``. - - Raises - ------ - ~discord.Forbidden - You do not have permissions to get channel message history. - ~discord.HTTPException - The request to get message history failed. - - Yields - ------- - :class:`~discord.Message` - The message with the message data parsed. - """ - - async def _around_strategy(retrieve: int, around: Optional[Snowflake], limit: Optional[int]): - if not around: - return [] - - around_id = around.id if around else None - data = await self._state.http.logs_from(channel.id, retrieve, around=around_id) - - return data, None, limit - - async def _after_strategy(retrieve: int, after: Optional[Snowflake], limit: Optional[int]): - after_id = after.id if after else None - data = await self._state.http.logs_from(channel.id, retrieve, after=after_id) - - if data: - if limit is not None: - limit -= len(data) - - after = Object(id=int(data[0]['id'])) - - return data, after, limit - - async def _before_strategy(retrieve: int, before: Optional[Snowflake], limit: Optional[int]): - before_id = before.id if before else None - data = await self._state.http.logs_from(channel.id, retrieve, before=before_id) - - if data: - if limit is not None: - limit -= len(data) - - before = Object(id=int(data[-1]['id'])) - - return data, before, limit - - if isinstance(before, datetime): - before = Object(id=utils.time_snowflake(before, high=False)) - if isinstance(after, datetime): - after = Object(id=utils.time_snowflake(after, high=True)) - if isinstance(around, datetime): - around = Object(id=utils.time_snowflake(around)) - - if oldest_first is None: - reverse = after is not None - else: - reverse = oldest_first - - after = after or OLDEST_OBJECT - predicate = None - - if around: - if limit is None: - raise ValueError('history does not support around with limit=None') - if limit > 101: - raise ValueError("history max limit 101 when specifying around parameter") - - # Strange Discord quirk - limit = 100 if limit == 101 else limit - - strategy, state = _around_strategy, around - - if before and after: - predicate = lambda m: after.id < int(m['id']) < before.id - elif before: - predicate = lambda m: int(m['id']) < before.id - elif after: - predicate = lambda m: after.id < int(m['id']) - elif reverse: - strategy, state = _after_strategy, after - if before: - predicate = lambda m: int(m['id']) < before.id - else: - strategy, state = _before_strategy, before - if after and after != OLDEST_OBJECT: - predicate = lambda m: int(m['id']) > after.id - - channel = await self._get_channel() - - while True: - retrieve = min(100 if limit is None else limit, 100) - if retrieve < 1: - return - - data, state, limit = await strategy(retrieve, state, limit) - - # Terminate loop on next iteration; there's no data left after this - if len(data) < 100: - limit = 0 - - if reverse: - data = reversed(data) - if predicate: - data = filter(predicate, data) - - for raw_message in data: - yield self._state.create_message(channel=channel, data=raw_message) - - -class Connectable(Protocol): - """An ABC that details the common operations on a channel that can - connect to a voice server. - - The following implement this ABC: - - - :class:`~discord.VoiceChannel` - - :class:`~discord.StageChannel` - """ - - __slots__ = () - _state: ConnectionState - - def _get_voice_client_key(self) -> Tuple[int, str]: - raise NotImplementedError - - def _get_voice_state_pair(self) -> Tuple[int, int]: - raise NotImplementedError - - async def connect( - self, - *, - timeout: float = 60.0, - reconnect: bool = True, - cls: Callable[[Client, Connectable], T] = VoiceClient, - self_deaf: bool = False, - self_mute: bool = False, - ) -> T: - """|coro| - - Connects to voice and creates a :class:`~discord.VoiceClient` to establish - your connection to the voice server. - - This requires :attr:`~discord.Intents.voice_states`. - - Parameters - ----------- - timeout: :class:`float` - The timeout in seconds to wait for the voice endpoint. - reconnect: :class:`bool` - Whether the bot should automatically attempt - a reconnect if a part of the handshake fails - or the gateway goes down. - cls: Type[:class:`~discord.VoiceProtocol`] - A type that subclasses :class:`~discord.VoiceProtocol` to connect with. - Defaults to :class:`~discord.VoiceClient`. - self_mute: :class:`bool` - Indicates if the client should be self-muted. - - .. versionadded:: 2.0 - self_deaf: :class:`bool` - Indicates if the client should be self-deafened. - - .. versionadded:: 2.0 - - Raises - ------- - asyncio.TimeoutError - Could not connect to the voice channel in time. - ~discord.ClientException - You are already connected to a voice channel. - ~discord.opus.OpusNotLoaded - The opus library has not been loaded. - - Returns - -------- - :class:`~discord.VoiceProtocol` - A voice client that is fully connected to the voice server. - """ - - key_id, _ = self._get_voice_client_key() - state = self._state - - if state._get_voice_client(key_id): - raise ClientException('Already connected to a voice channel.') - - client = state._get_client() - voice: T = cls(client, self) - - if not isinstance(voice, VoiceProtocol): - raise TypeError('Type must meet VoiceProtocol abstract base class.') - - state._add_voice_client(key_id, voice) - - try: - await voice.connect(timeout=timeout, reconnect=reconnect, self_deaf=self_deaf, self_mute=self_mute) - except asyncio.TimeoutError: - try: - await voice.disconnect(force=True) - except Exception: - # we don't care if disconnect failed because connection failed - pass - raise # re-raise - - return voice diff --git a/.venv/Lib/site-packages/discord/activity.py b/.venv/Lib/site-packages/discord/activity.py deleted file mode 100644 index 5e97300..0000000 --- a/.venv/Lib/site-packages/discord/activity.py +++ /dev/null @@ -1,842 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations - -import datetime -from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union, overload - -from .asset import Asset -from .enums import ActivityType, try_enum -from .colour import Colour -from .partial_emoji import PartialEmoji -from .utils import _get_as_snowflake - -__all__ = ( - 'BaseActivity', - 'Activity', - 'Streaming', - 'Game', - 'Spotify', - 'CustomActivity', -) - -"""If curious, this is the current schema for an activity. - -It's fairly long so I will document it here: - -All keys are optional. - -state: str (max: 128), -details: str (max: 128) -timestamps: dict - start: int (min: 1) - end: int (min: 1) -assets: dict - large_image: str (max: 32) - large_text: str (max: 128) - small_image: str (max: 32) - small_text: str (max: 128) -party: dict - id: str (max: 128), - size: List[int] (max-length: 2) - elem: int (min: 1) -secrets: dict - match: str (max: 128) - join: str (max: 128) - spectate: str (max: 128) -instance: bool -application_id: str -name: str (max: 128) -url: str -type: int -sync_id: str -session_id: str -flags: int -buttons: list[str (max: 32)] - -There are also activity flags which are mostly uninteresting for the library atm. - -t.ActivityFlags = { - INSTANCE: 1, - JOIN: 2, - SPECTATE: 4, - JOIN_REQUEST: 8, - SYNC: 16, - PLAY: 32 -} -""" - -if TYPE_CHECKING: - from .types.activity import ( - Activity as ActivityPayload, - ActivityTimestamps, - ActivityParty, - ActivityAssets, - ) - - from .state import ConnectionState - - -class BaseActivity: - """The base activity that all user-settable activities inherit from. - A user-settable activity is one that can be used in :meth:`Client.change_presence`. - - The following types currently count as user-settable: - - - :class:`Activity` - - :class:`Game` - - :class:`Streaming` - - :class:`CustomActivity` - - Note that although these types are considered user-settable by the library, - Discord typically ignores certain combinations of activity depending on - what is currently set. This behaviour may change in the future so there are - no guarantees on whether Discord will actually let you set these types. - - .. versionadded:: 1.3 - """ - - __slots__ = ('_created_at',) - - def __init__(self, **kwargs: Any) -> None: - self._created_at: Optional[float] = kwargs.pop('created_at', None) - - @property - def created_at(self) -> Optional[datetime.datetime]: - """Optional[:class:`datetime.datetime`]: When the user started doing this activity in UTC. - - .. versionadded:: 1.3 - """ - if self._created_at is not None: - return datetime.datetime.fromtimestamp(self._created_at / 1000, tz=datetime.timezone.utc) - - def to_dict(self) -> ActivityPayload: - raise NotImplementedError - - -class Activity(BaseActivity): - """Represents an activity in Discord. - - This could be an activity such as streaming, playing, listening - or watching. - - For memory optimisation purposes, some activities are offered in slimmed - down versions: - - - :class:`Game` - - :class:`Streaming` - - Attributes - ------------ - application_id: Optional[:class:`int`] - The application ID of the game. - name: Optional[:class:`str`] - The name of the activity. - url: Optional[:class:`str`] - A stream URL that the activity could be doing. - type: :class:`ActivityType` - The type of activity currently being done. - state: Optional[:class:`str`] - The user's current state. For example, "In Game". - details: Optional[:class:`str`] - The detail of the user's current activity. - timestamps: :class:`dict` - A dictionary of timestamps. It contains the following optional keys: - - - ``start``: Corresponds to when the user started doing the - activity in milliseconds since Unix epoch. - - ``end``: Corresponds to when the user will finish doing the - activity in milliseconds since Unix epoch. - - assets: :class:`dict` - A dictionary representing the images and their hover text of an activity. - It contains the following optional keys: - - - ``large_image``: A string representing the ID for the large image asset. - - ``large_text``: A string representing the text when hovering over the large image asset. - - ``small_image``: A string representing the ID for the small image asset. - - ``small_text``: A string representing the text when hovering over the small image asset. - - party: :class:`dict` - A dictionary representing the activity party. It contains the following optional keys: - - - ``id``: A string representing the party ID. - - ``size``: A list of up to two integer elements denoting (current_size, maximum_size). - buttons: List[:class:`str`] - A list of strings representing the labels of custom buttons shown in a rich presence. - - .. versionadded:: 2.0 - - emoji: Optional[:class:`PartialEmoji`] - The emoji that belongs to this activity. - """ - - __slots__ = ( - 'state', - 'details', - 'timestamps', - 'assets', - 'party', - 'flags', - 'sync_id', - 'session_id', - 'type', - 'name', - 'url', - 'application_id', - 'emoji', - 'buttons', - ) - - def __init__(self, **kwargs: Any) -> None: - super().__init__(**kwargs) - self.state: Optional[str] = kwargs.pop('state', None) - self.details: Optional[str] = kwargs.pop('details', None) - self.timestamps: ActivityTimestamps = kwargs.pop('timestamps', {}) - self.assets: ActivityAssets = kwargs.pop('assets', {}) - self.party: ActivityParty = kwargs.pop('party', {}) - self.application_id: Optional[int] = _get_as_snowflake(kwargs, 'application_id') - self.name: Optional[str] = kwargs.pop('name', None) - self.url: Optional[str] = kwargs.pop('url', None) - self.flags: int = kwargs.pop('flags', 0) - self.sync_id: Optional[str] = kwargs.pop('sync_id', None) - self.session_id: Optional[str] = kwargs.pop('session_id', None) - self.buttons: List[str] = kwargs.pop('buttons', []) - - activity_type = kwargs.pop('type', -1) - self.type: ActivityType = ( - activity_type if isinstance(activity_type, ActivityType) else try_enum(ActivityType, activity_type) - ) - - emoji = kwargs.pop('emoji', None) - self.emoji: Optional[PartialEmoji] = PartialEmoji.from_dict(emoji) if emoji is not None else None - - def __repr__(self) -> str: - attrs = ( - ('type', self.type), - ('name', self.name), - ('url', self.url), - ('details', self.details), - ('application_id', self.application_id), - ('session_id', self.session_id), - ('emoji', self.emoji), - ) - inner = ' '.join('%s=%r' % t for t in attrs) - return f'' - - def to_dict(self) -> Dict[str, Any]: - ret: Dict[str, Any] = {} - for attr in self.__slots__: - value = getattr(self, attr, None) - if value is None: - continue - - if isinstance(value, dict) and len(value) == 0: - continue - - ret[attr] = value - ret['type'] = int(self.type) - if self.emoji: - ret['emoji'] = self.emoji.to_dict() - return ret - - @property - def start(self) -> Optional[datetime.datetime]: - """Optional[:class:`datetime.datetime`]: When the user started doing this activity in UTC, if applicable.""" - try: - timestamp = self.timestamps['start'] / 1000 - except KeyError: - return None - else: - return datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc) - - @property - def end(self) -> Optional[datetime.datetime]: - """Optional[:class:`datetime.datetime`]: When the user will stop doing this activity in UTC, if applicable.""" - try: - timestamp = self.timestamps['end'] / 1000 - except KeyError: - return None - else: - return datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc) - - @property - def large_image_url(self) -> Optional[str]: - """Optional[:class:`str`]: Returns a URL pointing to the large image asset of this activity, if applicable.""" - try: - large_image = self.assets['large_image'] - except KeyError: - return None - else: - return self._image_url(large_image) - - @property - def small_image_url(self) -> Optional[str]: - """Optional[:class:`str`]: Returns a URL pointing to the small image asset of this activity, if applicable.""" - try: - small_image = self.assets['small_image'] - except KeyError: - return None - else: - return self._image_url(small_image) - - def _image_url(self, image: str) -> Optional[str]: - if image.startswith('mp:'): - return f'https://media.discordapp.net/{image[3:]}' - elif self.application_id is not None: - return Asset.BASE + f'/app-assets/{self.application_id}/{image}.png' - - @property - def large_image_text(self) -> Optional[str]: - """Optional[:class:`str`]: Returns the large image asset hover text of this activity, if applicable.""" - return self.assets.get('large_text', None) - - @property - def small_image_text(self) -> Optional[str]: - """Optional[:class:`str`]: Returns the small image asset hover text of this activity, if applicable.""" - return self.assets.get('small_text', None) - - -class Game(BaseActivity): - """A slimmed down version of :class:`Activity` that represents a Discord game. - - This is typically displayed via **Playing** on the official Discord client. - - .. container:: operations - - .. describe:: x == y - - Checks if two games are equal. - - .. describe:: x != y - - Checks if two games are not equal. - - .. describe:: hash(x) - - Returns the game's hash. - - .. describe:: str(x) - - Returns the game's name. - - Parameters - ----------- - name: :class:`str` - The game's name. - - Attributes - ----------- - name: :class:`str` - The game's name. - """ - - __slots__ = ('name', '_end', '_start') - - def __init__(self, name: str, **extra: Any) -> None: - super().__init__(**extra) - self.name: str = name - - try: - timestamps: ActivityTimestamps = extra['timestamps'] - except KeyError: - self._start = 0 - self._end = 0 - else: - self._start = timestamps.get('start', 0) - self._end = timestamps.get('end', 0) - - @property - def type(self) -> ActivityType: - """:class:`ActivityType`: Returns the game's type. This is for compatibility with :class:`Activity`. - - It always returns :attr:`ActivityType.playing`. - """ - return ActivityType.playing - - @property - def start(self) -> Optional[datetime.datetime]: - """Optional[:class:`datetime.datetime`]: When the user started playing this game in UTC, if applicable.""" - if self._start: - return datetime.datetime.fromtimestamp(self._start / 1000, tz=datetime.timezone.utc) - return None - - @property - def end(self) -> Optional[datetime.datetime]: - """Optional[:class:`datetime.datetime`]: When the user will stop playing this game in UTC, if applicable.""" - if self._end: - return datetime.datetime.fromtimestamp(self._end / 1000, tz=datetime.timezone.utc) - return None - - def __str__(self) -> str: - return str(self.name) - - def __repr__(self) -> str: - return f'' - - def to_dict(self) -> Dict[str, Any]: - timestamps: Dict[str, Any] = {} - if self._start: - timestamps['start'] = self._start - - if self._end: - timestamps['end'] = self._end - - return { - 'type': ActivityType.playing.value, - 'name': str(self.name), - 'timestamps': timestamps, - } - - def __eq__(self, other: object) -> bool: - return isinstance(other, Game) and other.name == self.name - - def __ne__(self, other: object) -> bool: - return not self.__eq__(other) - - def __hash__(self) -> int: - return hash(self.name) - - -class Streaming(BaseActivity): - """A slimmed down version of :class:`Activity` that represents a Discord streaming status. - - This is typically displayed via **Streaming** on the official Discord client. - - .. container:: operations - - .. describe:: x == y - - Checks if two streams are equal. - - .. describe:: x != y - - Checks if two streams are not equal. - - .. describe:: hash(x) - - Returns the stream's hash. - - .. describe:: str(x) - - Returns the stream's name. - - Attributes - ----------- - platform: Optional[:class:`str`] - Where the user is streaming from (ie. YouTube, Twitch). - - .. versionadded:: 1.3 - - name: Optional[:class:`str`] - The stream's name. - details: Optional[:class:`str`] - An alias for :attr:`name` - game: Optional[:class:`str`] - The game being streamed. - - .. versionadded:: 1.3 - - url: :class:`str` - The stream's URL. - assets: :class:`dict` - A dictionary comprising of similar keys than those in :attr:`Activity.assets`. - """ - - __slots__ = ('platform', 'name', 'game', 'url', 'details', 'assets') - - def __init__(self, *, name: Optional[str], url: str, **extra: Any) -> None: - super().__init__(**extra) - self.platform: Optional[str] = name - self.name: Optional[str] = extra.pop('details', name) - self.game: Optional[str] = extra.pop('state', None) - self.url: str = url - self.details: Optional[str] = extra.pop('details', self.name) # compatibility - self.assets: ActivityAssets = extra.pop('assets', {}) - - @property - def type(self) -> ActivityType: - """:class:`ActivityType`: Returns the game's type. This is for compatibility with :class:`Activity`. - - It always returns :attr:`ActivityType.streaming`. - """ - return ActivityType.streaming - - def __str__(self) -> str: - return str(self.name) - - def __repr__(self) -> str: - return f'' - - @property - def twitch_name(self) -> Optional[str]: - """Optional[:class:`str`]: If provided, the twitch name of the user streaming. - - This corresponds to the ``large_image`` key of the :attr:`Streaming.assets` - dictionary if it starts with ``twitch:``. Typically set by the Discord client. - """ - - try: - name = self.assets['large_image'] - except KeyError: - return None - else: - return name[7:] if name[:7] == 'twitch:' else None - - def to_dict(self) -> Dict[str, Any]: - ret: Dict[str, Any] = { - 'type': ActivityType.streaming.value, - 'name': str(self.name), - 'url': str(self.url), - 'assets': self.assets, - } - if self.details: - ret['details'] = self.details - return ret - - def __eq__(self, other: object) -> bool: - return isinstance(other, Streaming) and other.name == self.name and other.url == self.url - - def __ne__(self, other: object) -> bool: - return not self.__eq__(other) - - def __hash__(self) -> int: - return hash(self.name) - - -class Spotify: - """Represents a Spotify listening activity from Discord. This is a special case of - :class:`Activity` that makes it easier to work with the Spotify integration. - - .. container:: operations - - .. describe:: x == y - - Checks if two activities are equal. - - .. describe:: x != y - - Checks if two activities are not equal. - - .. describe:: hash(x) - - Returns the activity's hash. - - .. describe:: str(x) - - Returns the string 'Spotify'. - """ - - __slots__ = ('_state', '_details', '_timestamps', '_assets', '_party', '_sync_id', '_session_id', '_created_at') - - def __init__(self, **data: Any) -> None: - self._state: str = data.pop('state', '') - self._details: str = data.pop('details', '') - self._timestamps: ActivityTimestamps = data.pop('timestamps', {}) - self._assets: ActivityAssets = data.pop('assets', {}) - self._party: ActivityParty = data.pop('party', {}) - self._sync_id: str = data.pop('sync_id', '') - self._session_id: Optional[str] = data.pop('session_id') - self._created_at: Optional[float] = data.pop('created_at', None) - - @property - def type(self) -> ActivityType: - """:class:`ActivityType`: Returns the activity's type. This is for compatibility with :class:`Activity`. - - It always returns :attr:`ActivityType.listening`. - """ - return ActivityType.listening - - @property - def created_at(self) -> Optional[datetime.datetime]: - """Optional[:class:`datetime.datetime`]: When the user started listening in UTC. - - .. versionadded:: 1.3 - """ - if self._created_at is not None: - return datetime.datetime.fromtimestamp(self._created_at / 1000, tz=datetime.timezone.utc) - - @property - def colour(self) -> Colour: - """:class:`Colour`: Returns the Spotify integration colour, as a :class:`Colour`. - - There is an alias for this named :attr:`color`""" - return Colour(0x1DB954) - - @property - def color(self) -> Colour: - """:class:`Colour`: Returns the Spotify integration colour, as a :class:`Colour`. - - There is an alias for this named :attr:`colour`""" - return self.colour - - def to_dict(self) -> Dict[str, Any]: - return { - 'flags': 48, # SYNC | PLAY - 'name': 'Spotify', - 'assets': self._assets, - 'party': self._party, - 'sync_id': self._sync_id, - 'session_id': self._session_id, - 'timestamps': self._timestamps, - 'details': self._details, - 'state': self._state, - } - - @property - def name(self) -> str: - """:class:`str`: The activity's name. This will always return "Spotify".""" - return 'Spotify' - - def __eq__(self, other: object) -> bool: - return ( - isinstance(other, Spotify) - and other._session_id == self._session_id - and other._sync_id == self._sync_id - and other.start == self.start - ) - - def __ne__(self, other: object) -> bool: - return not self.__eq__(other) - - def __hash__(self) -> int: - return hash(self._session_id) - - def __str__(self) -> str: - return 'Spotify' - - def __repr__(self) -> str: - return f'' - - @property - def title(self) -> str: - """:class:`str`: The title of the song being played.""" - return self._details - - @property - def artists(self) -> List[str]: - """List[:class:`str`]: The artists of the song being played.""" - return self._state.split('; ') - - @property - def artist(self) -> str: - """:class:`str`: The artist of the song being played. - - This does not attempt to split the artist information into - multiple artists. Useful if there's only a single artist. - """ - return self._state - - @property - def album(self) -> str: - """:class:`str`: The album that the song being played belongs to.""" - return self._assets.get('large_text', '') - - @property - def album_cover_url(self) -> str: - """:class:`str`: The album cover image URL from Spotify's CDN.""" - large_image = self._assets.get('large_image', '') - if large_image[:8] != 'spotify:': - return '' - album_image_id = large_image[8:] - return 'https://i.scdn.co/image/' + album_image_id - - @property - def track_id(self) -> str: - """:class:`str`: The track ID used by Spotify to identify this song.""" - return self._sync_id - - @property - def track_url(self) -> str: - """:class:`str`: The track URL to listen on Spotify. - - .. versionadded:: 2.0 - """ - return f'https://open.spotify.com/track/{self.track_id}' - - @property - def start(self) -> datetime.datetime: - """:class:`datetime.datetime`: When the user started playing this song in UTC.""" - # the start key will be present here - return datetime.datetime.fromtimestamp(self._timestamps['start'] / 1000, tz=datetime.timezone.utc) # type: ignore - - @property - def end(self) -> datetime.datetime: - """:class:`datetime.datetime`: When the user will stop playing this song in UTC.""" - # the end key will be present here - return datetime.datetime.fromtimestamp(self._timestamps['end'] / 1000, tz=datetime.timezone.utc) # type: ignore - - @property - def duration(self) -> datetime.timedelta: - """:class:`datetime.timedelta`: The duration of the song being played.""" - return self.end - self.start - - @property - def party_id(self) -> str: - """:class:`str`: The party ID of the listening party.""" - return self._party.get('id', '') - - -class CustomActivity(BaseActivity): - """Represents a custom activity from Discord. - - .. container:: operations - - .. describe:: x == y - - Checks if two activities are equal. - - .. describe:: x != y - - Checks if two activities are not equal. - - .. describe:: hash(x) - - Returns the activity's hash. - - .. describe:: str(x) - - Returns the custom status text. - - .. versionadded:: 1.3 - - Attributes - ----------- - name: Optional[:class:`str`] - The custom activity's name. - emoji: Optional[:class:`PartialEmoji`] - The emoji to pass to the activity, if any. - """ - - __slots__ = ('name', 'emoji', 'state') - - def __init__(self, name: Optional[str], *, emoji: Optional[PartialEmoji] = None, **extra: Any) -> None: - super().__init__(**extra) - self.name: Optional[str] = name - self.state: Optional[str] = extra.pop('state', None) - if self.name == 'Custom Status': - self.name = self.state - - self.emoji: Optional[PartialEmoji] - if emoji is None: - self.emoji = emoji - elif isinstance(emoji, dict): - self.emoji = PartialEmoji.from_dict(emoji) - elif isinstance(emoji, str): - self.emoji = PartialEmoji(name=emoji) - elif isinstance(emoji, PartialEmoji): - self.emoji = emoji - else: - raise TypeError(f'Expected str, PartialEmoji, or None, received {type(emoji)!r} instead.') - - @property - def type(self) -> ActivityType: - """:class:`ActivityType`: Returns the activity's type. This is for compatibility with :class:`Activity`. - - It always returns :attr:`ActivityType.custom`. - """ - return ActivityType.custom - - def to_dict(self) -> Dict[str, Any]: - if self.name == self.state: - o = { - 'type': ActivityType.custom.value, - 'state': self.name, - 'name': 'Custom Status', - } - else: - o = { - 'type': ActivityType.custom.value, - 'name': self.name, - } - - if self.emoji: - o['emoji'] = self.emoji.to_dict() - return o - - def __eq__(self, other: object) -> bool: - return isinstance(other, CustomActivity) and other.name == self.name and other.emoji == self.emoji - - def __ne__(self, other: object) -> bool: - return not self.__eq__(other) - - def __hash__(self) -> int: - return hash((self.name, str(self.emoji))) - - def __str__(self) -> str: - if self.emoji: - if self.name: - return f'{self.emoji} {self.name}' - return str(self.emoji) - else: - return str(self.name) - - def __repr__(self) -> str: - return f'' - - -ActivityTypes = Union[Activity, Game, CustomActivity, Streaming, Spotify] - - -@overload -def create_activity(data: ActivityPayload, state: ConnectionState) -> ActivityTypes: - ... - - -@overload -def create_activity(data: None, state: ConnectionState) -> None: - ... - - -def create_activity(data: Optional[ActivityPayload], state: ConnectionState) -> Optional[ActivityTypes]: - if not data: - return None - - game_type = try_enum(ActivityType, data.get('type', -1)) - if game_type is ActivityType.playing: - if 'application_id' in data or 'session_id' in data: - return Activity(**data) - return Game(**data) - elif game_type is ActivityType.custom: - try: - name = data.pop('name') # type: ignore - except KeyError: - ret = Activity(**data) - else: - # we removed the name key from data already - ret = CustomActivity(name=name, **data) # type: ignore - elif game_type is ActivityType.streaming: - if 'url' in data: - # the url won't be None here - return Streaming(**data) # type: ignore - return Activity(**data) - elif game_type is ActivityType.listening and 'sync_id' in data and 'session_id' in data: - return Spotify(**data) - else: - ret = Activity(**data) - - if isinstance(ret.emoji, PartialEmoji): - ret.emoji._state = state - return ret diff --git a/.venv/Lib/site-packages/discord/app_commands/__init__.py b/.venv/Lib/site-packages/discord/app_commands/__init__.py deleted file mode 100644 index 9714617..0000000 --- a/.venv/Lib/site-packages/discord/app_commands/__init__.py +++ /dev/null @@ -1,20 +0,0 @@ -""" -discord.app_commands -~~~~~~~~~~~~~~~~~~~~~ - -Application commands support for the Discord API - -:copyright: (c) 2015-present Rapptz -:license: MIT, see LICENSE for more details. - -""" - -from .commands import * -from .errors import * -from .models import * -from .tree import * -from .namespace import * -from .transformers import * -from .translator import * -from . import checks as checks -from .checks import Cooldown as Cooldown diff --git a/.venv/Lib/site-packages/discord/app_commands/__pycache__/__init__.cpython-38.pyc b/.venv/Lib/site-packages/discord/app_commands/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index bdb9c1d..0000000 Binary files a/.venv/Lib/site-packages/discord/app_commands/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/app_commands/__pycache__/checks.cpython-38.pyc b/.venv/Lib/site-packages/discord/app_commands/__pycache__/checks.cpython-38.pyc deleted file mode 100644 index 92a1d6f..0000000 Binary files a/.venv/Lib/site-packages/discord/app_commands/__pycache__/checks.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/app_commands/__pycache__/commands.cpython-38.pyc b/.venv/Lib/site-packages/discord/app_commands/__pycache__/commands.cpython-38.pyc deleted file mode 100644 index d8c505c..0000000 Binary files a/.venv/Lib/site-packages/discord/app_commands/__pycache__/commands.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/app_commands/__pycache__/errors.cpython-38.pyc b/.venv/Lib/site-packages/discord/app_commands/__pycache__/errors.cpython-38.pyc deleted file mode 100644 index f604962..0000000 Binary files a/.venv/Lib/site-packages/discord/app_commands/__pycache__/errors.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/app_commands/__pycache__/models.cpython-38.pyc b/.venv/Lib/site-packages/discord/app_commands/__pycache__/models.cpython-38.pyc deleted file mode 100644 index df6094d..0000000 Binary files a/.venv/Lib/site-packages/discord/app_commands/__pycache__/models.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/app_commands/__pycache__/namespace.cpython-38.pyc b/.venv/Lib/site-packages/discord/app_commands/__pycache__/namespace.cpython-38.pyc deleted file mode 100644 index 717a1c5..0000000 Binary files a/.venv/Lib/site-packages/discord/app_commands/__pycache__/namespace.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/app_commands/__pycache__/transformers.cpython-38.pyc b/.venv/Lib/site-packages/discord/app_commands/__pycache__/transformers.cpython-38.pyc deleted file mode 100644 index b6baade..0000000 Binary files a/.venv/Lib/site-packages/discord/app_commands/__pycache__/transformers.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/app_commands/__pycache__/translator.cpython-38.pyc b/.venv/Lib/site-packages/discord/app_commands/__pycache__/translator.cpython-38.pyc deleted file mode 100644 index 87ab2cb..0000000 Binary files a/.venv/Lib/site-packages/discord/app_commands/__pycache__/translator.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/app_commands/__pycache__/tree.cpython-38.pyc b/.venv/Lib/site-packages/discord/app_commands/__pycache__/tree.cpython-38.pyc deleted file mode 100644 index a91e233..0000000 Binary files a/.venv/Lib/site-packages/discord/app_commands/__pycache__/tree.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/app_commands/checks.py b/.venv/Lib/site-packages/discord/app_commands/checks.py deleted file mode 100644 index 29cfe89..0000000 --- a/.venv/Lib/site-packages/discord/app_commands/checks.py +++ /dev/null @@ -1,537 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations - -from typing import ( - Any, - Coroutine, - Dict, - Hashable, - Union, - Callable, - TypeVar, - Optional, - TYPE_CHECKING, -) - -import time - -from .commands import check -from .errors import ( - NoPrivateMessage, - MissingRole, - MissingAnyRole, - MissingPermissions, - BotMissingPermissions, - CommandOnCooldown, -) - -from ..user import User -from ..permissions import Permissions -from ..utils import get as utils_get, MISSING, maybe_coroutine - -T = TypeVar('T') - -if TYPE_CHECKING: - from typing_extensions import Self - from ..interactions import Interaction - - CooldownFunction = Union[ - Callable[[Interaction], Coroutine[Any, Any, T]], - Callable[[Interaction], T], - ] - -__all__ = ( - 'has_role', - 'has_any_role', - 'has_permissions', - 'bot_has_permissions', - 'cooldown', - 'dynamic_cooldown', -) - - -class Cooldown: - """Represents a cooldown for a command. - - .. versionadded:: 2.0 - - Attributes - ----------- - rate: :class:`float` - The total number of tokens available per :attr:`per` seconds. - per: :class:`float` - The length of the cooldown period in seconds. - """ - - __slots__ = ('rate', 'per', '_window', '_tokens', '_last') - - def __init__(self, rate: float, per: float) -> None: - self.rate: int = int(rate) - self.per: float = float(per) - self._window: float = 0.0 - self._tokens: int = self.rate - self._last: float = 0.0 - - def get_tokens(self, current: Optional[float] = None) -> int: - """Returns the number of available tokens before rate limiting is applied. - - Parameters - ------------ - current: Optional[:class:`float`] - The time in seconds since Unix epoch to calculate tokens at. - If not supplied then :func:`time.time()` is used. - - Returns - -------- - :class:`int` - The number of tokens available before the cooldown is to be applied. - """ - if not current: - current = time.time() - - # the calculated tokens should be non-negative - tokens = max(self._tokens, 0) - - if current > self._window + self.per: - tokens = self.rate - return tokens - - def get_retry_after(self, current: Optional[float] = None) -> float: - """Returns the time in seconds until the cooldown will be reset. - - Parameters - ------------- - current: Optional[:class:`float`] - The current time in seconds since Unix epoch. - If not supplied, then :func:`time.time()` is used. - - Returns - ------- - :class:`float` - The number of seconds to wait before this cooldown will be reset. - """ - current = current or time.time() - tokens = self.get_tokens(current) - - if tokens == 0: - return self.per - (current - self._window) - - return 0.0 - - def update_rate_limit(self, current: Optional[float] = None, *, tokens: int = 1) -> Optional[float]: - """Updates the cooldown rate limit. - - Parameters - ------------- - current: Optional[:class:`float`] - The time in seconds since Unix epoch to update the rate limit at. - If not supplied, then :func:`time.time()` is used. - tokens: :class:`int` - The amount of tokens to deduct from the rate limit. - - Returns - ------- - Optional[:class:`float`] - The retry-after time in seconds if rate limited. - """ - current = current or time.time() - self._last = current - - self._tokens = self.get_tokens(current) - - # first token used means that we start a new rate limit window - if self._tokens == self.rate: - self._window = current - - # decrement tokens by specified number - self._tokens -= tokens - - # check if we are rate limited and return retry-after - if self._tokens < 0: - return self.per - (current - self._window) - - def reset(self) -> None: - """Reset the cooldown to its initial state.""" - self._tokens = self.rate - self._last = 0.0 - - def copy(self) -> Self: - """Creates a copy of this cooldown. - - Returns - -------- - :class:`Cooldown` - A new instance of this cooldown. - """ - return Cooldown(self.rate, self.per) - - def __repr__(self) -> str: - return f'' - - -def has_role(item: Union[int, str], /) -> Callable[[T], T]: - """A :func:`~discord.app_commands.check` that is added that checks if the member invoking the - command has the role specified via the name or ID specified. - - If a string is specified, you must give the exact name of the role, including - caps and spelling. - - If an integer is specified, you must give the exact snowflake ID of the role. - - This check raises one of two special exceptions, :exc:`~discord.app_commands.MissingRole` - if the user is missing a role, or :exc:`~discord.app_commands.NoPrivateMessage` if - it is used in a private message. Both inherit from :exc:`~discord.app_commands.CheckFailure`. - - .. versionadded:: 2.0 - - .. note:: - - This is different from the permission system that Discord provides for application - commands. This is done entirely locally in the program rather than being handled - by Discord. - - Parameters - ----------- - item: Union[:class:`int`, :class:`str`] - The name or ID of the role to check. - """ - - def predicate(interaction: Interaction) -> bool: - if isinstance(interaction.user, User): - raise NoPrivateMessage() - - if isinstance(item, int): - role = interaction.user.get_role(item) - else: - role = utils_get(interaction.user.roles, name=item) - - if role is None: - raise MissingRole(item) - return True - - return check(predicate) - - -def has_any_role(*items: Union[int, str]) -> Callable[[T], T]: - r"""A :func:`~discord.app_commands.check` that is added that checks if the member - invoking the command has **any** of the roles specified. This means that if they have - one out of the three roles specified, then this check will return ``True``. - - Similar to :func:`has_role`\, the names or IDs passed in must be exact. - - This check raises one of two special exceptions, :exc:`~discord.app_commands.MissingAnyRole` - if the user is missing all roles, or :exc:`~discord.app_commands.NoPrivateMessage` if - it is used in a private message. Both inherit from :exc:`~discord.app_commands.CheckFailure`. - - .. versionadded:: 2.0 - - .. note:: - - This is different from the permission system that Discord provides for application - commands. This is done entirely locally in the program rather than being handled - by Discord. - - Parameters - ----------- - items: List[Union[:class:`str`, :class:`int`]] - An argument list of names or IDs to check that the member has roles wise. - - Example - -------- - - .. code-block:: python3 - - @tree.command() - @app_commands.checks.has_any_role('Library Devs', 'Moderators', 492212595072434186) - async def cool(interaction: discord.Interaction): - await interaction.response.send_message('You are cool indeed') - """ - - def predicate(interaction: Interaction) -> bool: - if isinstance(interaction.user, User): - raise NoPrivateMessage() - - if any( - interaction.user.get_role(item) is not None - if isinstance(item, int) - else utils_get(interaction.user.roles, name=item) is not None - for item in items - ): - return True - raise MissingAnyRole(list(items)) - - return check(predicate) - - -def has_permissions(**perms: bool) -> Callable[[T], T]: - r"""A :func:`~discord.app_commands.check` that is added that checks if the member - has all of the permissions necessary. - - Note that this check operates on the permissions given by - :attr:`discord.Interaction.permissions`. - - The permissions passed in must be exactly like the properties shown under - :class:`discord.Permissions`. - - This check raises a special exception, :exc:`~discord.app_commands.MissingPermissions` - that is inherited from :exc:`~discord.app_commands.CheckFailure`. - - .. versionadded:: 2.0 - - .. note:: - - This is different from the permission system that Discord provides for application - commands. This is done entirely locally in the program rather than being handled - by Discord. - - Parameters - ------------ - \*\*perms: :class:`bool` - Keyword arguments denoting the permissions to check for. - - Example - --------- - - .. code-block:: python3 - - @tree.command() - @app_commands.checks.has_permissions(manage_messages=True) - async def test(interaction: discord.Interaction): - await interaction.response.send_message('You can manage messages.') - - """ - - invalid = perms.keys() - Permissions.VALID_FLAGS.keys() - if invalid: - raise TypeError(f"Invalid permission(s): {', '.join(invalid)}") - - def predicate(interaction: Interaction) -> bool: - permissions = interaction.permissions - - missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value] - - if not missing: - return True - - raise MissingPermissions(missing) - - return check(predicate) - - -def bot_has_permissions(**perms: bool) -> Callable[[T], T]: - """Similar to :func:`has_permissions` except checks if the bot itself has - the permissions listed. This relies on :attr:`discord.Interaction.app_permissions`. - - This check raises a special exception, :exc:`~discord.app_commands.BotMissingPermissions` - that is inherited from :exc:`~discord.app_commands.CheckFailure`. - - .. versionadded:: 2.0 - """ - - invalid = set(perms) - set(Permissions.VALID_FLAGS) - if invalid: - raise TypeError(f"Invalid permission(s): {', '.join(invalid)}") - - def predicate(interaction: Interaction) -> bool: - permissions = interaction.app_permissions - missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value] - - if not missing: - return True - - raise BotMissingPermissions(missing) - - return check(predicate) - - -def _create_cooldown_decorator( - key: CooldownFunction[Hashable], factory: CooldownFunction[Optional[Cooldown]] -) -> Callable[[T], T]: - - mapping: Dict[Any, Cooldown] = {} - - async def get_bucket( - interaction: Interaction, - *, - mapping: Dict[Any, Cooldown] = mapping, - key: CooldownFunction[Hashable] = key, - factory: CooldownFunction[Optional[Cooldown]] = factory, - ) -> Optional[Cooldown]: - current = interaction.created_at.timestamp() - dead_keys = [k for k, v in mapping.items() if current > v._last + v.per] - for k in dead_keys: - del mapping[k] - - k = await maybe_coroutine(key, interaction) - if k not in mapping: - bucket: Optional[Cooldown] = await maybe_coroutine(factory, interaction) - if bucket is not None: - mapping[k] = bucket - else: - bucket = mapping[k] - - return bucket - - async def predicate(interaction: Interaction) -> bool: - bucket = await get_bucket(interaction) - if bucket is None: - return True - - retry_after = bucket.update_rate_limit(interaction.created_at.timestamp()) - if retry_after is None: - return True - - raise CommandOnCooldown(bucket, retry_after) - - return check(predicate) - - -def cooldown( - rate: float, - per: float, - *, - key: Optional[CooldownFunction[Hashable]] = MISSING, -) -> Callable[[T], T]: - """A decorator that adds a cooldown to a command. - - A cooldown allows a command to only be used a specific amount - of times in a specific time frame. These cooldowns are based off - of the ``key`` function provided. If a ``key`` is not provided - then it defaults to a user-level cooldown. The ``key`` function - must take a single parameter, the :class:`discord.Interaction` and - return a value that is used as a key to the internal cooldown mapping. - - The ``key`` function can optionally be a coroutine. - - If a cooldown is triggered, then :exc:`~discord.app_commands.CommandOnCooldown` is - raised to the error handlers. - - Examples - --------- - - Setting a one per 5 seconds per member cooldown on a command: - - .. code-block:: python3 - - @tree.command() - @app_commands.checks.cooldown(1, 5.0, key=lambda i: (i.guild_id, i.user.id)) - async def test(interaction: discord.Interaction): - await interaction.response.send_message('Hello') - - @test.error - async def on_test_error(interaction: discord.Interaction, error: app_commands.AppCommandError): - if isinstance(error, app_commands.CommandOnCooldown): - await interaction.response.send_message(str(error), ephemeral=True) - - Parameters - ------------ - rate: :class:`int` - The number of times a command can be used before triggering a cooldown. - per: :class:`float` - The amount of seconds to wait for a cooldown when it's been triggered. - key: Optional[Callable[[:class:`discord.Interaction`], :class:`collections.abc.Hashable`]] - A function that returns a key to the mapping denoting the type of cooldown. - Can optionally be a coroutine. If not given then defaults to a user-level - cooldown. If ``None`` is passed then it is interpreted as a "global" cooldown. - """ - - if key is MISSING: - key_func = lambda interaction: interaction.user.id - elif key is None: - key_func = lambda i: None - else: - key_func = key - - factory = lambda interaction: Cooldown(rate, per) - - return _create_cooldown_decorator(key_func, factory) - - -def dynamic_cooldown( - factory: CooldownFunction[Optional[Cooldown]], - *, - key: Optional[CooldownFunction[Hashable]] = MISSING, -) -> Callable[[T], T]: - """A decorator that adds a dynamic cooldown to a command. - - A cooldown allows a command to only be used a specific amount - of times in a specific time frame. These cooldowns are based off - of the ``key`` function provided. If a ``key`` is not provided - then it defaults to a user-level cooldown. The ``key`` function - must take a single parameter, the :class:`discord.Interaction` and - return a value that is used as a key to the internal cooldown mapping. - - If a ``factory`` function is given, it must be a function that - accepts a single parameter of type :class:`discord.Interaction` and must - return a :class:`~discord.app_commands.Cooldown` or ``None``. - If ``None`` is returned then that cooldown is effectively bypassed. - - Both ``key`` and ``factory`` can optionally be coroutines. - - If a cooldown is triggered, then :exc:`~discord.app_commands.CommandOnCooldown` is - raised to the error handlers. - - Examples - --------- - - Setting a cooldown for everyone but the owner. - - .. code-block:: python3 - - def cooldown_for_everyone_but_me(interaction: discord.Interaction) -> Optional[app_commands.Cooldown]: - if interaction.user.id == 80088516616269824: - return None - return app_commands.Cooldown(1, 10.0) - - @tree.command() - @app_commands.checks.dynamic_cooldown(cooldown_for_everyone_but_me) - async def test(interaction: discord.Interaction): - await interaction.response.send_message('Hello') - - @test.error - async def on_test_error(interaction: discord.Interaction, error: app_commands.AppCommandError): - if isinstance(error, app_commands.CommandOnCooldown): - await interaction.response.send_message(str(error), ephemeral=True) - - Parameters - ------------ - factory: Optional[Callable[[:class:`discord.Interaction`], Optional[:class:`~discord.app_commands.Cooldown`]]] - A function that takes an interaction and returns a cooldown that will apply to that interaction - or ``None`` if the interaction should not have a cooldown. - key: Optional[Callable[[:class:`discord.Interaction`], :class:`collections.abc.Hashable`]] - A function that returns a key to the mapping denoting the type of cooldown. - Can optionally be a coroutine. If not given then defaults to a user-level - cooldown. If ``None`` is passed then it is interpreted as a "global" cooldown. - """ - - if key is MISSING: - key_func = lambda interaction: interaction.user.id - elif key is None: - key_func = lambda i: None - else: - key_func = key - - return _create_cooldown_decorator(key_func, factory) diff --git a/.venv/Lib/site-packages/discord/app_commands/commands.py b/.venv/Lib/site-packages/discord/app_commands/commands.py deleted file mode 100644 index c4f9163..0000000 --- a/.venv/Lib/site-packages/discord/app_commands/commands.py +++ /dev/null @@ -1,2509 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations -import inspect - -from typing import ( - Any, - Callable, - ClassVar, - Coroutine, - Dict, - Generator, - Generic, - List, - MutableMapping, - Optional, - Set, - TYPE_CHECKING, - Tuple, - Type, - TypeVar, - Union, - overload, -) -from textwrap import TextWrapper - -import re - -from ..enums import AppCommandOptionType, AppCommandType, ChannelType, Locale -from .models import Choice -from .transformers import annotation_to_parameter, CommandParameter, NoneType -from .errors import AppCommandError, CheckFailure, CommandInvokeError, CommandSignatureMismatch, CommandAlreadyRegistered -from .translator import TranslationContextLocation, TranslationContext, Translator, locale_str -from ..message import Message -from ..user import User -from ..member import Member -from ..permissions import Permissions -from ..utils import resolve_annotation, MISSING, is_inside_class, maybe_coroutine, async_all - -if TYPE_CHECKING: - from typing_extensions import ParamSpec, Concatenate - from ..interactions import Interaction - from ..abc import Snowflake - from .namespace import Namespace - from .models import ChoiceT - - # Generally, these two libraries are supposed to be separate from each other. - # However, for type hinting purposes it's unfortunately necessary for one to - # reference the other to prevent type checking errors in callbacks - from discord.ext.commands import Cog - - ErrorFunc = Callable[[Interaction, AppCommandError], Coroutine[Any, Any, None]] - -__all__ = ( - 'Command', - 'ContextMenu', - 'Group', - 'Parameter', - 'context_menu', - 'command', - 'describe', - 'check', - 'rename', - 'choices', - 'autocomplete', - 'guilds', - 'guild_only', - 'default_permissions', -) - -if TYPE_CHECKING: - P = ParamSpec('P') -else: - P = TypeVar('P') - -T = TypeVar('T') -F = TypeVar('F', bound=Callable[..., Any]) -GroupT = TypeVar('GroupT', bound='Binding') -Coro = Coroutine[Any, Any, T] -UnboundError = Callable[['Interaction', AppCommandError], Coro[Any]] -Error = Union[ - Callable[[GroupT, 'Interaction', AppCommandError], Coro[Any]], - UnboundError, -] -Check = Callable[['Interaction'], Union[bool, Coro[bool]]] -Binding = Union['Group', 'Cog'] - - -if TYPE_CHECKING: - CommandCallback = Union[ - Callable[Concatenate[GroupT, 'Interaction', P], Coro[T]], - Callable[Concatenate['Interaction', P], Coro[T]], - ] - - ContextMenuCallback = Union[ - # If groups end up support context menus these would be uncommented - # Callable[[GroupT, 'Interaction', Member], Coro[Any]], - # Callable[[GroupT, 'Interaction', User], Coro[Any]], - # Callable[[GroupT, 'Interaction', Message], Coro[Any]], - # Callable[[GroupT, 'Interaction', Union[Member, User]], Coro[Any]], - Callable[['Interaction', Member], Coro[Any]], - Callable[['Interaction', User], Coro[Any]], - Callable[['Interaction', Message], Coro[Any]], - Callable[['Interaction', Union[Member, User]], Coro[Any]], - ] - - AutocompleteCallback = Union[ - Callable[[GroupT, 'Interaction', ChoiceT], Coro[List[Choice[ChoiceT]]]], - Callable[['Interaction', ChoiceT], Coro[List[Choice[ChoiceT]]]], - ] -else: - CommandCallback = Callable[..., Coro[T]] - ContextMenuCallback = Callable[..., Coro[T]] - AutocompleteCallback = Callable[..., Coro[T]] - - -CheckInputParameter = Union['Command[Any, ..., Any]', 'ContextMenu', 'CommandCallback[Any, ..., Any]', ContextMenuCallback] - -# The re module doesn't support \p{} so we have to list characters from Thai and Devanagari manually. -THAI_COMBINING = r'\u0e31-\u0e3a\u0e47-\u0e4e' -DEVANAGARI_COMBINING = r'\u0900-\u0903\u093a\u093b\u093c\u093e\u093f\u0940-\u094f\u0955\u0956\u0957\u0962\u0963' -VALID_SLASH_COMMAND_NAME = re.compile(r'^[-_\w' + THAI_COMBINING + DEVANAGARI_COMBINING + r']{1,32}$') - -CAMEL_CASE_REGEX = re.compile(r'(?\w+)' - -ARG_DESCRIPTION_SUBREGEX = r'(?P(?:.|\n)+?(?:\Z|\r?\n(?=[\S\r\n])))' - -ARG_TYPE_SUBREGEX = r'(?:.+)' - -GOOGLE_DOCSTRING_ARG_REGEX = re.compile( - rf'^{ARG_NAME_SUBREGEX}[ \t]*(?:\({ARG_TYPE_SUBREGEX}\))?[ \t]*:[ \t]*{ARG_DESCRIPTION_SUBREGEX}', - re.MULTILINE, -) - -SPHINX_DOCSTRING_ARG_REGEX = re.compile( - rf'^:param {ARG_NAME_SUBREGEX}:[ \t]+{ARG_DESCRIPTION_SUBREGEX}', - re.MULTILINE, -) - -NUMPY_DOCSTRING_ARG_REGEX = re.compile( - rf'^{ARG_NAME_SUBREGEX}(?:[ \t]*:)?(?:[ \t]+{ARG_TYPE_SUBREGEX})?[ \t]*\r?\n[ \t]+{ARG_DESCRIPTION_SUBREGEX}', - re.MULTILINE, -) - - -def _shorten( - input: str, - *, - _wrapper: TextWrapper = TextWrapper(width=100, max_lines=1, replace_whitespace=True, placeholder='…'), -) -> str: - try: - # split on the first double newline since arguments may appear after that - input, _ = re.split(r'\n\s*\n', input, maxsplit=1) - except ValueError: - pass - return _wrapper.fill(' '.join(input.strip().split())) - - -def _parse_args_from_docstring(func: Callable[..., Any], params: Dict[str, CommandParameter]) -> Dict[str, str]: - docstring = inspect.getdoc(func) - - if docstring is None: - return {} - - # Extract the arguments - # Note: These are loose regexes, but they are good enough for our purposes - # For Google-style, look only at the lines that are indented - section_lines = inspect.cleandoc('\n'.join(line for line in docstring.splitlines() if line.startswith(' '))) - docstring_styles = ( - GOOGLE_DOCSTRING_ARG_REGEX.finditer(section_lines), - SPHINX_DOCSTRING_ARG_REGEX.finditer(docstring), - NUMPY_DOCSTRING_ARG_REGEX.finditer(docstring), - ) - - return { - m.group('name'): m.group('description') for matches in docstring_styles for m in matches if m.group('name') in params - } - - -def _to_kebab_case(text: str) -> str: - return CAMEL_CASE_REGEX.sub('-', text).lower() - - -def validate_name(name: str) -> str: - match = VALID_SLASH_COMMAND_NAME.match(name) - if match is None: - raise ValueError( - f'{name!r} must be between 1-32 characters and contain only lower-case letters, numbers, hyphens, or underscores.' - ) - - # Ideally, name.islower() would work instead but since certain characters - # are Lo (e.g. CJK) those don't pass the test. I'd use `casefold` instead as - # well, but chances are the server-side check is probably something similar to - # this code anyway. - if name.lower() != name: - raise ValueError(f'{name!r} must be all lower-case') - return name - - -def validate_context_menu_name(name: str) -> str: - if not name or len(name) > 32: - raise ValueError('context menu names must be between 1-32 characters') - return name - - -def _validate_auto_complete_callback( - callback: AutocompleteCallback[GroupT, ChoiceT] -) -> AutocompleteCallback[GroupT, ChoiceT]: - # This function needs to ensure the following is true: - # If self.foo is passed then don't pass command.binding to the callback - # If Class.foo is passed then it is assumed command.binding has to be passed - # If free_function_foo is passed then no binding should be passed at all - # Passing command.binding is mandated by pass_command_binding - - binding = getattr(callback, '__self__', None) - pass_command_binding = binding is None and is_inside_class(callback) - - # 'method' objects can't have dynamic attributes - if binding is None: - callback.pass_command_binding = pass_command_binding - - required_parameters = 2 + pass_command_binding - params = inspect.signature(callback).parameters - if len(params) != required_parameters: - raise TypeError(f'autocomplete callback {callback.__qualname__!r} requires either 2 or 3 parameters to be passed') - - return callback - - -def _context_menu_annotation(annotation: Any, *, _none: type = NoneType) -> AppCommandType: - if annotation is Message: - return AppCommandType.message - - supported_types: Set[Any] = {Member, User} - if annotation in supported_types: - return AppCommandType.user - - # Check if there's an origin - origin = getattr(annotation, '__origin__', None) - if origin is not Union: - # Only Union is supported so bail early - msg = ( - f'unsupported type annotation {annotation!r}, must be either discord.Member, ' - 'discord.User, discord.Message, or a typing.Union of discord.Member and discord.User' - ) - raise TypeError(msg) - - # Only Union[Member, User] is supported - if not all(arg in supported_types for arg in annotation.__args__): - raise TypeError(f'unsupported types given inside {annotation!r}') - - return AppCommandType.user - - -def _populate_descriptions(params: Dict[str, CommandParameter], descriptions: Dict[str, Any]) -> None: - for name, param in params.items(): - description = descriptions.pop(name, MISSING) - if description is MISSING: - param.description = '…' - continue - - if not isinstance(description, (str, locale_str)): - raise TypeError('description must be a string') - - if isinstance(description, str): - param.description = _shorten(description) - else: - param.description = description - - if descriptions: - first = next(iter(descriptions)) - raise TypeError(f'unknown parameter given: {first}') - - -def _populate_renames(params: Dict[str, CommandParameter], renames: Dict[str, Union[str, locale_str]]) -> None: - rename_map: Dict[str, Union[str, locale_str]] = {} - - # original name to renamed name - - for name in params.keys(): - new_name = renames.pop(name, MISSING) - - if new_name is MISSING: - rename_map[name] = name - continue - - if name in rename_map: - raise ValueError(f'{new_name} is already used') - - if isinstance(new_name, str): - new_name = validate_name(new_name) - else: - validate_name(new_name.message) - - rename_map[name] = new_name - params[name]._rename = new_name - - if renames: - first = next(iter(renames)) - raise ValueError(f'unknown parameter given: {first}') - - -def _populate_choices(params: Dict[str, CommandParameter], all_choices: Dict[str, List[Choice]]) -> None: - for name, param in params.items(): - choices = all_choices.pop(name, MISSING) - if choices is MISSING: - continue - - if not isinstance(choices, list): - raise TypeError('choices must be a list of Choice') - - if not all(isinstance(choice, Choice) for choice in choices): - raise TypeError('choices must be a list of Choice') - - if param.type not in (AppCommandOptionType.string, AppCommandOptionType.number, AppCommandOptionType.integer): - raise TypeError('choices are only supported for integer, string, or number option types') - - if not all(param.type == choice._option_type for choice in choices): - raise TypeError('choices must all have the same inner option type as the parameter choice type') - - param.choices = choices - - if all_choices: - first = next(iter(all_choices)) - raise TypeError(f'unknown parameter given: {first}') - - -def _populate_autocomplete(params: Dict[str, CommandParameter], autocomplete: Dict[str, Any]) -> None: - for name, param in params.items(): - callback = autocomplete.pop(name, MISSING) - if callback is MISSING: - continue - - if not inspect.iscoroutinefunction(callback): - raise TypeError('autocomplete callback must be a coroutine function') - - if param.type not in (AppCommandOptionType.string, AppCommandOptionType.number, AppCommandOptionType.integer): - raise TypeError('autocomplete is only supported for integer, string, or number option types') - - if param.is_choice_annotation(): - raise TypeError( - 'Choice annotation unsupported for autocomplete parameters, consider using a regular annotation instead' - ) - - param.autocomplete = _validate_auto_complete_callback(callback) - - if autocomplete: - first = next(iter(autocomplete)) - raise TypeError(f'unknown parameter given: {first}') - - -def _extract_parameters_from_callback(func: Callable[..., Any], globalns: Dict[str, Any]) -> Dict[str, CommandParameter]: - params = inspect.signature(func).parameters - cache = {} - required_params = is_inside_class(func) + 1 - if len(params) < required_params: - raise TypeError(f'callback {func.__qualname__!r} must have more than {required_params - 1} parameter(s)') - - iterator = iter(params.values()) - for _ in range(0, required_params): - next(iterator) - - parameters: List[CommandParameter] = [] - for parameter in iterator: - if parameter.annotation is parameter.empty: - raise TypeError(f'parameter {parameter.name!r} is missing a type annotation in callback {func.__qualname__!r}') - - resolved = resolve_annotation(parameter.annotation, globalns, globalns, cache) - param = annotation_to_parameter(resolved, parameter) - parameters.append(param) - - values = sorted(parameters, key=lambda a: a.required, reverse=True) - result = {v.name: v for v in values} - - descriptions = _parse_args_from_docstring(func, result) - - try: - descriptions.update(func.__discord_app_commands_param_description__) - except AttributeError: - for param in values: - if param.description is MISSING: - param.description = '…' - if descriptions: - _populate_descriptions(result, descriptions) - - try: - renames = func.__discord_app_commands_param_rename__ - except AttributeError: - pass - else: - _populate_renames(result, renames.copy()) - - try: - choices = func.__discord_app_commands_param_choices__ - except AttributeError: - pass - else: - _populate_choices(result, choices.copy()) - - try: - autocomplete = func.__discord_app_commands_param_autocomplete__ - except AttributeError: - pass - else: - _populate_autocomplete(result, autocomplete.copy()) - - return result - - -def _get_context_menu_parameter(func: ContextMenuCallback) -> Tuple[str, Any, AppCommandType]: - params = inspect.signature(func).parameters - if len(params) != 2: - msg = ( - f'context menu callback {func.__qualname__!r} requires 2 parameters, ' - 'the first one being the interaction and the other one explicitly ' - 'annotated with either discord.Message, discord.User, discord.Member, ' - 'or a typing.Union of discord.Member and discord.User' - ) - raise TypeError(msg) - - iterator = iter(params.values()) - next(iterator) # skip interaction - parameter = next(iterator) - if parameter.annotation is parameter.empty: - msg = ( - f'second parameter of context menu callback {func.__qualname__!r} must be explicitly ' - 'annotated with either discord.Message, discord.User, discord.Member, or ' - 'a typing.Union of discord.Member and discord.User' - ) - raise TypeError(msg) - - resolved = resolve_annotation(parameter.annotation, func.__globals__, func.__globals__, {}) - type = _context_menu_annotation(resolved) - return (parameter.name, resolved, type) - - -class Parameter: - """A class that contains the parameter information of a :class:`Command` callback. - - .. versionadded:: 2.0 - - Attributes - ----------- - name: :class:`str` - The name of the parameter. This is the Python identifier for the parameter. - display_name: :class:`str` - The displayed name of the parameter on Discord. - description: :class:`str` - The description of the parameter. - autocomplete: :class:`bool` - Whether the parameter has an autocomplete handler. - locale_name: Optional[:class:`locale_str`] - The display name's locale string, if available. - locale_description: Optional[:class:`locale_str`] - The description's locale string, if available. - required: :class:`bool` - Whether the parameter is required - choices: List[:class:`~discord.app_commands.Choice`] - A list of choices this parameter takes, if any. - type: :class:`~discord.AppCommandOptionType` - The underlying type of this parameter. - channel_types: List[:class:`~discord.ChannelType`] - The channel types that are allowed for this parameter. - min_value: Optional[Union[:class:`int`, :class:`float`]] - The minimum supported value for this parameter. - max_value: Optional[Union[:class:`int`, :class:`float`]] - The maximum supported value for this parameter. - default: Any - The default value of the parameter, if given. - If not given then this is :data:`~discord.utils.MISSING`. - command: :class:`Command` - The command this parameter is attached to. - """ - - def __init__(self, parent: CommandParameter, command: Command[Any, ..., Any]) -> None: - self.__parent: CommandParameter = parent - self.__command: Command[Any, ..., Any] = command - - @property - def command(self) -> Command[Any, ..., Any]: - return self.__command - - @property - def name(self) -> str: - return self.__parent.name - - @property - def display_name(self) -> str: - return self.__parent.display_name - - @property - def required(self) -> bool: - return self.__parent.required - - @property - def description(self) -> str: - return str(self.__parent.description) - - @property - def locale_name(self) -> Optional[locale_str]: - if isinstance(self.__parent._rename, locale_str): - return self.__parent._rename - return None - - @property - def locale_description(self) -> Optional[locale_str]: - if isinstance(self.__parent.description, locale_str): - return self.__parent.description - return None - - @property - def autocomplete(self) -> bool: - return self.__parent.autocomplete is not None - - @property - def default(self) -> Any: - return self.__parent.default - - @property - def type(self) -> AppCommandOptionType: - return self.__parent.type - - @property - def choices(self) -> List[Choice[Union[int, float, str]]]: - choices = self.__parent.choices - if choices is MISSING: - return [] - return choices.copy() - - @property - def channel_types(self) -> List[ChannelType]: - channel_types = self.__parent.channel_types - if channel_types is MISSING: - return [] - return channel_types.copy() - - @property - def min_value(self) -> Optional[Union[int, float]]: - return self.__parent.min_value - - @property - def max_value(self) -> Optional[Union[int, float]]: - return self.__parent.max_value - - -class Command(Generic[GroupT, P, T]): - """A class that implements an application command. - - These are usually not created manually, instead they are created using - one of the following decorators: - - - :func:`~discord.app_commands.command` - - :meth:`Group.command ` - - :meth:`CommandTree.command ` - - .. versionadded:: 2.0 - - Parameters - ----------- - name: Union[:class:`str`, :class:`locale_str`] - The name of the application command. - description: Union[:class:`str`, :class:`locale_str`] - The description of the application command. This shows up in the UI to describe - the application command. - callback: :ref:`coroutine ` - The coroutine that is executed when the command is called. - auto_locale_strings: :class:`bool` - If this is set to ``True``, then all translatable strings will implicitly - be wrapped into :class:`locale_str` rather than :class:`str`. This could - avoid some repetition and be more ergonomic for certain defaults such - as default command names, command descriptions, and parameter names. - Defaults to ``True``. - nsfw: :class:`bool` - Whether the command is NSFW and should only work in NSFW channels. - Defaults to ``False``. - - Due to a Discord limitation, this does not work on subcommands. - parent: Optional[:class:`Group`] - The parent application command. ``None`` if there isn't one. - extras: :class:`dict` - A dictionary that can be used to store extraneous data. - The library will not touch any values or keys within this dictionary. - - Attributes - ------------ - name: :class:`str` - The name of the application command. - description: :class:`str` - The description of the application command. This shows up in the UI to describe - the application command. - checks - A list of predicates that take a :class:`~discord.Interaction` parameter - to indicate whether the command callback should be executed. If an exception - is necessary to be thrown to signal failure, then one inherited from - :exc:`AppCommandError` should be used. If all the checks fail without - propagating an exception, :exc:`CheckFailure` is raised. - default_permissions: Optional[:class:`~discord.Permissions`] - The default permissions that can execute this command on Discord. Note - that server administrators can override this value in the client. - Setting an empty permissions field will disallow anyone except server - administrators from using the command in a guild. - - Due to a Discord limitation, this does not work on subcommands. - guild_only: :class:`bool` - Whether the command should only be usable in guild contexts. - - Due to a Discord limitation, this does not work on subcommands. - nsfw: :class:`bool` - Whether the command is NSFW and should only work in NSFW channels. - - Due to a Discord limitation, this does not work on subcommands. - parent: Optional[:class:`Group`] - The parent application command. ``None`` if there isn't one. - extras: :class:`dict` - A dictionary that can be used to store extraneous data. - The library will not touch any values or keys within this dictionary. - """ - - def __init__( - self, - *, - name: Union[str, locale_str], - description: Union[str, locale_str], - callback: CommandCallback[GroupT, P, T], - nsfw: bool = False, - parent: Optional[Group] = None, - guild_ids: Optional[List[int]] = None, - auto_locale_strings: bool = True, - extras: Dict[Any, Any] = MISSING, - ): - name, locale = (name.message, name) if isinstance(name, locale_str) else (name, None) - self.name: str = validate_name(name) - self._locale_name: Optional[locale_str] = locale - description, locale = ( - (description.message, description) if isinstance(description, locale_str) else (description, None) - ) - self.description: str = description - self._locale_description: Optional[locale_str] = locale - self._attr: Optional[str] = None - self._callback: CommandCallback[GroupT, P, T] = callback - self.parent: Optional[Group] = parent - self.binding: Optional[GroupT] = None - self.on_error: Optional[Error[GroupT]] = None - self.module: Optional[str] = callback.__module__ - - # Unwrap __self__ for bound methods - try: - self.binding = callback.__self__ - self._callback = callback = callback.__func__ - except AttributeError: - pass - - self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__) - self.checks: List[Check] = getattr(callback, '__discord_app_commands_checks__', []) - self._guild_ids: Optional[List[int]] = guild_ids or getattr( - callback, '__discord_app_commands_default_guilds__', None - ) - self.default_permissions: Optional[Permissions] = getattr( - callback, '__discord_app_commands_default_permissions__', None - ) - self.guild_only: bool = getattr(callback, '__discord_app_commands_guild_only__', False) - self.nsfw: bool = nsfw - self.extras: Dict[Any, Any] = extras or {} - - if self._guild_ids is not None and self.parent is not None: - raise ValueError('child commands cannot have default guilds set, consider setting them in the parent instead') - - if auto_locale_strings: - self._convert_to_locale_strings() - - def _convert_to_locale_strings(self) -> None: - if self._locale_name is None: - self._locale_name = locale_str(self.name) - if self._locale_description is None: - self._locale_description = locale_str(self.description) - - for param in self._params.values(): - param._convert_to_locale_strings() - - def __set_name__(self, owner: Type[Any], name: str) -> None: - self._attr = name - - @property - def callback(self) -> CommandCallback[GroupT, P, T]: - """:ref:`coroutine `: The coroutine that is executed when the command is called.""" - return self._callback - - def _copy_with( - self, - *, - parent: Optional[Group], - binding: GroupT, - bindings: MutableMapping[GroupT, GroupT] = MISSING, - set_on_binding: bool = True, - ) -> Command: - bindings = {} if bindings is MISSING else bindings - - cls = self.__class__ - copy = cls.__new__(cls) - copy.name = self.name - copy._locale_name = self._locale_name - copy._guild_ids = self._guild_ids - copy.checks = self.checks - copy.description = self.description - copy._locale_description = self._locale_description - copy.default_permissions = self.default_permissions - copy.guild_only = self.guild_only - copy.nsfw = self.nsfw - copy._attr = self._attr - copy._callback = self._callback - copy.on_error = self.on_error - copy._params = self._params.copy() - copy.module = self.module - copy.parent = parent - copy.binding = bindings.get(self.binding) if self.binding is not None else binding - copy.extras = self.extras - - if copy._attr and set_on_binding: - setattr(copy.binding, copy._attr, copy) - - return copy - - async def get_translated_payload(self, translator: Translator) -> Dict[str, Any]: - base = self.to_dict() - name_localizations: Dict[str, str] = {} - description_localizations: Dict[str, str] = {} - - # Prevent creating these objects in a heavy loop - name_context = TranslationContext(location=TranslationContextLocation.command_name, data=self) - description_context = TranslationContext(location=TranslationContextLocation.command_description, data=self) - - for locale in Locale: - if self._locale_name: - translation = await translator._checked_translate(self._locale_name, locale, name_context) - if translation is not None: - name_localizations[locale.value] = translation - - if self._locale_description: - translation = await translator._checked_translate(self._locale_description, locale, description_context) - if translation is not None: - description_localizations[locale.value] = translation - - base['name_localizations'] = name_localizations - base['description_localizations'] = description_localizations - base['options'] = [ - await param.get_translated_payload(translator, Parameter(param, self)) for param in self._params.values() - ] - return base - - def to_dict(self) -> Dict[str, Any]: - # If we have a parent then our type is a subcommand - # Otherwise, the type falls back to the specific command type (e.g. slash command or context menu) - option_type = AppCommandType.chat_input.value if self.parent is None else AppCommandOptionType.subcommand.value - base: Dict[str, Any] = { - 'name': self.name, - 'description': self.description, - 'type': option_type, - 'options': [param.to_dict() for param in self._params.values()], - } - - if self.parent is None: - base['nsfw'] = self.nsfw - base['dm_permission'] = not self.guild_only - base['default_member_permissions'] = None if self.default_permissions is None else self.default_permissions.value - - return base - - async def _invoke_error_handlers(self, interaction: Interaction, error: AppCommandError) -> None: - # These type ignores are because the type checker can't narrow this type properly. - if self.on_error is not None: - if self.binding is not None: - await self.on_error(self.binding, interaction, error) # type: ignore - else: - await self.on_error(interaction, error) # type: ignore - - parent = self.parent - if parent is not None: - await parent.on_error(interaction, error) - - if parent.parent is not None: - await parent.parent.on_error(interaction, error) - - binding_error_handler = getattr(self.binding, '__discord_app_commands_error_handler__', None) - if binding_error_handler is not None: - await binding_error_handler(interaction, error) - - def _has_any_error_handlers(self) -> bool: - if self.on_error is not None: - return True - - parent = self.parent - if parent is not None: - # Check if the on_error is overridden - if parent.__class__.on_error is not Group.on_error: - return True - - if parent.parent is not None: - parent_cls = parent.parent.__class__ - if parent_cls.on_error is not Group.on_error: - return True - - return False - - async def _transform_arguments(self, interaction: Interaction, namespace: Namespace) -> Dict[str, Any]: - values = namespace.__dict__ - transformed_values = {} - - for param in self._params.values(): - try: - value = values[param.display_name] - except KeyError: - if not param.required: - transformed_values[param.name] = param.default - else: - raise CommandSignatureMismatch(self) from None - else: - transformed_values[param.name] = await param.transform(interaction, value) - - return transformed_values - - async def _do_call(self, interaction: Interaction, params: Dict[str, Any]) -> T: - # These type ignores are because the type checker doesn't quite understand the narrowing here - # Likewise, it thinks we're missing positional arguments when there aren't any. - try: - if self.binding is not None: - return await self._callback(self.binding, interaction, **params) # type: ignore - return await self._callback(interaction, **params) # type: ignore - except TypeError as e: - # In order to detect mismatch from the provided signature and the Discord data, - # there are many ways it can go wrong yet all of them eventually lead to a TypeError - # from the Python compiler showcasing that the signature is incorrect. This lovely - # piece of code essentially checks the last frame of the caller and checks if the - # locals contains our `self` reference. - # - # This is because there is a possibility that a TypeError is raised within the body - # of the function, and in that case the locals wouldn't contain a reference to - # the command object under the name `self`. - frame = inspect.trace()[-1].frame - if frame.f_locals.get('self') is self: - raise CommandSignatureMismatch(self) from None - raise CommandInvokeError(self, e) from e - except AppCommandError: - raise - except Exception as e: - raise CommandInvokeError(self, e) from e - - async def _invoke_with_namespace(self, interaction: Interaction, namespace: Namespace) -> T: - if not await self._check_can_run(interaction): - raise CheckFailure(f'The check functions for command {self.name!r} failed.') - - transformed_values = await self._transform_arguments(interaction, namespace) - return await self._do_call(interaction, transformed_values) - - async def _invoke_autocomplete(self, interaction: Interaction, name: str, namespace: Namespace): - # The namespace contains the Discord provided names so this will be fine - # even if the name is renamed - value = namespace.__dict__[name] - - try: - param = self._params[name] - except KeyError: - # Slow case, it might be a rename - params = {param.display_name: param for param in self._params.values()} - try: - param = params[name] - except KeyError: - raise CommandSignatureMismatch(self) from None - - if param.autocomplete is None: - raise CommandSignatureMismatch(self) - - predicates = getattr(param.autocomplete, '__discord_app_commands_checks__', []) - if predicates: - try: - if not await async_all(f(interaction) for f in predicates): - if not interaction.response.is_done(): - await interaction.response.autocomplete([]) - return - except Exception: - if not interaction.response.is_done(): - await interaction.response.autocomplete([]) - return - - if getattr(param.autocomplete, 'pass_command_binding', False): - binding = self.binding - if binding is not None: - choices = await param.autocomplete(binding, interaction, value) - else: - raise TypeError('autocomplete parameter expected a bound self parameter but one was not provided') - else: - choices = await param.autocomplete(interaction, value) - - if interaction.response.is_done(): - return - - await interaction.response.autocomplete(choices) - - def _get_internal_command(self, name: str) -> Optional[Union[Command, Group]]: - return None - - @property - def parameters(self) -> List[Parameter]: - """Returns a list of parameters for this command. - - This does not include the ``self`` or ``interaction`` parameters. - - Returns - -------- - List[:class:`Parameter`] - The parameters of this command. - """ - return [Parameter(p, self) for p in self._params.values()] - - def get_parameter(self, name: str) -> Optional[Parameter]: - """Retrieves a parameter by its name. - - The name must be the Python identifier rather than the renamed - one for display on Discord. - - Parameters - ----------- - name: :class:`str` - The parameter name in the callback function. - - Returns - -------- - Optional[:class:`Parameter`] - The parameter or ``None`` if not found. - """ - - parent = self._params.get(name) - if parent is not None: - return Parameter(parent, self) - return None - - @property - def root_parent(self) -> Optional[Group]: - """Optional[:class:`Group`]: The root parent of this command.""" - if self.parent is None: - return None - parent = self.parent - return parent.parent or parent - - @property - def qualified_name(self) -> str: - """:class:`str`: Returns the fully qualified command name. - - The qualified name includes the parent name as well. For example, - in a command like ``/foo bar`` the qualified name is ``foo bar``. - """ - # A B C - # ^ self - # ^ parent - # ^ grandparent - if self.parent is None: - return self.name - - names = [self.name, self.parent.name] - grandparent = self.parent.parent - if grandparent is not None: - names.append(grandparent.name) - - return ' '.join(reversed(names)) - - async def _check_can_run(self, interaction: Interaction) -> bool: - if self.parent is not None and self.parent is not self.binding: - # For commands with a parent which isn't the binding, i.e. - # - # - # - # The parent check needs to be called first - if not await maybe_coroutine(self.parent.interaction_check, interaction): - return False - - if self.binding is not None: - check: Optional[Check] = getattr(self.binding, 'interaction_check', None) - if check: - ret = await maybe_coroutine(check, interaction) - if not ret: - return False - - predicates = self.checks - if not predicates: - return True - - return await async_all(f(interaction) for f in predicates) - - def error(self, coro: Error[GroupT]) -> Error[GroupT]: - """A decorator that registers a coroutine as a local error handler. - - The local error handler is called whenever an exception is raised in the body - of the command or during handling of the command. The error handler must take - 2 parameters, the interaction and the error. - - The error passed will be derived from :exc:`AppCommandError`. - - Parameters - ----------- - coro: :ref:`coroutine ` - The coroutine to register as the local error handler. - - Raises - ------- - TypeError - The coroutine passed is not actually a coroutine. - """ - - if not inspect.iscoroutinefunction(coro): - raise TypeError('The error handler must be a coroutine.') - - self.on_error = coro - return coro - - def autocomplete( - self, name: str - ) -> Callable[[AutocompleteCallback[GroupT, ChoiceT]], AutocompleteCallback[GroupT, ChoiceT]]: - """A decorator that registers a coroutine as an autocomplete prompt for a parameter. - - The coroutine callback must have 2 parameters, the :class:`~discord.Interaction`, - and the current value by the user (usually either a :class:`str`, :class:`int`, or :class:`float`, - depending on the type of the parameter being marked as autocomplete). - - To get the values from other parameters that may be filled in, accessing - :attr:`.Interaction.namespace` will give a :class:`Namespace` object with those - values. - - Parent :func:`checks ` are ignored within an autocomplete. However, checks can be added - to the autocomplete callback and the ones added will be called. If the checks fail for any reason - then an empty list is sent as the interaction response. - - The coroutine decorator **must** return a list of :class:`~discord.app_commands.Choice` objects. - Only up to 25 objects are supported. - - Example: - - .. code-block:: python3 - - @app_commands.command() - async def fruits(interaction: discord.Interaction, fruit: str): - await interaction.response.send_message(f'Your favourite fruit seems to be {fruit}') - - @fruits.autocomplete('fruit') - async def fruits_autocomplete( - interaction: discord.Interaction, - current: str, - ) -> List[app_commands.Choice[str]]: - fruits = ['Banana', 'Pineapple', 'Apple', 'Watermelon', 'Melon', 'Cherry'] - return [ - app_commands.Choice(name=fruit, value=fruit) - for fruit in fruits if current.lower() in fruit.lower() - ] - - - Parameters - ----------- - name: :class:`str` - The parameter name to register as autocomplete. - - Raises - ------- - TypeError - The coroutine passed is not actually a coroutine or - the parameter is not found or of an invalid type. - """ - - def decorator(coro: AutocompleteCallback[GroupT, ChoiceT]) -> AutocompleteCallback[GroupT, ChoiceT]: - if not inspect.iscoroutinefunction(coro): - raise TypeError('The error handler must be a coroutine.') - - try: - param = self._params[name] - except KeyError: - raise TypeError(f'unknown parameter: {name!r}') from None - - if param.type not in (AppCommandOptionType.string, AppCommandOptionType.number, AppCommandOptionType.integer): - raise TypeError('autocomplete is only supported for integer, string, or number option types') - - if param.is_choice_annotation(): - raise TypeError( - 'Choice annotation unsupported for autocomplete parameters, consider using a regular annotation instead' - ) - - param.autocomplete = _validate_auto_complete_callback(coro) - return coro - - return decorator - - def add_check(self, func: Check, /) -> None: - """Adds a check to the command. - - This is the non-decorator interface to :func:`check`. - - Parameters - ----------- - func - The function that will be used as a check. - """ - - self.checks.append(func) - - def remove_check(self, func: Check, /) -> None: - """Removes a check from the command. - - This function is idempotent and will not raise an exception - if the function is not in the command's checks. - - Parameters - ----------- - func - The function to remove from the checks. - """ - - try: - self.checks.remove(func) - except ValueError: - pass - - -class ContextMenu: - """A class that implements a context menu application command. - - These are usually not created manually, instead they are created using - one of the following decorators: - - - :func:`~discord.app_commands.context_menu` - - :meth:`CommandTree.command ` - - .. versionadded:: 2.0 - - Parameters - ----------- - name: Union[:class:`str`, :class:`locale_str`] - The name of the context menu. - callback: :ref:`coroutine ` - The coroutine that is executed when the command is called. - type: :class:`.AppCommandType` - The type of context menu application command. By default, this is inferred - by the parameter of the callback. - auto_locale_strings: :class:`bool` - If this is set to ``True``, then all translatable strings will implicitly - be wrapped into :class:`locale_str` rather than :class:`str`. This could - avoid some repetition and be more ergonomic for certain defaults such - as default command names, command descriptions, and parameter names. - Defaults to ``True``. - nsfw: :class:`bool` - Whether the command is NSFW and should only work in NSFW channels. - Defaults to ``False``. - extras: :class:`dict` - A dictionary that can be used to store extraneous data. - The library will not touch any values or keys within this dictionary. - - Attributes - ------------ - name: :class:`str` - The name of the context menu. - type: :class:`.AppCommandType` - The type of context menu application command. By default, this is inferred - by the parameter of the callback. - default_permissions: Optional[:class:`~discord.Permissions`] - The default permissions that can execute this command on Discord. Note - that server administrators can override this value in the client. - Setting an empty permissions field will disallow anyone except server - administrators from using the command in a guild. - guild_only: :class:`bool` - Whether the command should only be usable in guild contexts. - Defaults to ``False``. - nsfw: :class:`bool` - Whether the command is NSFW and should only work in NSFW channels. - Defaults to ``False``. - checks - A list of predicates that take a :class:`~discord.Interaction` parameter - to indicate whether the command callback should be executed. If an exception - is necessary to be thrown to signal failure, then one inherited from - :exc:`AppCommandError` should be used. If all the checks fail without - propagating an exception, :exc:`CheckFailure` is raised. - extras: :class:`dict` - A dictionary that can be used to store extraneous data. - The library will not touch any values or keys within this dictionary. - """ - - def __init__( - self, - *, - name: Union[str, locale_str], - callback: ContextMenuCallback, - type: AppCommandType = MISSING, - nsfw: bool = False, - guild_ids: Optional[List[int]] = None, - auto_locale_strings: bool = True, - extras: Dict[Any, Any] = MISSING, - ): - name, locale = (name.message, name) if isinstance(name, locale_str) else (name, None) - self.name: str = validate_context_menu_name(name) - self._locale_name: Optional[locale_str] = locale - self._callback: ContextMenuCallback = callback - (param, annotation, actual_type) = _get_context_menu_parameter(callback) - if type is MISSING: - type = actual_type - - if actual_type != type: - raise ValueError(f'context menu callback implies a type of {actual_type} but {type} was passed.') - - self.type: AppCommandType = type - self._param_name = param - self._annotation = annotation - self.module: Optional[str] = callback.__module__ - self._guild_ids = guild_ids or getattr(callback, '__discord_app_commands_default_guilds__', None) - self.on_error: Optional[UnboundError] = None - self.default_permissions: Optional[Permissions] = getattr( - callback, '__discord_app_commands_default_permissions__', None - ) - self.nsfw: bool = nsfw - self.guild_only: bool = getattr(callback, '__discord_app_commands_guild_only__', False) - self.checks: List[Check] = getattr(callback, '__discord_app_commands_checks__', []) - self.extras: Dict[Any, Any] = extras or {} - - if auto_locale_strings: - if self._locale_name is None: - self._locale_name = locale_str(self.name) - - @property - def callback(self) -> ContextMenuCallback: - """:ref:`coroutine `: The coroutine that is executed when the context menu is called.""" - return self._callback - - @property - def qualified_name(self) -> str: - """:class:`str`: Returns the fully qualified command name.""" - return self.name - - async def get_translated_payload(self, translator: Translator) -> Dict[str, Any]: - base = self.to_dict() - context = TranslationContext(location=TranslationContextLocation.command_name, data=self) - if self._locale_name: - name_localizations: Dict[str, str] = {} - for locale in Locale: - translation = await translator._checked_translate(self._locale_name, locale, context) - if translation is not None: - name_localizations[locale.value] = translation - - base['name_localizations'] = name_localizations - return base - - def to_dict(self) -> Dict[str, Any]: - return { - 'name': self.name, - 'type': self.type.value, - 'dm_permission': not self.guild_only, - 'default_member_permissions': None if self.default_permissions is None else self.default_permissions.value, - 'nsfw': self.nsfw, - } - - async def _check_can_run(self, interaction: Interaction) -> bool: - predicates = self.checks - if not predicates: - return True - - return await async_all(f(interaction) for f in predicates) - - def _has_any_error_handlers(self) -> bool: - return self.on_error is not None - - async def _invoke(self, interaction: Interaction, arg: Any): - try: - if not await self._check_can_run(interaction): - raise CheckFailure(f'The check functions for context menu {self.name!r} failed.') - - await self._callback(interaction, arg) - except AppCommandError: - raise - except Exception as e: - raise CommandInvokeError(self, e) from e - - def error(self, coro: UnboundError) -> UnboundError: - """A decorator that registers a coroutine as a local error handler. - - The local error handler is called whenever an exception is raised in the body - of the command or during handling of the command. The error handler must take - 2 parameters, the interaction and the error. - - The error passed will be derived from :exc:`AppCommandError`. - - Parameters - ----------- - coro: :ref:`coroutine ` - The coroutine to register as the local error handler. - - Raises - ------- - TypeError - The coroutine passed is not actually a coroutine. - """ - - if not inspect.iscoroutinefunction(coro): - raise TypeError('The error handler must be a coroutine.') - - self.on_error = coro - return coro - - def add_check(self, func: Check, /) -> None: - """Adds a check to the command. - - This is the non-decorator interface to :func:`check`. - - Parameters - ----------- - func - The function that will be used as a check. - """ - - self.checks.append(func) - - def remove_check(self, func: Check, /) -> None: - """Removes a check from the command. - - This function is idempotent and will not raise an exception - if the function is not in the command's checks. - - Parameters - ----------- - func - The function to remove from the checks. - """ - - try: - self.checks.remove(func) - except ValueError: - pass - - -class Group: - """A class that implements an application command group. - - These are usually inherited rather than created manually. - - Decorators such as :func:`guild_only`, :func:`guilds`, and :func:`default_permissions` - will apply to the group if used on top of a subclass. For example: - - .. code-block:: python3 - - from discord import app_commands - - @app_commands.guild_only() - class MyGroup(app_commands.Group): - pass - - .. versionadded:: 2.0 - - Parameters - ----------- - name: Union[:class:`str`, :class:`locale_str`] - The name of the group. If not given, it defaults to a lower-case - kebab-case version of the class name. - description: Union[:class:`str`, :class:`locale_str`] - The description of the group. This shows up in the UI to describe - the group. If not given, it defaults to the docstring of the - class shortened to 100 characters. - auto_locale_strings: :class:`bool` - If this is set to ``True``, then all translatable strings will implicitly - be wrapped into :class:`locale_str` rather than :class:`str`. This could - avoid some repetition and be more ergonomic for certain defaults such - as default command names, command descriptions, and parameter names. - Defaults to ``True``. - default_permissions: Optional[:class:`~discord.Permissions`] - The default permissions that can execute this group on Discord. Note - that server administrators can override this value in the client. - Setting an empty permissions field will disallow anyone except server - administrators from using the command in a guild. - - Due to a Discord limitation, this does not work on subcommands. - guild_only: :class:`bool` - Whether the group should only be usable in guild contexts. - Defaults to ``False``. - - Due to a Discord limitation, this does not work on subcommands. - nsfw: :class:`bool` - Whether the command is NSFW and should only work in NSFW channels. - Defaults to ``False``. - - Due to a Discord limitation, this does not work on subcommands. - parent: Optional[:class:`Group`] - The parent application command. ``None`` if there isn't one. - extras: :class:`dict` - A dictionary that can be used to store extraneous data. - The library will not touch any values or keys within this dictionary. - - Attributes - ------------ - name: :class:`str` - The name of the group. - description: :class:`str` - The description of the group. This shows up in the UI to describe - the group. - default_permissions: Optional[:class:`~discord.Permissions`] - The default permissions that can execute this group on Discord. Note - that server administrators can override this value in the client. - Setting an empty permissions field will disallow anyone except server - administrators from using the command in a guild. - - Due to a Discord limitation, this does not work on subcommands. - guild_only: :class:`bool` - Whether the group should only be usable in guild contexts. - - Due to a Discord limitation, this does not work on subcommands. - nsfw: :class:`bool` - Whether the command is NSFW and should only work in NSFW channels. - - Due to a Discord limitation, this does not work on subcommands. - parent: Optional[:class:`Group`] - The parent group. ``None`` if there isn't one. - extras: :class:`dict` - A dictionary that can be used to store extraneous data. - The library will not touch any values or keys within this dictionary. - """ - - __discord_app_commands_group_children__: ClassVar[List[Union[Command[Any, ..., Any], Group]]] = [] - __discord_app_commands_skip_init_binding__: bool = False - __discord_app_commands_group_name__: str = MISSING - __discord_app_commands_group_description__: str = MISSING - __discord_app_commands_group_locale_name__: Optional[locale_str] = None - __discord_app_commands_group_locale_description__: Optional[locale_str] = None - __discord_app_commands_group_nsfw__: bool = False - __discord_app_commands_guild_only__: bool = MISSING - __discord_app_commands_default_permissions__: Optional[Permissions] = MISSING - __discord_app_commands_has_module__: bool = False - __discord_app_commands_error_handler__: Optional[ - Callable[[Interaction, AppCommandError], Coroutine[Any, Any, None]] - ] = None - - def __init_subclass__( - cls, - *, - name: Union[str, locale_str] = MISSING, - description: Union[str, locale_str] = MISSING, - guild_only: bool = MISSING, - nsfw: bool = False, - default_permissions: Optional[Permissions] = MISSING, - ) -> None: - if not cls.__discord_app_commands_group_children__: - children: List[Union[Command[Any, ..., Any], Group]] = [ - member for member in cls.__dict__.values() if isinstance(member, (Group, Command)) and member.parent is None - ] - - cls.__discord_app_commands_group_children__ = children - - found = set() - for child in children: - if child.name in found: - raise TypeError(f'Command {child.name!r} is a duplicate') - found.add(child.name) - - if len(children) > 25: - raise TypeError('groups cannot have more than 25 commands') - - if name is MISSING: - cls.__discord_app_commands_group_name__ = validate_name(_to_kebab_case(cls.__name__)) - elif isinstance(name, str): - cls.__discord_app_commands_group_name__ = validate_name(name) - else: - cls.__discord_app_commands_group_name__ = validate_name(name.message) - cls.__discord_app_commands_group_locale_name__ = name - - if description is MISSING: - if cls.__doc__ is None: - cls.__discord_app_commands_group_description__ = '…' - else: - cls.__discord_app_commands_group_description__ = _shorten(cls.__doc__) - elif isinstance(description, str): - cls.__discord_app_commands_group_description__ = description - else: - cls.__discord_app_commands_group_description__ = description.message - cls.__discord_app_commands_group_locale_description__ = description - - if guild_only is not MISSING: - cls.__discord_app_commands_guild_only__ = guild_only - - if default_permissions is not MISSING: - cls.__discord_app_commands_default_permissions__ = default_permissions - - if cls.__module__ != __name__: - cls.__discord_app_commands_has_module__ = True - cls.__discord_app_commands_group_nsfw__ = nsfw - - def __init__( - self, - *, - name: Union[str, locale_str] = MISSING, - description: Union[str, locale_str] = MISSING, - parent: Optional[Group] = None, - guild_ids: Optional[List[int]] = None, - guild_only: bool = MISSING, - nsfw: bool = MISSING, - auto_locale_strings: bool = True, - default_permissions: Optional[Permissions] = MISSING, - extras: Dict[Any, Any] = MISSING, - ): - cls = self.__class__ - - if name is MISSING: - name, locale = cls.__discord_app_commands_group_name__, cls.__discord_app_commands_group_locale_name__ - elif isinstance(name, str): - name, locale = validate_name(name), None - else: - name, locale = validate_name(name.message), name - self.name: str = name - self._locale_name: Optional[locale_str] = locale - - if description is MISSING: - description, locale = ( - cls.__discord_app_commands_group_description__, - cls.__discord_app_commands_group_locale_description__, - ) - elif isinstance(description, str): - description, locale = description, None - else: - description, locale = description.message, description - self.description: str = description - self._locale_description: Optional[locale_str] = locale - - self._attr: Optional[str] = None - self._owner_cls: Optional[Type[Any]] = None - self._guild_ids: Optional[List[int]] = guild_ids or getattr(cls, '__discord_app_commands_default_guilds__', None) - - if default_permissions is MISSING: - if cls.__discord_app_commands_default_permissions__ is MISSING: - default_permissions = None - else: - default_permissions = cls.__discord_app_commands_default_permissions__ - - self.default_permissions: Optional[Permissions] = default_permissions - - if guild_only is MISSING: - if cls.__discord_app_commands_guild_only__ is MISSING: - guild_only = False - else: - guild_only = cls.__discord_app_commands_guild_only__ - - self.guild_only: bool = guild_only - - if nsfw is MISSING: - nsfw = cls.__discord_app_commands_group_nsfw__ - - self.nsfw: bool = nsfw - - if not self.description: - raise TypeError('groups must have a description') - - self.parent: Optional[Group] = parent - self.module: Optional[str] - if cls.__discord_app_commands_has_module__: - self.module = cls.__module__ - else: - try: - # This is pretty hacky - # It allows the module to be fetched if someone just constructs a bare Group object though. - self.module = inspect.currentframe().f_back.f_globals['__name__'] # type: ignore - except (AttributeError, IndexError): - self.module = None - - self._children: Dict[str, Union[Command, Group]] = {} - self.extras: Dict[Any, Any] = extras or {} - - bindings: Dict[Group, Group] = {} - - for child in self.__discord_app_commands_group_children__: - # commands and groups created directly in this class (no parent) - copy = ( - child._copy_with(parent=self, binding=self, bindings=bindings, set_on_binding=False) - if not cls.__discord_app_commands_skip_init_binding__ - else child - ) - - self._children[copy.name] = copy - if copy._attr and not cls.__discord_app_commands_skip_init_binding__: - setattr(self, copy._attr, copy) - - if parent is not None: - if parent.parent is not None: - raise ValueError('groups can only be nested at most one level') - parent.add_command(self) - - if auto_locale_strings: - self._convert_to_locale_strings() - - def _convert_to_locale_strings(self) -> None: - if self._locale_name is None: - self._locale_name = locale_str(self.name) - if self._locale_description is None: - self._locale_description = locale_str(self.description) - - # I don't know if propagating to the children is the right behaviour here. - - def __set_name__(self, owner: Type[Any], name: str) -> None: - self._attr = name - self.module = owner.__module__ - self._owner_cls = owner - - def _copy_with( - self, - *, - parent: Optional[Group], - binding: Binding, - bindings: MutableMapping[Group, Group] = MISSING, - set_on_binding: bool = True, - ) -> Group: - bindings = {} if bindings is MISSING else bindings - - cls = self.__class__ - copy = cls.__new__(cls) - copy.name = self.name - copy._locale_name = self._locale_name - copy._guild_ids = self._guild_ids - copy.description = self.description - copy._locale_description = self._locale_description - copy.parent = parent - copy.module = self.module - copy.default_permissions = self.default_permissions - copy.guild_only = self.guild_only - copy.nsfw = self.nsfw - copy._attr = self._attr - copy._owner_cls = self._owner_cls - copy._children = {} - copy.extras = self.extras - - bindings[self] = copy - - for child in self._children.values(): - child_copy = child._copy_with(parent=copy, binding=binding, bindings=bindings) - child_copy.parent = copy - copy._children[child_copy.name] = child_copy - - if isinstance(child_copy, Group) and child_copy._attr and set_on_binding: - if binding.__class__ is child_copy._owner_cls: - setattr(binding, child_copy._attr, child_copy) - elif child_copy._owner_cls is copy.__class__: - setattr(copy, child_copy._attr, child_copy) - - if copy._attr and set_on_binding: - setattr(parent or binding, copy._attr, copy) - - return copy - - async def get_translated_payload(self, translator: Translator) -> Dict[str, Any]: - base = self.to_dict() - name_localizations: Dict[str, str] = {} - description_localizations: Dict[str, str] = {} - - # Prevent creating these objects in a heavy loop - name_context = TranslationContext(location=TranslationContextLocation.group_name, data=self) - description_context = TranslationContext(location=TranslationContextLocation.group_description, data=self) - for locale in Locale: - if self._locale_name: - translation = await translator._checked_translate(self._locale_name, locale, name_context) - if translation is not None: - name_localizations[locale.value] = translation - - if self._locale_description: - translation = await translator._checked_translate(self._locale_description, locale, description_context) - if translation is not None: - description_localizations[locale.value] = translation - - base['name_localizations'] = name_localizations - base['description_localizations'] = description_localizations - base['options'] = [await child.get_translated_payload(translator) for child in self._children.values()] - return base - - def to_dict(self) -> Dict[str, Any]: - # If this has a parent command then it's part of a subcommand group - # Otherwise, it's just a regular command - option_type = 1 if self.parent is None else AppCommandOptionType.subcommand_group.value - base: Dict[str, Any] = { - 'name': self.name, - 'description': self.description, - 'type': option_type, - 'options': [child.to_dict() for child in self._children.values()], - } - - if self.parent is None: - base['nsfw'] = self.nsfw - base['dm_permission'] = not self.guild_only - base['default_member_permissions'] = None if self.default_permissions is None else self.default_permissions.value - - return base - - @property - def root_parent(self) -> Optional[Group]: - """Optional[:class:`Group`]: The parent of this group.""" - return self.parent - - @property - def qualified_name(self) -> str: - """:class:`str`: Returns the fully qualified group name. - - The qualified name includes the parent name as well. For example, - in a group like ``/foo bar`` the qualified name is ``foo bar``. - """ - - if self.parent is None: - return self.name - return f'{self.parent.name} {self.name}' - - def _get_internal_command(self, name: str) -> Optional[Union[Command[Any, ..., Any], Group]]: - return self._children.get(name) - - @property - def commands(self) -> List[Union[Command[Any, ..., Any], Group]]: - """List[Union[:class:`Command`, :class:`Group`]]: The commands that this group contains.""" - return list(self._children.values()) - - def walk_commands(self) -> Generator[Union[Command[Any, ..., Any], Group], None, None]: - """An iterator that recursively walks through all commands that this group contains. - - Yields - --------- - Union[:class:`Command`, :class:`Group`] - The commands in this group. - """ - - for command in self._children.values(): - yield command - if isinstance(command, Group): - yield from command.walk_commands() - - async def on_error(self, interaction: Interaction, error: AppCommandError, /) -> None: - """|coro| - - A callback that is called when a child's command raises an :exc:`AppCommandError`. - - To get the command that failed, :attr:`discord.Interaction.command` should be used. - - The default implementation does nothing. - - Parameters - ----------- - interaction: :class:`~discord.Interaction` - The interaction that is being handled. - error: :exc:`AppCommandError` - The exception that was raised. - """ - - pass - - def error(self, coro: ErrorFunc) -> ErrorFunc: - """A decorator that registers a coroutine as a local error handler. - - The local error handler is called whenever an exception is raised in a child command. - The error handler must take 2 parameters, the interaction and the error. - - The error passed will be derived from :exc:`AppCommandError`. - - Parameters - ----------- - coro: :ref:`coroutine ` - The coroutine to register as the local error handler. - - Raises - ------- - TypeError - The coroutine passed is not actually a coroutine, or is an invalid coroutine. - """ - - if not inspect.iscoroutinefunction(coro): - raise TypeError('The error handler must be a coroutine.') - - params = inspect.signature(coro).parameters - if len(params) != 2: - raise TypeError('The error handler must have 2 parameters.') - - self.on_error = coro - return coro - - async def interaction_check(self, interaction: Interaction, /) -> bool: - """|coro| - - A callback that is called when an interaction happens within the group - that checks whether a command inside the group should be executed. - - This is useful to override if, for example, you want to ensure that the - interaction author is a given user. - - The default implementation of this returns ``True``. - - .. note:: - - If an exception occurs within the body then the check - is considered a failure and error handlers such as - :meth:`on_error` is called. See :exc:`AppCommandError` - for more information. - - Parameters - ----------- - interaction: :class:`~discord.Interaction` - The interaction that occurred. - - Returns - --------- - :class:`bool` - Whether the view children's callbacks should be called. - """ - - return True - - def add_command(self, command: Union[Command[Any, ..., Any], Group], /, *, override: bool = False) -> None: - """Adds a command or group to this group's internal list of commands. - - Parameters - ----------- - command: Union[:class:`Command`, :class:`Group`] - The command or group to add. - override: :class:`bool` - Whether to override a pre-existing command or group with the same name. - If ``False`` then an exception is raised. - - Raises - ------- - CommandAlreadyRegistered - The command or group is already registered. Note that the :attr:`CommandAlreadyRegistered.guild_id` - attribute will always be ``None`` in this case. - ValueError - There are too many commands already registered or the group is too - deeply nested. - TypeError - The wrong command type was passed. - """ - - if not isinstance(command, (Command, Group)): - raise TypeError(f'expected Command or Group not {command.__class__!r}') - - if isinstance(command, Group) and self.parent is not None: - # In a tree like so: - # - # - # - # this needs to be forbidden - raise ValueError(f'{command.name!r} is too nested, groups can only be nested at most one level') - - if not override and command.name in self._children: - raise CommandAlreadyRegistered(command.name, guild_id=None) - - self._children[command.name] = command - command.parent = self - if len(self._children) > 25: - raise ValueError('maximum number of child commands exceeded') - - def remove_command(self, name: str, /) -> Optional[Union[Command[Any, ..., Any], Group]]: - """Removes a command or group from the internal list of commands. - - Parameters - ----------- - name: :class:`str` - The name of the command or group to remove. - - Returns - -------- - Optional[Union[:class:`~discord.app_commands.Command`, :class:`~discord.app_commands.Group`]] - The command that was removed. If nothing was removed - then ``None`` is returned instead. - """ - - self._children.pop(name, None) - - def get_command(self, name: str, /) -> Optional[Union[Command[Any, ..., Any], Group]]: - """Retrieves a command or group from its name. - - Parameters - ----------- - name: :class:`str` - The name of the command or group to retrieve. - - Returns - -------- - Optional[Union[:class:`~discord.app_commands.Command`, :class:`~discord.app_commands.Group`]] - The command or group that was retrieved. If nothing was found - then ``None`` is returned instead. - """ - return self._children.get(name) - - def command( - self, - *, - name: Union[str, locale_str] = MISSING, - description: Union[str, locale_str] = MISSING, - nsfw: bool = False, - auto_locale_strings: bool = True, - extras: Dict[Any, Any] = MISSING, - ) -> Callable[[CommandCallback[GroupT, P, T]], Command[GroupT, P, T]]: - """A decorator that creates an application command from a regular function under this group. - - Parameters - ------------ - name: Union[:class:`str`, :class:`locale_str`] - The name of the application command. If not given, it defaults to a lower-case - version of the callback name. - description: Union[:class:`str`, :class:`locale_str`] - The description of the application command. This shows up in the UI to describe - the application command. If not given, it defaults to the first line of the docstring - of the callback shortened to 100 characters. - nsfw: :class:`bool` - Whether the command is NSFW and should only work in NSFW channels. Defaults to ``False``. - auto_locale_strings: :class:`bool` - If this is set to ``True``, then all translatable strings will implicitly - be wrapped into :class:`locale_str` rather than :class:`str`. This could - avoid some repetition and be more ergonomic for certain defaults such - as default command names, command descriptions, and parameter names. - Defaults to ``True``. - extras: :class:`dict` - A dictionary that can be used to store extraneous data. - The library will not touch any values or keys within this dictionary. - """ - - def decorator(func: CommandCallback[GroupT, P, T]) -> Command[GroupT, P, T]: - if not inspect.iscoroutinefunction(func): - raise TypeError('command function must be a coroutine function') - - if description is MISSING: - if func.__doc__ is None: - desc = '…' - else: - desc = _shorten(func.__doc__) - else: - desc = description - - command = Command( - name=name if name is not MISSING else func.__name__, - description=desc, - callback=func, - nsfw=nsfw, - parent=self, - auto_locale_strings=auto_locale_strings, - extras=extras, - ) - self.add_command(command) - return command - - return decorator - - -def command( - *, - name: Union[str, locale_str] = MISSING, - description: Union[str, locale_str] = MISSING, - nsfw: bool = False, - auto_locale_strings: bool = True, - extras: Dict[Any, Any] = MISSING, -) -> Callable[[CommandCallback[GroupT, P, T]], Command[GroupT, P, T]]: - """Creates an application command from a regular function. - - Parameters - ------------ - name: :class:`str` - The name of the application command. If not given, it defaults to a lower-case - version of the callback name. - description: :class:`str` - The description of the application command. This shows up in the UI to describe - the application command. If not given, it defaults to the first line of the docstring - of the callback shortened to 100 characters. - nsfw: :class:`bool` - Whether the command is NSFW and should only work in NSFW channels. Defaults to ``False``. - - Due to a Discord limitation, this does not work on subcommands. - auto_locale_strings: :class:`bool` - If this is set to ``True``, then all translatable strings will implicitly - be wrapped into :class:`locale_str` rather than :class:`str`. This could - avoid some repetition and be more ergonomic for certain defaults such - as default command names, command descriptions, and parameter names. - Defaults to ``True``. - extras: :class:`dict` - A dictionary that can be used to store extraneous data. - The library will not touch any values or keys within this dictionary. - """ - - def decorator(func: CommandCallback[GroupT, P, T]) -> Command[GroupT, P, T]: - if not inspect.iscoroutinefunction(func): - raise TypeError('command function must be a coroutine function') - - if description is MISSING: - if func.__doc__ is None: - desc = '…' - else: - desc = _shorten(func.__doc__) - else: - desc = description - - return Command( - name=name if name is not MISSING else func.__name__, - description=desc, - callback=func, - parent=None, - nsfw=nsfw, - auto_locale_strings=auto_locale_strings, - extras=extras, - ) - - return decorator - - -def context_menu( - *, - name: Union[str, locale_str] = MISSING, - nsfw: bool = False, - auto_locale_strings: bool = True, - extras: Dict[Any, Any] = MISSING, -) -> Callable[[ContextMenuCallback], ContextMenu]: - """Creates an application command context menu from a regular function. - - This function must have a signature of :class:`~discord.Interaction` as its first parameter - and taking either a :class:`~discord.Member`, :class:`~discord.User`, or :class:`~discord.Message`, - or a :obj:`typing.Union` of ``Member`` and ``User`` as its second parameter. - - Examples - --------- - - .. code-block:: python3 - - @app_commands.context_menu() - async def react(interaction: discord.Interaction, message: discord.Message): - await interaction.response.send_message('Very cool message!', ephemeral=True) - - @app_commands.context_menu() - async def ban(interaction: discord.Interaction, user: discord.Member): - await interaction.response.send_message(f'Should I actually ban {user}...', ephemeral=True) - - Parameters - ------------ - name: Union[:class:`str`, :class:`locale_str`] - The name of the context menu command. If not given, it defaults to a title-case - version of the callback name. Note that unlike regular slash commands this can - have spaces and upper case characters in the name. - nsfw: :class:`bool` - Whether the command is NSFW and should only work in NSFW channels. Defaults to ``False``. - - Due to a Discord limitation, this does not work on subcommands. - auto_locale_strings: :class:`bool` - If this is set to ``True``, then all translatable strings will implicitly - be wrapped into :class:`locale_str` rather than :class:`str`. This could - avoid some repetition and be more ergonomic for certain defaults such - as default command names, command descriptions, and parameter names. - Defaults to ``True``. - extras: :class:`dict` - A dictionary that can be used to store extraneous data. - The library will not touch any values or keys within this dictionary. - """ - - def decorator(func: ContextMenuCallback) -> ContextMenu: - if not inspect.iscoroutinefunction(func): - raise TypeError('context menu function must be a coroutine function') - - actual_name = func.__name__.title() if name is MISSING else name - return ContextMenu( - name=actual_name, - nsfw=nsfw, - callback=func, - auto_locale_strings=auto_locale_strings, - extras=extras, - ) - - return decorator - - -def describe(**parameters: Union[str, locale_str]) -> Callable[[T], T]: - r'''Describes the given parameters by their name using the key of the keyword argument - as the name. - - Example: - - .. code-block:: python3 - - @app_commands.command(description='Bans a member') - @app_commands.describe(member='the member to ban') - async def ban(interaction: discord.Interaction, member: discord.Member): - await interaction.response.send_message(f'Banned {member}') - - Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings. - - Example: - - .. code-block:: python3 - - @app_commands.command() - async def ban(interaction: discord.Interaction, member: discord.Member): - """Bans a member - - Parameters - ----------- - member: discord.Member - the member to ban - """ - await interaction.response.send_message(f'Banned {member}') - - Parameters - ----------- - \*\*parameters: Union[:class:`str`, :class:`locale_str`] - The description of the parameters. - - Raises - -------- - TypeError - The parameter name is not found. - ''' - - def decorator(inner: T) -> T: - if isinstance(inner, Command): - _populate_descriptions(inner._params, parameters) - else: - try: - inner.__discord_app_commands_param_description__.update(parameters) # type: ignore # Runtime attribute access - except AttributeError: - inner.__discord_app_commands_param_description__ = parameters # type: ignore # Runtime attribute assignment - - return inner - - return decorator - - -def rename(**parameters: Union[str, locale_str]) -> Callable[[T], T]: - r"""Renames the given parameters by their name using the key of the keyword argument - as the name. - - This renames the parameter within the Discord UI. When referring to the parameter in other - decorators, the parameter name used in the function is used instead of the renamed one. - - Example: - - .. code-block:: python3 - - @app_commands.command() - @app_commands.rename(the_member_to_ban='member') - async def ban(interaction: discord.Interaction, the_member_to_ban: discord.Member): - await interaction.response.send_message(f'Banned {the_member_to_ban}') - - Parameters - ----------- - \*\*parameters: Union[:class:`str`, :class:`locale_str`] - The name of the parameters. - - Raises - -------- - ValueError - The parameter name is already used by another parameter. - TypeError - The parameter name is not found. - """ - - def decorator(inner: T) -> T: - if isinstance(inner, Command): - _populate_renames(inner._params, parameters) - else: - try: - inner.__discord_app_commands_param_rename__.update(parameters) # type: ignore # Runtime attribute access - except AttributeError: - inner.__discord_app_commands_param_rename__ = parameters # type: ignore # Runtime attribute assignment - - return inner - - return decorator - - -def choices(**parameters: List[Choice[ChoiceT]]) -> Callable[[T], T]: - r"""Instructs the given parameters by their name to use the given choices for their choices. - - Example: - - .. code-block:: python3 - - @app_commands.command() - @app_commands.describe(fruits='fruits to choose from') - @app_commands.choices(fruits=[ - Choice(name='apple', value=1), - Choice(name='banana', value=2), - Choice(name='cherry', value=3), - ]) - async def fruit(interaction: discord.Interaction, fruits: Choice[int]): - await interaction.response.send_message(f'Your favourite fruit is {fruits.name}.') - - .. note:: - - This is not the only way to provide choices to a command. There are two more ergonomic ways - of doing this. The first one is to use a :obj:`typing.Literal` annotation: - - .. code-block:: python3 - - @app_commands.command() - @app_commands.describe(fruits='fruits to choose from') - async def fruit(interaction: discord.Interaction, fruits: Literal['apple', 'banana', 'cherry']): - await interaction.response.send_message(f'Your favourite fruit is {fruits}.') - - The second way is to use an :class:`enum.Enum`: - - .. code-block:: python3 - - class Fruits(enum.Enum): - apple = 1 - banana = 2 - cherry = 3 - - @app_commands.command() - @app_commands.describe(fruits='fruits to choose from') - async def fruit(interaction: discord.Interaction, fruits: Fruits): - await interaction.response.send_message(f'Your favourite fruit is {fruits}.') - - - Parameters - ----------- - \*\*parameters - The choices of the parameters. - - Raises - -------- - TypeError - The parameter name is not found or the parameter type was incorrect. - """ - - def decorator(inner: T) -> T: - if isinstance(inner, Command): - _populate_choices(inner._params, parameters) - else: - try: - inner.__discord_app_commands_param_choices__.update(parameters) # type: ignore # Runtime attribute access - except AttributeError: - inner.__discord_app_commands_param_choices__ = parameters # type: ignore # Runtime attribute assignment - - return inner - - return decorator - - -def autocomplete(**parameters: AutocompleteCallback[GroupT, ChoiceT]) -> Callable[[T], T]: - r"""Associates the given parameters with the given autocomplete callback. - - Autocomplete is only supported on types that have :class:`str`, :class:`int`, or :class:`float` - values. - - :func:`Checks ` are supported, however they must be attached to the autocomplete - callback in order to work. Checks attached to the command are ignored when invoking the autocomplete - callback. - - For more information, see the :meth:`Command.autocomplete` documentation. - - Example: - - .. code-block:: python3 - - async def fruit_autocomplete( - interaction: discord.Interaction, - current: str, - ) -> List[app_commands.Choice[str]]: - fruits = ['Banana', 'Pineapple', 'Apple', 'Watermelon', 'Melon', 'Cherry'] - return [ - app_commands.Choice(name=fruit, value=fruit) - for fruit in fruits if current.lower() in fruit.lower() - ] - - @app_commands.command() - @app_commands.autocomplete(fruit=fruit_autocomplete) - async def fruits(interaction: discord.Interaction, fruit: str): - await interaction.response.send_message(f'Your favourite fruit seems to be {fruit}') - - Parameters - ----------- - \*\*parameters - The parameters to mark as autocomplete. - - Raises - -------- - TypeError - The parameter name is not found or the parameter type was incorrect. - """ - - def decorator(inner: T) -> T: - if isinstance(inner, Command): - _populate_autocomplete(inner._params, parameters) - else: - try: - inner.__discord_app_commands_param_autocomplete__.update(parameters) # type: ignore # Runtime attribute access - except AttributeError: - inner.__discord_app_commands_param_autocomplete__ = parameters # type: ignore # Runtime attribute assignment - - return inner - - return decorator - - -def guilds(*guild_ids: Union[Snowflake, int]) -> Callable[[T], T]: - r"""Associates the given guilds with the command. - - When the command instance is added to a :class:`CommandTree`, the guilds that are - specified by this decorator become the default guilds that it's added to rather - than being a global command. - - .. note:: - - Due to an implementation quirk and Python limitation, if this is used in conjunction - with the :meth:`CommandTree.command` or :meth:`CommandTree.context_menu` decorator - then this must go below that decorator. - - Example: - - .. code-block:: python3 - - MY_GUILD_ID = discord.Object(...) # Guild ID here - - @app_commands.command() - @app_commands.guilds(MY_GUILD_ID) - async def bonk(interaction: discord.Interaction): - await interaction.response.send_message('Bonk', ephemeral=True) - - Parameters - ----------- - \*guild_ids: Union[:class:`int`, :class:`~discord.abc.Snowflake`] - The guilds to associate this command with. The command tree will - use this as the default when added rather than adding it as a global - command. - """ - - defaults: List[int] = [g if isinstance(g, int) else g.id for g in guild_ids] - - def decorator(inner: T) -> T: - if isinstance(inner, (Group, ContextMenu)): - inner._guild_ids = defaults - elif isinstance(inner, Command): - if inner.parent is not None: - raise ValueError('child commands of a group cannot have default guilds set') - - inner._guild_ids = defaults - else: - # Runtime attribute assignment - inner.__discord_app_commands_default_guilds__ = defaults # type: ignore - - return inner - - return decorator - - -def check(predicate: Check) -> Callable[[T], T]: - r"""A decorator that adds a check to an application command. - - These checks should be predicates that take in a single parameter taking - a :class:`~discord.Interaction`. If the check returns a ``False``\-like value then - during invocation a :exc:`CheckFailure` exception is raised and sent to - the appropriate error handlers. - - These checks can be either a coroutine or not. - - Examples - --------- - - Creating a basic check to see if the command invoker is you. - - .. code-block:: python3 - - def check_if_it_is_me(interaction: discord.Interaction) -> bool: - return interaction.user.id == 85309593344815104 - - @tree.command() - @app_commands.check(check_if_it_is_me) - async def only_for_me(interaction: discord.Interaction): - await interaction.response.send_message('I know you!', ephemeral=True) - - Transforming common checks into its own decorator: - - .. code-block:: python3 - - def is_me(): - def predicate(interaction: discord.Interaction) -> bool: - return interaction.user.id == 85309593344815104 - return app_commands.check(predicate) - - @tree.command() - @is_me() - async def only_me(interaction: discord.Interaction): - await interaction.response.send_message('Only you!') - - Parameters - ----------- - predicate: Callable[[:class:`~discord.Interaction`], :class:`bool`] - The predicate to check if the command should be invoked. - """ - - def decorator(func: CheckInputParameter) -> CheckInputParameter: - if isinstance(func, (Command, ContextMenu)): - func.checks.append(predicate) - else: - if not hasattr(func, '__discord_app_commands_checks__'): - func.__discord_app_commands_checks__ = [] - - func.__discord_app_commands_checks__.append(predicate) - - return func - - return decorator # type: ignore - - -@overload -def guild_only(func: None = ...) -> Callable[[T], T]: - ... - - -@overload -def guild_only(func: T) -> T: - ... - - -def guild_only(func: Optional[T] = None) -> Union[T, Callable[[T], T]]: - """A decorator that indicates this command can only be used in a guild context. - - This is **not** implemented as a :func:`check`, and is instead verified by Discord server side. - Therefore, there is no error handler called when a command is used within a private message. - - This decorator can be called with or without parentheses. - - Due to a Discord limitation, this decorator does nothing in subcommands and is ignored. - - Examples - --------- - - .. code-block:: python3 - - @app_commands.command() - @app_commands.guild_only() - async def my_guild_only_command(interaction: discord.Interaction) -> None: - await interaction.response.send_message('I am only available in guilds!') - """ - - def inner(f: T) -> T: - if isinstance(f, (Command, Group, ContextMenu)): - f.guild_only = True - else: - f.__discord_app_commands_guild_only__ = True # type: ignore # Runtime attribute assignment - return f - - # Check if called with parentheses or not - if func is None: - # Called with parentheses - return inner - else: - return inner(func) - - -def default_permissions(**perms: bool) -> Callable[[T], T]: - r"""A decorator that sets the default permissions needed to execute this command. - - When this decorator is used, by default users must have these permissions to execute the command. - However, an administrator can change the permissions needed to execute this command using the official - client. Therefore, this only serves as a hint. - - Setting an empty permissions field, including via calling this with no arguments, will disallow anyone - except server administrators from using the command in a guild. - - This is sent to Discord server side, and is not a :func:`check`. Therefore, error handlers are not called. - - Due to a Discord limitation, this decorator does nothing in subcommands and is ignored. - - .. warning:: - - This serves as a *hint* and members are *not* required to have the permissions given to actually - execute this command. If you want to ensure that members have the permissions needed, consider using - :func:`~discord.app_commands.checks.has_permissions` instead. - - Parameters - ----------- - \*\*perms: :class:`bool` - Keyword arguments denoting the permissions to set as the default. - - Example - --------- - - .. code-block:: python3 - - @app_commands.command() - @app_commands.default_permissions(manage_messages=True) - async def test(interaction: discord.Interaction): - await interaction.response.send_message('You may or may not have manage messages.') - """ - - permissions = Permissions(**perms) - - def decorator(func: T) -> T: - if isinstance(func, (Command, Group, ContextMenu)): - func.default_permissions = permissions - else: - func.__discord_app_commands_default_permissions__ = permissions # type: ignore # Runtime attribute assignment - - return func - - return decorator diff --git a/.venv/Lib/site-packages/discord/app_commands/errors.py b/.venv/Lib/site-packages/discord/app_commands/errors.py deleted file mode 100644 index 69c40c8..0000000 --- a/.venv/Lib/site-packages/discord/app_commands/errors.py +++ /dev/null @@ -1,528 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations - -from typing import Any, TYPE_CHECKING, List, Optional, Sequence, Union - -from ..enums import AppCommandOptionType, AppCommandType, Locale -from ..errors import DiscordException, HTTPException, _flatten_error_dict - -__all__ = ( - 'AppCommandError', - 'CommandInvokeError', - 'TransformerError', - 'TranslationError', - 'CheckFailure', - 'CommandAlreadyRegistered', - 'CommandSignatureMismatch', - 'CommandNotFound', - 'CommandLimitReached', - 'NoPrivateMessage', - 'MissingRole', - 'MissingAnyRole', - 'MissingPermissions', - 'BotMissingPermissions', - 'CommandOnCooldown', - 'MissingApplicationID', - 'CommandSyncFailure', -) - -if TYPE_CHECKING: - from .commands import Command, Group, ContextMenu, Parameter - from .transformers import Transformer - from .translator import TranslationContextTypes, locale_str - from ..types.snowflake import Snowflake, SnowflakeList - from .checks import Cooldown - - CommandTypes = Union[Command[Any, ..., Any], Group, ContextMenu] - -APP_ID_NOT_FOUND = ( - 'Client does not have an application_id set. Either the function was called before on_ready ' - 'was called or application_id was not passed to the Client constructor.' -) - - -class AppCommandError(DiscordException): - """The base exception type for all application command related errors. - - This inherits from :exc:`discord.DiscordException`. - - This exception and exceptions inherited from it are handled - in a special way as they are caught and passed into various error handlers - in this order: - - - :meth:`Command.error ` - - :meth:`Group.on_error ` - - :meth:`CommandTree.on_error ` - - .. versionadded:: 2.0 - """ - - pass - - -class CommandInvokeError(AppCommandError): - """An exception raised when the command being invoked raised an exception. - - This inherits from :exc:`~discord.app_commands.AppCommandError`. - - .. versionadded:: 2.0 - - Attributes - ----------- - original: :exc:`Exception` - The original exception that was raised. You can also get this via - the ``__cause__`` attribute. - command: Union[:class:`Command`, :class:`ContextMenu`] - The command that failed. - """ - - def __init__(self, command: Union[Command[Any, ..., Any], ContextMenu], e: Exception) -> None: - self.original: Exception = e - self.command: Union[Command[Any, ..., Any], ContextMenu] = command - super().__init__(f'Command {command.name!r} raised an exception: {e.__class__.__name__}: {e}') - - -class TransformerError(AppCommandError): - """An exception raised when a :class:`Transformer` or type annotation fails to - convert to its target type. - - This inherits from :exc:`~discord.app_commands.AppCommandError`. - - If an exception occurs while converting that does not subclass - :exc:`AppCommandError` then the exception is wrapped into this exception. - The original exception can be retrieved using the ``__cause__`` attribute. - Otherwise if the exception derives from :exc:`AppCommandError` then it will - be propagated as-is. - - .. versionadded:: 2.0 - - Attributes - ----------- - value: Any - The value that failed to convert. - type: :class:`~discord.AppCommandOptionType` - The type of argument that failed to convert. - transformer: :class:`Transformer` - The transformer that failed the conversion. - """ - - def __init__(self, value: Any, opt_type: AppCommandOptionType, transformer: Transformer): - self.value: Any = value - self.type: AppCommandOptionType = opt_type - self.transformer: Transformer = transformer - - super().__init__(f'Failed to convert {value} to {transformer._error_display_name!s}') - - -class TranslationError(AppCommandError): - """An exception raised when the library fails to translate a string. - - This inherits from :exc:`~discord.app_commands.AppCommandError`. - - If an exception occurs while calling :meth:`Translator.translate` that does - not subclass this then the exception is wrapped into this exception. - The original exception can be retrieved using the ``__cause__`` attribute. - Otherwise it will be propagated as-is. - - .. versionadded:: 2.0 - - Attributes - ----------- - string: Optional[Union[:class:`str`, :class:`locale_str`]] - The string that caused the error, if any. - locale: Optional[:class:`~discord.Locale`] - The locale that caused the error, if any. - context: :class:`~discord.app_commands.TranslationContext` - The context of the translation that triggered the error. - """ - - def __init__( - self, - *msg: str, - string: Optional[Union[str, locale_str]] = None, - locale: Optional[Locale] = None, - context: TranslationContextTypes, - ) -> None: - self.string: Optional[Union[str, locale_str]] = string - self.locale: Optional[Locale] = locale - self.context: TranslationContextTypes = context - - if msg: - super().__init__(*msg) - else: - ctx = context.location.name.replace('_', ' ') - fmt = f'Failed to translate {self.string!r} in a {ctx}' - if self.locale is not None: - fmt = f'{fmt} in the {self.locale.value} locale' - - super().__init__(fmt) - - -class CheckFailure(AppCommandError): - """An exception raised when check predicates in a command have failed. - - This inherits from :exc:`~discord.app_commands.AppCommandError`. - - .. versionadded:: 2.0 - """ - - pass - - -class NoPrivateMessage(CheckFailure): - """An exception raised when a command does not work in a direct message. - - This inherits from :exc:`~discord.app_commands.CheckFailure`. - - .. versionadded:: 2.0 - """ - - def __init__(self, message: Optional[str] = None) -> None: - super().__init__(message or 'This command cannot be used in direct messages.') - - -class MissingRole(CheckFailure): - """An exception raised when the command invoker lacks a role to run a command. - - This inherits from :exc:`~discord.app_commands.CheckFailure`. - - .. versionadded:: 2.0 - - Attributes - ----------- - missing_role: Union[:class:`str`, :class:`int`] - The required role that is missing. - This is the parameter passed to :func:`~discord.app_commands.checks.has_role`. - """ - - def __init__(self, missing_role: Snowflake) -> None: - self.missing_role: Snowflake = missing_role - message = f'Role {missing_role!r} is required to run this command.' - super().__init__(message) - - -class MissingAnyRole(CheckFailure): - """An exception raised when the command invoker lacks any of the roles - specified to run a command. - - This inherits from :exc:`~discord.app_commands.CheckFailure`. - - .. versionadded:: 2.0 - - Attributes - ----------- - missing_roles: List[Union[:class:`str`, :class:`int`]] - The roles that the invoker is missing. - These are the parameters passed to :func:`~discord.app_commands.checks.has_any_role`. - """ - - def __init__(self, missing_roles: SnowflakeList) -> None: - self.missing_roles: SnowflakeList = missing_roles - - missing = [f"'{role}'" for role in missing_roles] - - if len(missing) > 2: - fmt = '{}, or {}'.format(', '.join(missing[:-1]), missing[-1]) - else: - fmt = ' or '.join(missing) - - message = f'You are missing at least one of the required roles: {fmt}' - super().__init__(message) - - -class MissingPermissions(CheckFailure): - """An exception raised when the command invoker lacks permissions to run a - command. - - This inherits from :exc:`~discord.app_commands.CheckFailure`. - - .. versionadded:: 2.0 - - Attributes - ----------- - missing_permissions: List[:class:`str`] - The required permissions that are missing. - """ - - def __init__(self, missing_permissions: List[str], *args: Any) -> None: - self.missing_permissions: List[str] = missing_permissions - - missing = [perm.replace('_', ' ').replace('guild', 'server').title() for perm in missing_permissions] - - if len(missing) > 2: - fmt = '{}, and {}'.format(", ".join(missing[:-1]), missing[-1]) - else: - fmt = ' and '.join(missing) - message = f'You are missing {fmt} permission(s) to run this command.' - super().__init__(message, *args) - - -class BotMissingPermissions(CheckFailure): - """An exception raised when the bot's member lacks permissions to run a - command. - - This inherits from :exc:`~discord.app_commands.CheckFailure`. - - .. versionadded:: 2.0 - - Attributes - ----------- - missing_permissions: List[:class:`str`] - The required permissions that are missing. - """ - - def __init__(self, missing_permissions: List[str], *args: Any) -> None: - self.missing_permissions: List[str] = missing_permissions - - missing = [perm.replace('_', ' ').replace('guild', 'server').title() for perm in missing_permissions] - - if len(missing) > 2: - fmt = '{}, and {}'.format(", ".join(missing[:-1]), missing[-1]) - else: - fmt = ' and '.join(missing) - message = f'Bot requires {fmt} permission(s) to run this command.' - super().__init__(message, *args) - - -class CommandOnCooldown(CheckFailure): - """An exception raised when the command being invoked is on cooldown. - - This inherits from :exc:`~discord.app_commands.CheckFailure`. - - .. versionadded:: 2.0 - - Attributes - ----------- - cooldown: :class:`~discord.app_commands.Cooldown` - The cooldown that was triggered. - retry_after: :class:`float` - The amount of seconds to wait before you can retry again. - """ - - def __init__(self, cooldown: Cooldown, retry_after: float) -> None: - self.cooldown: Cooldown = cooldown - self.retry_after: float = retry_after - super().__init__(f'You are on cooldown. Try again in {retry_after:.2f}s') - - -class CommandAlreadyRegistered(AppCommandError): - """An exception raised when a command is already registered. - - This inherits from :exc:`~discord.app_commands.AppCommandError`. - - .. versionadded:: 2.0 - - Attributes - ----------- - name: :class:`str` - The name of the command already registered. - guild_id: Optional[:class:`int`] - The guild ID this command was already registered at. - If ``None`` then it was a global command. - """ - - def __init__(self, name: str, guild_id: Optional[int]): - self.name: str = name - self.guild_id: Optional[int] = guild_id - super().__init__(f'Command {name!r} already registered.') - - -class CommandNotFound(AppCommandError): - """An exception raised when an application command could not be found. - - This inherits from :exc:`~discord.app_commands.AppCommandError`. - - .. versionadded:: 2.0 - - Attributes - ------------ - name: :class:`str` - The name of the application command not found. - parents: List[:class:`str`] - A list of parent command names that were previously found - prior to the application command not being found. - type: :class:`~discord.AppCommandType` - The type of command that was not found. - """ - - def __init__(self, name: str, parents: List[str], type: AppCommandType = AppCommandType.chat_input): - self.name: str = name - self.parents: List[str] = parents - self.type: AppCommandType = type - super().__init__(f'Application command {name!r} not found') - - -class CommandLimitReached(AppCommandError): - """An exception raised when the maximum number of application commands was reached - either globally or in a guild. - - This inherits from :exc:`~discord.app_commands.AppCommandError`. - - .. versionadded:: 2.0 - - Attributes - ------------ - type: :class:`~discord.AppCommandType` - The type of command that reached the limit. - guild_id: Optional[:class:`int`] - The guild ID that reached the limit or ``None`` if it was global. - limit: :class:`int` - The limit that was hit. - """ - - def __init__(self, guild_id: Optional[int], limit: int, type: AppCommandType = AppCommandType.chat_input): - self.guild_id: Optional[int] = guild_id - self.limit: int = limit - self.type: AppCommandType = type - - lookup = { - AppCommandType.chat_input: 'slash commands', - AppCommandType.message: 'message context menu commands', - AppCommandType.user: 'user context menu commands', - } - desc = lookup.get(type, 'application commands') - ns = 'globally' if self.guild_id is None else f'for guild ID {self.guild_id}' - super().__init__(f'maximum number of {desc} exceeded {limit} {ns}') - - -class CommandSignatureMismatch(AppCommandError): - """An exception raised when an application command from Discord has a different signature - from the one provided in the code. This happens because your command definition differs - from the command definition you provided Discord. Either your code is out of date or the - data from Discord is out of sync. - - This inherits from :exc:`~discord.app_commands.AppCommandError`. - - .. versionadded:: 2.0 - - Attributes - ------------ - command: Union[:class:`~.app_commands.Command`, :class:`~.app_commands.ContextMenu`, :class:`~.app_commands.Group`] - The command that had the signature mismatch. - """ - - def __init__(self, command: Union[Command[Any, ..., Any], ContextMenu, Group]): - self.command: Union[Command[Any, ..., Any], ContextMenu, Group] = command - msg = ( - f'The signature for command {command.name!r} is different from the one provided by Discord. ' - 'This can happen because either your code is out of date or you have not synced the ' - 'commands with Discord, causing the mismatch in data. It is recommended to sync the ' - 'command tree to fix this issue.' - ) - super().__init__(msg) - - -class MissingApplicationID(AppCommandError): - """An exception raised when the client does not have an application ID set. - An application ID is required for syncing application commands. - - This inherits from :exc:`~discord.app_commands.AppCommandError`. - - .. versionadded:: 2.0 - """ - - def __init__(self, message: Optional[str] = None): - super().__init__(message or APP_ID_NOT_FOUND) - - -def _get_command_error( - index: str, - inner: Any, - objects: Sequence[Union[Parameter, CommandTypes]], - messages: List[str], - indent: int = 0, -) -> None: - # Import these here to avoid circular imports - from .commands import Command, Group, ContextMenu - - indentation = ' ' * indent - - # Top level errors are: - # : { : } - # The dicts could be nested, e.g. - # : { : { : } } - # Luckily, this is already handled by the flatten_error_dict utility - if not index.isdigit(): - errors = _flatten_error_dict(inner, index) - messages.extend(f'In {k}: {v}' for k, v in errors.items()) - return - - idx = int(index) - try: - obj = objects[idx] - except IndexError: - dedent_one_level = ' ' * (indent - 2) - errors = _flatten_error_dict(inner, index) - messages.extend(f'{dedent_one_level}In {k}: {v}' for k, v in errors.items()) - return - - children: Sequence[Union[Parameter, CommandTypes]] = [] - if isinstance(obj, Command): - messages.append(f'{indentation}In command {obj.qualified_name!r} defined in function {obj.callback.__qualname__!r}') - children = obj.parameters - elif isinstance(obj, Group): - messages.append(f'{indentation}In group {obj.qualified_name!r} defined in module {obj.module!r}') - children = obj.commands - elif isinstance(obj, ContextMenu): - messages.append( - f'{indentation}In context menu {obj.qualified_name!r} defined in function {obj.callback.__qualname__!r}' - ) - else: - messages.append(f'{indentation}In parameter {obj.name!r}') - - for key, remaining in inner.items(): - # Special case the 'options' key since they have well defined meanings - if key == 'options': - for index, d in remaining.items(): - _get_command_error(index, d, children, messages, indent=indent + 2) - else: - errors = _flatten_error_dict(remaining, key=key) - messages.extend(f'{indentation} {k}: {v}' for k, v in errors.items()) - - -class CommandSyncFailure(AppCommandError, HTTPException): - """An exception raised when :meth:`CommandTree.sync` failed. - - This provides syncing failures in a slightly more readable format. - - This inherits from :exc:`~discord.app_commands.AppCommandError` - and :exc:`~discord.HTTPException`. - - .. versionadded:: 2.0 - """ - - def __init__(self, child: HTTPException, commands: List[CommandTypes]) -> None: - # Consume the child exception and make it seem as if we are that exception - self.__dict__.update(child.__dict__) - - messages = [f'Failed to upload commands to Discord (HTTP status {self.status}, error code {self.code})'] - - if self._errors: - for index, inner in self._errors.items(): - _get_command_error(index, inner, commands, messages) - - # Equivalent to super().__init__(...) but skips other constructors - self.args = ('\n'.join(messages),) diff --git a/.venv/Lib/site-packages/discord/app_commands/models.py b/.venv/Lib/site-packages/discord/app_commands/models.py deleted file mode 100644 index 9deffff..0000000 --- a/.venv/Lib/site-packages/discord/app_commands/models.py +++ /dev/null @@ -1,1091 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations -from datetime import datetime - -from .errors import MissingApplicationID -from .translator import TranslationContextLocation, TranslationContext, locale_str, Translator -from ..permissions import Permissions -from ..enums import AppCommandOptionType, AppCommandType, AppCommandPermissionType, ChannelType, Locale, try_enum -from ..mixins import Hashable -from ..utils import _get_as_snowflake, parse_time, snowflake_time, MISSING -from ..object import Object -from ..role import Role -from ..member import Member - -from typing import Any, Dict, Generic, List, TYPE_CHECKING, Optional, TypeVar, Union - -__all__ = ( - 'AppCommand', - 'AppCommandGroup', - 'AppCommandChannel', - 'AppCommandThread', - 'AppCommandPermissions', - 'GuildAppCommandPermissions', - 'Argument', - 'Choice', - 'AllChannels', -) - -ChoiceT = TypeVar('ChoiceT', str, int, float, Union[str, int, float]) - - -def is_app_command_argument_type(value: int) -> bool: - return 11 >= value >= 3 - - -if TYPE_CHECKING: - from ..types.command import ( - ApplicationCommand as ApplicationCommandPayload, - ApplicationCommandOption, - ApplicationCommandOptionChoice, - ApplicationCommandPermissions, - GuildApplicationCommandPermissions, - ) - from ..types.interactions import ( - PartialChannel, - PartialThread, - ) - from ..types.threads import ( - ThreadMetadata, - ThreadArchiveDuration, - ) - - from ..abc import Snowflake - from ..state import ConnectionState - from ..guild import GuildChannel, Guild - from ..channel import TextChannel - from ..threads import Thread - from ..user import User - - ApplicationCommandParent = Union['AppCommand', 'AppCommandGroup'] - - -class AllChannels: - """Represents all channels for application command permissions. - - .. versionadded:: 2.0 - - Attributes - ----------- - guild: :class:`~discord.Guild` - The guild the application command permission is for. - """ - - __slots__ = ('guild',) - - def __init__(self, guild: Guild): - self.guild: Guild = guild - - @property - def id(self) -> int: - """:class:`int`: The ID sentinel used to represent all channels. Equivalent to the guild's ID minus 1.""" - return self.guild.id - 1 - - def __repr__(self) -> str: - return f'' - - -def _to_locale_dict(data: Dict[str, str]) -> Dict[Locale, str]: - return {try_enum(Locale, key): value for key, value in data.items()} - - -class AppCommand(Hashable): - """Represents an application command. - - In common parlance this is referred to as a "Slash Command" or a - "Context Menu Command". - - .. versionadded:: 2.0 - - .. container:: operations - - .. describe:: x == y - - Checks if two application commands are equal. - - .. describe:: x != y - - Checks if two application commands are not equal. - - .. describe:: hash(x) - - Returns the application command's hash. - - .. describe:: str(x) - - Returns the application command's name. - - Attributes - ----------- - id: :class:`int` - The application command's ID. - application_id: :class:`int` - The application command's application's ID. - type: :class:`~discord.AppCommandType` - The application command's type. - name: :class:`str` - The application command's name. - description: :class:`str` - The application command's description. - name_localizations: Dict[:class:`~discord.Locale`, :class:`str`] - The localised names of the application command. Used for display purposes. - description_localizations: Dict[:class:`~discord.Locale`, :class:`str`] - The localised descriptions of the application command. Used for display purposes. - options: List[Union[:class:`Argument`, :class:`AppCommandGroup`]] - A list of options. - default_member_permissions: Optional[:class:`~discord.Permissions`] - The default member permissions that can run this command. - dm_permission: :class:`bool` - A boolean that indicates whether this command can be run in direct messages. - guild_id: Optional[:class:`int`] - The ID of the guild this command is registered in. A value of ``None`` - denotes that it is a global command. - nsfw: :class:`bool` - Whether the command is NSFW and should only work in NSFW channels. - """ - - __slots__ = ( - 'id', - 'type', - 'application_id', - 'name', - 'description', - 'name_localizations', - 'description_localizations', - 'guild_id', - 'options', - 'default_member_permissions', - 'dm_permission', - 'nsfw', - '_state', - ) - - def __init__(self, *, data: ApplicationCommandPayload, state: ConnectionState) -> None: - self._state: ConnectionState = state - self._from_data(data) - - def _from_data(self, data: ApplicationCommandPayload) -> None: - self.id: int = int(data['id']) - self.application_id: int = int(data['application_id']) - self.name: str = data['name'] - self.description: str = data['description'] - self.guild_id: Optional[int] = _get_as_snowflake(data, 'guild_id') - self.type: AppCommandType = try_enum(AppCommandType, data.get('type', 1)) - self.options: List[Union[Argument, AppCommandGroup]] = [ - app_command_option_factory(data=d, parent=self, state=self._state) for d in data.get('options', []) - ] - self.default_member_permissions: Optional[Permissions] - permissions = data.get('default_member_permissions') - if permissions is None: - self.default_member_permissions = None - else: - self.default_member_permissions = Permissions(int(permissions)) - - dm_permission = data.get('dm_permission') - # For some reason this field can be explicit null and mean True - if dm_permission is None: - dm_permission = True - - self.dm_permission: bool = dm_permission - self.nsfw: bool = data.get('nsfw', False) - self.name_localizations: Dict[Locale, str] = _to_locale_dict(data.get('name_localizations') or {}) - self.description_localizations: Dict[Locale, str] = _to_locale_dict(data.get('description_localizations') or {}) - - def to_dict(self) -> ApplicationCommandPayload: - return { - 'id': self.id, - 'type': self.type.value, - 'application_id': self.application_id, - 'name': self.name, - 'description': self.description, - 'name_localizations': {str(k): v for k, v in self.name_localizations.items()}, - 'description_localizations': {str(k): v for k, v in self.description_localizations.items()}, - 'options': [opt.to_dict() for opt in self.options], - } # type: ignore # Type checker does not understand this literal. - - def __str__(self) -> str: - return self.name - - def __repr__(self) -> str: - return f'<{self.__class__.__name__} id={self.id!r} name={self.name!r} type={self.type!r}>' - - @property - def mention(self) -> str: - """:class:`str`: Returns a string that allows you to mention the given AppCommand.""" - return f'' - - @property - def guild(self) -> Optional[Guild]: - """Optional[:class:`~discord.Guild`]: Returns the guild this command is registered to - if it exists. - """ - return self._state._get_guild(self.guild_id) - - async def delete(self) -> None: - """|coro| - - Deletes the application command. - - Raises - ------- - NotFound - The application command was not found. - Forbidden - You do not have permission to delete this application command. - HTTPException - Deleting the application command failed. - MissingApplicationID - The client does not have an application ID. - """ - state = self._state - if not state.application_id: - raise MissingApplicationID - - if self.guild_id: - await state.http.delete_guild_command( - state.application_id, - self.guild_id, - self.id, - ) - else: - await state.http.delete_global_command( - state.application_id, - self.id, - ) - - async def edit( - self, - *, - name: str = MISSING, - description: str = MISSING, - default_member_permissions: Optional[Permissions] = MISSING, - dm_permission: bool = MISSING, - options: List[Union[Argument, AppCommandGroup]] = MISSING, - ) -> AppCommand: - """|coro| - - Edits the application command. - - Parameters - ----------- - name: :class:`str` - The new name for the application command. - description: :class:`str` - The new description for the application command. - default_member_permissions: Optional[:class:`~discord.Permissions`] - The new default permissions needed to use this application command. - Pass value of ``None`` to remove any permission requirements. - dm_permission: :class:`bool` - Indicates if the application command can be used in DMs. - options: List[Union[:class:`Argument`, :class:`AppCommandGroup`]] - List of new options for this application command. - - Raises - ------- - NotFound - The application command was not found. - Forbidden - You do not have permission to edit this application command. - HTTPException - Editing the application command failed. - MissingApplicationID - The client does not have an application ID. - - Returns - -------- - :class:`AppCommand` - The newly edited application command. - """ - state = self._state - if not state.application_id: - raise MissingApplicationID - - payload = {} - - if name is not MISSING: - payload['name'] = name - - if description is not MISSING: - payload['description'] = description - - if default_member_permissions is not MISSING: - if default_member_permissions is not None: - payload['default_member_permissions'] = default_member_permissions.value - else: - payload['default_member_permissions'] = None - - if self.guild_id is None and dm_permission is not MISSING: - payload['dm_permission'] = dm_permission - - if options is not MISSING: - payload['options'] = [option.to_dict() for option in options] - - if not payload: - return self - - if self.guild_id: - data = await state.http.edit_guild_command( - state.application_id, - self.guild_id, - self.id, - payload, - ) - else: - data = await state.http.edit_global_command( - state.application_id, - self.id, - payload, - ) - return AppCommand(data=data, state=state) - - async def fetch_permissions(self, guild: Snowflake) -> GuildAppCommandPermissions: - """|coro| - - Retrieves this command's permission in the guild. - - Parameters - ----------- - guild: :class:`~discord.abc.Snowflake` - The guild to retrieve the permissions from. - - Raises - ------- - Forbidden - You do not have permission to fetch the application command's permissions. - HTTPException - Fetching the application command's permissions failed. - MissingApplicationID - The client does not have an application ID. - NotFound - The application command's permissions could not be found. - This can also indicate that the permissions are synced with the guild - (i.e. they are unchanged from the default). - - Returns - -------- - :class:`GuildAppCommandPermissions` - An object representing the application command's permissions in the guild. - """ - state = self._state - if not state.application_id: - raise MissingApplicationID - - data = await state.http.get_application_command_permissions( - state.application_id, - guild.id, - self.id, - ) - return GuildAppCommandPermissions(data=data, state=state, command=self) - - -class Choice(Generic[ChoiceT]): - """Represents an application command argument choice. - - .. versionadded:: 2.0 - - .. container:: operations - - .. describe:: x == y - - Checks if two choices are equal. - - .. describe:: x != y - - Checks if two choices are not equal. - - .. describe:: hash(x) - - Returns the choice's hash. - - Parameters - ----------- - name: Union[:class:`str`, :class:`locale_str`] - The name of the choice. Used for display purposes. - Can only be up to 100 characters. - name_localizations: Dict[:class:`~discord.Locale`, :class:`str`] - The localised names of the choice. Used for display purposes. - value: Union[:class:`int`, :class:`str`, :class:`float`] - The value of the choice. If it's a string, it can only be - up to 100 characters long. - """ - - __slots__ = ('name', 'value', '_locale_name', 'name_localizations') - - def __init__(self, *, name: Union[str, locale_str], value: ChoiceT): - name, locale = (name.message, name) if isinstance(name, locale_str) else (name, None) - self.name: str = name - self._locale_name: Optional[locale_str] = locale - self.value: ChoiceT = value - self.name_localizations: Dict[Locale, str] = {} - - @classmethod - def from_dict(cls, data: ApplicationCommandOptionChoice) -> Choice[ChoiceT]: - self = cls.__new__(cls) - self.name = data['name'] - self.value = data['value'] - self.name_localizations = _to_locale_dict(data.get('name_localizations') or {}) - return self - - def __eq__(self, o: object) -> bool: - return isinstance(o, Choice) and self.name == o.name and self.value == o.value - - def __hash__(self) -> int: - return hash((self.name, self.value)) - - def __repr__(self) -> str: - return f'{self.__class__.__name__}(name={self.name!r}, value={self.value!r})' - - @property - def _option_type(self) -> AppCommandOptionType: - if isinstance(self.value, int): - return AppCommandOptionType.integer - elif isinstance(self.value, float): - return AppCommandOptionType.number - elif isinstance(self.value, str): - return AppCommandOptionType.string - else: - raise TypeError( - f'invalid Choice value type given, expected int, str, or float but received {self.value.__class__!r}' - ) - - async def get_translated_payload(self, translator: Translator) -> Dict[str, Any]: - base = self.to_dict() - name_localizations: Dict[str, str] = {} - context = TranslationContext(location=TranslationContextLocation.choice_name, data=self) - if self._locale_name: - for locale in Locale: - translation = await translator._checked_translate(self._locale_name, locale, context) - if translation is not None: - name_localizations[locale.value] = translation - - if name_localizations: - base['name_localizations'] = name_localizations - - return base - - async def get_translated_payload_for_locale(self, translator: Translator, locale: Locale) -> Dict[str, Any]: - base = self.to_dict() - if self._locale_name: - context = TranslationContext(location=TranslationContextLocation.choice_name, data=self) - translation = await translator._checked_translate(self._locale_name, locale, context) - if translation is not None: - base['name'] = translation - - return base - - def to_dict(self) -> Dict[str, Any]: - base = { - 'name': self.name, - 'value': self.value, - } - if self.name_localizations: - base['name_localizations'] = {str(k): v for k, v in self.name_localizations.items()} - return base - - -class AppCommandChannel(Hashable): - """Represents an application command partially resolved channel object. - - .. versionadded:: 2.0 - - .. container:: operations - - .. describe:: x == y - - Checks if two channels are equal. - - .. describe:: x != y - - Checks if two channels are not equal. - - .. describe:: hash(x) - - Returns the channel's hash. - - .. describe:: str(x) - - Returns the channel's name. - - Attributes - ----------- - id: :class:`int` - The ID of the channel. - type: :class:`~discord.ChannelType` - The type of channel. - name: :class:`str` - The name of the channel. - permissions: :class:`~discord.Permissions` - The resolved permissions of the user who invoked - the application command in that channel. - guild_id: :class:`int` - The guild ID this channel belongs to. - """ - - __slots__ = ( - 'id', - 'type', - 'name', - 'permissions', - 'guild_id', - '_state', - ) - - def __init__( - self, - *, - state: ConnectionState, - data: PartialChannel, - guild_id: int, - ): - self._state: ConnectionState = state - self.guild_id: int = guild_id - self.id: int = int(data['id']) - self.type: ChannelType = try_enum(ChannelType, data['type']) - self.name: str = data['name'] - self.permissions: Permissions = Permissions(int(data['permissions'])) - - def __str__(self) -> str: - return self.name - - def __repr__(self) -> str: - return f'<{self.__class__.__name__} id={self.id!r} name={self.name!r} type={self.type!r}>' - - @property - def guild(self) -> Optional[Guild]: - """Optional[:class:`~discord.Guild`]: The channel's guild, from cache, if found.""" - return self._state._get_guild(self.guild_id) - - def resolve(self) -> Optional[GuildChannel]: - """Resolves the application command channel to the appropriate channel - from cache if found. - - Returns - -------- - Optional[:class:`.abc.GuildChannel`] - The resolved guild channel or ``None`` if not found in cache. - """ - guild = self._state._get_guild(self.guild_id) - if guild is not None: - return guild.get_channel(self.id) - return None - - async def fetch(self) -> GuildChannel: - """|coro| - - Fetches the partial channel to a full :class:`.abc.GuildChannel`. - - Raises - -------- - NotFound - The channel was not found. - Forbidden - You do not have the permissions required to get a channel. - HTTPException - Retrieving the channel failed. - - Returns - -------- - :class:`.abc.GuildChannel` - The full channel. - """ - client = self._state._get_client() - return await client.fetch_channel(self.id) # type: ignore # This is explicit narrowing - - @property - def mention(self) -> str: - """:class:`str`: The string that allows you to mention the channel.""" - return f'<#{self.id}>' - - @property - def created_at(self) -> datetime: - """:class:`datetime.datetime`: An aware timestamp of when this channel was created in UTC.""" - return snowflake_time(self.id) - - -class AppCommandThread(Hashable): - """Represents an application command partially resolved thread object. - - .. versionadded:: 2.0 - - .. container:: operations - - .. describe:: x == y - - Checks if two thread are equal. - - .. describe:: x != y - - Checks if two thread are not equal. - - .. describe:: hash(x) - - Returns the thread's hash. - - .. describe:: str(x) - - Returns the thread's name. - - Attributes - ----------- - id: :class:`int` - The ID of the thread. - type: :class:`~discord.ChannelType` - The type of thread. - name: :class:`str` - The name of the thread. - parent_id: :class:`int` - The parent text channel ID this thread belongs to. - permissions: :class:`~discord.Permissions` - The resolved permissions of the user who invoked - the application command in that thread. - guild_id: :class:`int` - The guild ID this thread belongs to. - archived: :class:`bool` - Whether the thread is archived. - locked: :class:`bool` - Whether the thread is locked. - invitable: :class:`bool` - Whether non-moderators can add other non-moderators to this thread. - This is always ``True`` for public threads. - archiver_id: Optional[:class:`int`] - The user's ID that archived this thread. - auto_archive_duration: :class:`int` - The duration in minutes until the thread is automatically archived due to inactivity. - Usually a value of 60, 1440, 4320 and 10080. - archive_timestamp: :class:`datetime.datetime` - An aware timestamp of when the thread's archived status was last updated in UTC. - """ - - __slots__ = ( - 'id', - 'type', - 'name', - 'permissions', - 'guild_id', - 'parent_id', - 'archived', - 'archiver_id', - 'auto_archive_duration', - 'archive_timestamp', - 'locked', - 'invitable', - '_created_at', - '_state', - ) - - def __init__( - self, - *, - state: ConnectionState, - data: PartialThread, - guild_id: int, - ): - self._state: ConnectionState = state - self.guild_id: int = guild_id - self.id: int = int(data['id']) - self.parent_id: int = int(data['parent_id']) - self.type: ChannelType = try_enum(ChannelType, data['type']) - self.name: str = data['name'] - self.permissions: Permissions = Permissions(int(data['permissions'])) - self._unroll_metadata(data['thread_metadata']) - - def __str__(self) -> str: - return self.name - - def __repr__(self) -> str: - return f'<{self.__class__.__name__} id={self.id!r} name={self.name!r} archived={self.archived} type={self.type!r}>' - - @property - def guild(self) -> Optional[Guild]: - """Optional[:class:`~discord.Guild`]: The channel's guild, from cache, if found.""" - return self._state._get_guild(self.guild_id) - - def _unroll_metadata(self, data: ThreadMetadata) -> None: - self.archived: bool = data['archived'] - self.archiver_id: Optional[int] = _get_as_snowflake(data, 'archiver_id') - self.auto_archive_duration: ThreadArchiveDuration = data['auto_archive_duration'] - self.archive_timestamp: datetime = parse_time(data['archive_timestamp']) - self.locked: bool = data.get('locked', False) - self.invitable: bool = data.get('invitable', True) - self._created_at: Optional[datetime] = parse_time(data.get('create_timestamp')) - - @property - def parent(self) -> Optional[TextChannel]: - """Optional[:class:`~discord.TextChannel`]: The parent channel this thread belongs to.""" - return self.guild.get_channel(self.parent_id) # type: ignore - - @property - def mention(self) -> str: - """:class:`str`: The string that allows you to mention the thread.""" - return f'<#{self.id}>' - - @property - def created_at(self) -> Optional[datetime]: - """An aware timestamp of when the thread was created in UTC. - - .. note:: - - This timestamp only exists for threads created after 9 January 2022, otherwise returns ``None``. - """ - return self._created_at - - def resolve(self) -> Optional[Thread]: - """Resolves the application command channel to the appropriate channel - from cache if found. - - Returns - -------- - Optional[:class:`.abc.GuildChannel`] - The resolved guild channel or ``None`` if not found in cache. - """ - guild = self._state._get_guild(self.guild_id) - if guild is not None: - return guild.get_thread(self.id) - return None - - async def fetch(self) -> Thread: - """|coro| - - Fetches the partial channel to a full :class:`~discord.Thread`. - - Raises - -------- - NotFound - The thread was not found. - Forbidden - You do not have the permissions required to get a thread. - HTTPException - Retrieving the thread failed. - - Returns - -------- - :class:`~discord.Thread` - The full thread. - """ - client = self._state._get_client() - return await client.fetch_channel(self.id) # type: ignore # This is explicit narrowing - - -class Argument: - """Represents an application command argument. - - .. versionadded:: 2.0 - - Attributes - ------------ - type: :class:`~discord.AppCommandOptionType` - The type of argument. - name: :class:`str` - The name of the argument. - description: :class:`str` - The description of the argument. - name_localizations: Dict[:class:`~discord.Locale`, :class:`str`] - The localised names of the argument. Used for display purposes. - description_localizations: Dict[:class:`~discord.Locale`, :class:`str`] - The localised descriptions of the argument. Used for display purposes. - required: :class:`bool` - Whether the argument is required. - choices: List[:class:`Choice`] - A list of choices for the command to choose from for this argument. - parent: Union[:class:`AppCommand`, :class:`AppCommandGroup`] - The parent application command that has this argument. - channel_types: List[:class:`~discord.ChannelType`] - The channel types that are allowed for this parameter. - min_value: Optional[Union[:class:`int`, :class:`float`]] - The minimum supported value for this parameter. - max_value: Optional[Union[:class:`int`, :class:`float`]] - The maximum supported value for this parameter. - min_length: Optional[:class:`int`] - The minimum allowed length for this parameter. - max_length: Optional[:class:`int`] - The maximum allowed length for this parameter. - autocomplete: :class:`bool` - Whether the argument has autocomplete. - """ - - __slots__ = ( - 'type', - 'name', - 'description', - 'name_localizations', - 'description_localizations', - 'required', - 'choices', - 'channel_types', - 'min_value', - 'max_value', - 'min_length', - 'max_length', - 'autocomplete', - 'parent', - '_state', - ) - - def __init__( - self, *, parent: ApplicationCommandParent, data: ApplicationCommandOption, state: Optional[ConnectionState] = None - ) -> None: - self._state: Optional[ConnectionState] = state - self.parent: ApplicationCommandParent = parent - self._from_data(data) - - def __repr__(self) -> str: - return f'<{self.__class__.__name__} name={self.name!r} type={self.type!r} required={self.required}>' - - def _from_data(self, data: ApplicationCommandOption) -> None: - self.type: AppCommandOptionType = try_enum(AppCommandOptionType, data['type']) - self.name: str = data['name'] - self.description: str = data['description'] - self.required: bool = data.get('required', False) - self.min_value: Optional[Union[int, float]] = data.get('min_value') - self.max_value: Optional[Union[int, float]] = data.get('max_value') - self.min_length: Optional[int] = data.get('min_length') - self.max_length: Optional[int] = data.get('max_length') - self.autocomplete: bool = data.get('autocomplete', False) - self.channel_types: List[ChannelType] = [try_enum(ChannelType, d) for d in data.get('channel_types', [])] - self.choices: List[Choice[Union[int, float, str]]] = [Choice.from_dict(d) for d in data.get('choices', [])] - self.name_localizations: Dict[Locale, str] = _to_locale_dict(data.get('name_localizations') or {}) - self.description_localizations: Dict[Locale, str] = _to_locale_dict(data.get('description_localizations') or {}) - - def to_dict(self) -> ApplicationCommandOption: - return { - 'name': self.name, - 'type': self.type.value, - 'description': self.description, - 'required': self.required, - 'choices': [choice.to_dict() for choice in self.choices], - 'channel_types': [channel_type.value for channel_type in self.channel_types], - 'min_value': self.min_value, - 'max_value': self.max_value, - 'min_length': self.min_length, - 'max_length': self.max_length, - 'autocomplete': self.autocomplete, - 'options': [], - 'name_localizations': {str(k): v for k, v in self.name_localizations.items()}, - 'description_localizations': {str(k): v for k, v in self.description_localizations.items()}, - } # type: ignore # Type checker does not understand this literal. - - -class AppCommandGroup: - """Represents an application command subcommand. - - .. versionadded:: 2.0 - - Attributes - ------------ - type: :class:`~discord.AppCommandOptionType` - The type of subcommand. - name: :class:`str` - The name of the subcommand. - description: :class:`str` - The description of the subcommand. - name_localizations: Dict[:class:`~discord.Locale`, :class:`str`] - The localised names of the subcommand. Used for display purposes. - description_localizations: Dict[:class:`~discord.Locale`, :class:`str`] - The localised descriptions of the subcommand. Used for display purposes. - options: List[Union[:class:`Argument`, :class:`AppCommandGroup`]] - A list of options. - parent: Union[:class:`AppCommand`, :class:`AppCommandGroup`] - The parent application command. - """ - - __slots__ = ( - 'type', - 'name', - 'description', - 'name_localizations', - 'description_localizations', - 'options', - 'parent', - '_state', - ) - - def __init__( - self, *, parent: ApplicationCommandParent, data: ApplicationCommandOption, state: Optional[ConnectionState] = None - ) -> None: - self.parent: ApplicationCommandParent = parent - self._state: Optional[ConnectionState] = state - self._from_data(data) - - def __repr__(self) -> str: - return f'<{self.__class__.__name__} name={self.name!r} type={self.type!r}>' - - @property - def qualified_name(self) -> str: - """:class:`str`: Returns the fully qualified command name. - - The qualified name includes the parent name as well. For example, - in a command like ``/foo bar`` the qualified name is ``foo bar``. - """ - # A B C - # ^ self - # ^ parent - # ^ grandparent - names = [self.name, self.parent.name] - if isinstance(self.parent, AppCommandGroup): - names.append(self.parent.parent.name) - - return ' '.join(reversed(names)) - - @property - def mention(self) -> str: - """:class:`str`: Returns a string that allows you to mention the given AppCommandGroup.""" - if isinstance(self.parent, AppCommand): - base_command = self.parent - else: - base_command = self.parent.parent - return f'' # type: ignore - - def _from_data(self, data: ApplicationCommandOption) -> None: - self.type: AppCommandOptionType = try_enum(AppCommandOptionType, data['type']) - self.name: str = data['name'] - self.description: str = data['description'] - self.options: List[Union[Argument, AppCommandGroup]] = [ - app_command_option_factory(data=d, parent=self, state=self._state) for d in data.get('options', []) - ] - self.name_localizations: Dict[Locale, str] = _to_locale_dict(data.get('name_localizations') or {}) - self.description_localizations: Dict[Locale, str] = _to_locale_dict(data.get('description_localizations') or {}) - - def to_dict(self) -> 'ApplicationCommandOption': - return { - 'name': self.name, - 'type': self.type.value, - 'description': self.description, - 'options': [arg.to_dict() for arg in self.options], - 'name_localizations': {str(k): v for k, v in self.name_localizations.items()}, - 'description_localizations': {str(k): v for k, v in self.description_localizations.items()}, - } # type: ignore # Type checker does not understand this literal. - - -class AppCommandPermissions: - """Represents the permissions for an application command. - - .. versionadded:: 2.0 - - Attributes - ----------- - guild: :class:`~discord.Guild` - The guild associated with this permission. - id: :class:`int` - The ID of the permission target, such as a role, channel, or guild. - The special ``guild_id - 1`` sentinel is used to represent "all channels". - target: Any - The role, user, or channel associated with this permission. This could also be the :class:`AllChannels` sentinel type. - Falls back to :class:`~discord.Object` if the target could not be found in the cache. - type: :class:`.AppCommandPermissionType` - The type of permission. - permission: :class:`bool` - The permission value. ``True`` for allow, ``False`` for deny. - """ - - __slots__ = ('id', 'type', 'permission', 'target', 'guild', '_state') - - def __init__(self, *, data: ApplicationCommandPermissions, guild: Guild, state: ConnectionState) -> None: - self._state: ConnectionState = state - self.guild: Guild = guild - - self.id: int = int(data['id']) - self.type: AppCommandPermissionType = try_enum(AppCommandPermissionType, data['type']) - self.permission: bool = data['permission'] - - _object = None - _type = MISSING - - if self.type is AppCommandPermissionType.user: - _object = guild.get_member(self.id) or self._state.get_user(self.id) - _type = Member - elif self.type is AppCommandPermissionType.channel: - if self.id == (guild.id - 1): - _object = AllChannels(guild) - else: - _object = guild.get_channel(self.id) - elif self.type is AppCommandPermissionType.role: - _object = guild.get_role(self.id) - _type = Role - - if _object is None: - _object = Object(id=self.id, type=_type) - - self.target: Union[Object, User, Member, Role, AllChannels, GuildChannel] = _object - - def to_dict(self) -> ApplicationCommandPermissions: - return { - 'id': self.target.id, - 'type': self.type.value, - 'permission': self.permission, - } - - -class GuildAppCommandPermissions: - """Represents the permissions for an application command in a guild. - - .. versionadded:: 2.0 - - Attributes - ----------- - application_id: :class:`int` - The application ID. - command: :class:`.AppCommand` - The application command associated with the permissions. - id: :class:`int` - ID of the command or the application ID. - When this is the application ID instead of a command ID, - the permissions apply to all commands that do not contain explicit overwrites. - guild_id: :class:`int` - The guild ID associated with the permissions. - permissions: List[:class:`AppCommandPermissions`] - The permissions, this is a max of 100. - """ - - __slots__ = ('id', 'application_id', 'command', 'guild_id', 'permissions', '_state') - - def __init__(self, *, data: GuildApplicationCommandPermissions, state: ConnectionState, command: AppCommand) -> None: - self._state: ConnectionState = state - self.command: AppCommand = command - - self.id: int = int(data['id']) - self.application_id: int = int(data['application_id']) - self.guild_id: int = int(data['guild_id']) - guild = self.guild - self.permissions: List[AppCommandPermissions] = [ - AppCommandPermissions(data=value, guild=guild, state=self._state) for value in data['permissions'] - ] - - def to_dict(self) -> Dict[str, Any]: - return {'permissions': [p.to_dict() for p in self.permissions]} - - @property - def guild(self) -> Guild: - """:class:`~discord.Guild`: The guild associated with the permissions.""" - return self._state._get_or_create_unavailable_guild(self.guild_id) - - -def app_command_option_factory( - parent: ApplicationCommandParent, data: ApplicationCommandOption, *, state: Optional[ConnectionState] = None -) -> Union[Argument, AppCommandGroup]: - if is_app_command_argument_type(data['type']): - return Argument(parent=parent, data=data, state=state) - else: - return AppCommandGroup(parent=parent, data=data, state=state) diff --git a/.venv/Lib/site-packages/discord/app_commands/namespace.py b/.venv/Lib/site-packages/discord/app_commands/namespace.py deleted file mode 100644 index a56d8aa..0000000 --- a/.venv/Lib/site-packages/discord/app_commands/namespace.py +++ /dev/null @@ -1,258 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations - -from typing import TYPE_CHECKING, Any, Dict, Iterable, Iterator, List, NamedTuple, Tuple -from ..member import Member -from ..object import Object -from ..role import Role -from ..message import Message, Attachment -from ..channel import PartialMessageable -from ..enums import AppCommandOptionType -from .models import AppCommandChannel, AppCommandThread - -if TYPE_CHECKING: - from ..interactions import Interaction - from ..types.interactions import ResolvedData, ApplicationCommandInteractionDataOption - -__all__ = ('Namespace',) - - -class ResolveKey(NamedTuple): - id: str - # CommandOptionType does not use 0 or negative numbers so those can be safe for library - # internal use, if necessary. Likewise, only 6, 7, 8, and 11 are actually in use. - type: int - - @classmethod - def any_with(cls, id: str) -> ResolveKey: - return ResolveKey(id=id, type=-1) - - def __eq__(self, o: object) -> bool: - if not isinstance(o, ResolveKey): - return NotImplemented - if self.type == -1 or o.type == -1: - return self.id == o.id - return (self.id, self.type) == (o.id, o.type) - - def __hash__(self) -> int: - # Most of the time an ID lookup is all that is necessary - # In case of collision then we look up both the ID and the type. - return hash(self.id) - - -class Namespace: - """An object that holds the parameters being passed to a command in a mostly raw state. - - This class is deliberately simple and just holds the option name and resolved value as a simple - key-pair mapping. These attributes can be accessed using dot notation. For example, an option - with the name of ``example`` can be accessed using ``ns.example``. If an attribute is not found, - then ``None`` is returned rather than an attribute error. - - .. versionadded:: 2.0 - - .. container:: operations - - .. describe:: x == y - - Checks if two namespaces are equal by checking if all attributes are equal. - .. describe:: x != y - - Checks if two namespaces are not equal. - .. describe:: x[key] - - Returns an attribute if it is found, otherwise raises - a :exc:`KeyError`. - .. describe:: key in x - - Checks if the attribute is in the namespace. - .. describe:: iter(x) - - Returns an iterator of ``(name, value)`` pairs. This allows it - to be, for example, constructed as a dict or a list of pairs. - - This namespace object converts resolved objects into their appropriate form depending on their - type. Consult the table below for conversion information. - - +-------------------------------------------+-------------------------------------------------------------------------------+ - | Option Type | Resolved Type | - +===========================================+===============================================================================+ - | :attr:`.AppCommandOptionType.string` | :class:`str` | - +-------------------------------------------+-------------------------------------------------------------------------------+ - | :attr:`.AppCommandOptionType.integer` | :class:`int` | - +-------------------------------------------+-------------------------------------------------------------------------------+ - | :attr:`.AppCommandOptionType.boolean` | :class:`bool` | - +-------------------------------------------+-------------------------------------------------------------------------------+ - | :attr:`.AppCommandOptionType.number` | :class:`float` | - +-------------------------------------------+-------------------------------------------------------------------------------+ - | :attr:`.AppCommandOptionType.user` | :class:`~discord.User` or :class:`~discord.Member` | - +-------------------------------------------+-------------------------------------------------------------------------------+ - | :attr:`.AppCommandOptionType.channel` | :class:`.AppCommandChannel` or :class:`.AppCommandThread` | - +-------------------------------------------+-------------------------------------------------------------------------------+ - | :attr:`.AppCommandOptionType.role` | :class:`~discord.Role` | - +-------------------------------------------+-------------------------------------------------------------------------------+ - | :attr:`.AppCommandOptionType.mentionable` | :class:`~discord.User` or :class:`~discord.Member`, or :class:`~discord.Role` | - +-------------------------------------------+-------------------------------------------------------------------------------+ - | :attr:`.AppCommandOptionType.attachment` | :class:`~discord.Attachment` | - +-------------------------------------------+-------------------------------------------------------------------------------+ - - .. note:: - - In autocomplete interactions, the namespace might not be validated or filled in. Discord does not - send the resolved data as well, so this means that certain fields end up just as IDs rather than - the resolved data. In these cases, a :class:`discord.Object` is returned instead. - - This is a Discord limitation. - """ - - def __init__( - self, - interaction: Interaction, - resolved: ResolvedData, - options: List[ApplicationCommandInteractionDataOption], - ): - completed = self._get_resolved_items(interaction, resolved) - for option in options: - opt_type = option['type'] - name = option['name'] - focused = option.get('focused', False) - if opt_type in (3, 4, 5): # string, integer, boolean - value = option['value'] # type: ignore # Key is there - self.__dict__[name] = value - elif opt_type == 10: # number - value = option['value'] # type: ignore # Key is there - # This condition is written this way because 0 can be a valid float - if value is None or value == '': - self.__dict__[name] = float('nan') - else: - if not focused: - self.__dict__[name] = float(value) - else: - # Autocomplete focused values tend to be garbage in - self.__dict__[name] = value - elif opt_type in (6, 7, 8, 9, 11): - # Remaining ones should be snowflake based ones with resolved data - snowflake: str = option['value'] # type: ignore # Key is there - if opt_type == 9: # Mentionable - # Mentionable is User | Role, these do not cause any conflict - key = ResolveKey.any_with(snowflake) - else: - # The remaining keys can conflict, for example, a role and a channel - # could end up with the same ID in very old guilds since they used to default - # to sharing the guild ID. Old general channels no longer exist, but some old - # servers will still have them so this needs to be handled. - key = ResolveKey(id=snowflake, type=opt_type) - - value = completed.get(key) or Object(id=int(snowflake)) - self.__dict__[name] = value - - @classmethod - def _get_resolved_items(cls, interaction: Interaction, resolved: ResolvedData) -> Dict[ResolveKey, Any]: - completed: Dict[ResolveKey, Any] = {} - state = interaction._state - members = resolved.get('members', {}) - guild_id = interaction.guild_id - guild = state._get_or_create_unavailable_guild(guild_id) if guild_id is not None else None - type = AppCommandOptionType.user.value - for (user_id, user_data) in resolved.get('users', {}).items(): - try: - member_data = members[user_id] - except KeyError: - completed[ResolveKey(id=user_id, type=type)] = state.create_user(user_data) - else: - member_data['user'] = user_data - # Guild ID can't be None in this case. - # There's a type mismatch here that I don't actually care about - member = Member(state=state, guild=guild, data=member_data) # type: ignore - completed[ResolveKey(id=user_id, type=type)] = member - - type = AppCommandOptionType.role.value - completed.update( - { - # The guild ID can't be None in this case. - ResolveKey(id=role_id, type=type): Role(guild=guild, state=state, data=role_data) # type: ignore - for role_id, role_data in resolved.get('roles', {}).items() - } - ) - - type = AppCommandOptionType.channel.value - for (channel_id, channel_data) in resolved.get('channels', {}).items(): - key = ResolveKey(id=channel_id, type=type) - if channel_data['type'] in (10, 11, 12): - # The guild ID can't be none in this case - completed[key] = AppCommandThread(state=state, data=channel_data, guild_id=guild_id) # type: ignore - else: - # The guild ID can't be none in this case - completed[key] = AppCommandChannel(state=state, data=channel_data, guild_id=guild_id) # type: ignore - - type = AppCommandOptionType.attachment.value - completed.update( - { - ResolveKey(id=attachment_id, type=type): Attachment(data=attachment_data, state=state) - for attachment_id, attachment_data in resolved.get('attachments', {}).items() - } - ) - - guild = state._get_guild(guild_id) - for (message_id, message_data) in resolved.get('messages', {}).items(): - channel_id = int(message_data['channel_id']) - if guild is None: - channel = PartialMessageable(state=state, guild_id=guild_id, id=channel_id) - else: - channel = guild.get_channel_or_thread(channel_id) or PartialMessageable( - state=state, guild_id=guild_id, id=channel_id - ) - - # Type checker doesn't understand this due to failure to narrow - message = Message(state=state, channel=channel, data=message_data) # type: ignore - key = ResolveKey(id=message_id, type=-1) - completed[key] = message - - return completed - - def __repr__(self) -> str: - items = (f'{k}={v!r}' for k, v in self.__dict__.items()) - return '<{} {}>'.format(self.__class__.__name__, ' '.join(items)) - - def __eq__(self, other: object) -> bool: - if isinstance(self, Namespace) and isinstance(other, Namespace): - return self.__dict__ == other.__dict__ - return NotImplemented - - def __getitem__(self, key: str) -> Any: - return self.__dict__[key] - - def __contains__(self, key: str) -> Any: - return key in self.__dict__ - - def __getattr__(self, attr: str) -> Any: - return None - - def __iter__(self) -> Iterator[Tuple[str, Any]]: - yield from self.__dict__.items() - - def _update_with_defaults(self, defaults: Iterable[Tuple[str, Any]]) -> None: - for key, value in defaults: - self.__dict__.setdefault(key, value) diff --git a/.venv/Lib/site-packages/discord/app_commands/transformers.py b/.venv/Lib/site-packages/discord/app_commands/transformers.py deleted file mode 100644 index 84c44ec..0000000 --- a/.venv/Lib/site-packages/discord/app_commands/transformers.py +++ /dev/null @@ -1,871 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations -import inspect - -from dataclasses import dataclass -from enum import Enum -from typing import ( - TYPE_CHECKING, - Any, - Callable, - ClassVar, - Coroutine, - Dict, - List, - Literal, - Optional, - Set, - Tuple, - Type, - TypeVar, - Union, -) - -from .errors import AppCommandError, TransformerError -from .models import AppCommandChannel, AppCommandThread, Choice -from .translator import TranslationContextLocation, TranslationContext, Translator, locale_str -from ..channel import StageChannel, VoiceChannel, TextChannel, CategoryChannel -from ..abc import GuildChannel -from ..threads import Thread -from ..enums import Enum as InternalEnum, AppCommandOptionType, ChannelType, Locale -from ..utils import MISSING, maybe_coroutine -from ..user import User -from ..role import Role -from ..member import Member -from ..message import Attachment - -__all__ = ( - 'Transformer', - 'Transform', - 'Range', -) - -T = TypeVar('T') -FuncT = TypeVar('FuncT', bound=Callable[..., Any]) -ChoiceT = TypeVar('ChoiceT', str, int, float, Union[str, int, float]) -NoneType = type(None) - -if TYPE_CHECKING: - from ..interactions import Interaction - from .commands import Parameter - - -@dataclass -class CommandParameter: - # The name of the parameter is *always* the parameter name in the code - # Therefore, it can't be Union[str, locale_str] - name: str = MISSING - description: Union[str, locale_str] = MISSING - required: bool = MISSING - default: Any = MISSING - choices: List[Choice[Union[str, int, float]]] = MISSING - type: AppCommandOptionType = MISSING - channel_types: List[ChannelType] = MISSING - min_value: Optional[Union[int, float]] = None - max_value: Optional[Union[int, float]] = None - autocomplete: Optional[Callable[..., Coroutine[Any, Any, Any]]] = None - _rename: Union[str, locale_str] = MISSING - _annotation: Any = MISSING - - async def get_translated_payload(self, translator: Translator, data: Parameter) -> Dict[str, Any]: - base = self.to_dict() - - rename = self._rename - description = self.description - needs_name_translations = isinstance(rename, locale_str) - needs_description_translations = isinstance(description, locale_str) - name_localizations: Dict[str, str] = {} - description_localizations: Dict[str, str] = {} - - # Prevent creating these objects in a heavy loop - name_context = TranslationContext(location=TranslationContextLocation.parameter_name, data=data) - description_context = TranslationContext(location=TranslationContextLocation.parameter_description, data=data) - for locale in Locale: - if needs_name_translations: - translation = await translator._checked_translate(rename, locale, name_context) - if translation is not None: - name_localizations[locale.value] = translation - - if needs_description_translations: - translation = await translator._checked_translate(description, locale, description_context) - if translation is not None: - description_localizations[locale.value] = translation - - if self.choices: - base['choices'] = [await choice.get_translated_payload(translator) for choice in self.choices] - - if name_localizations: - base['name_localizations'] = name_localizations - - if description_localizations: - base['description_localizations'] = description_localizations - - return base - - def to_dict(self) -> Dict[str, Any]: - base = { - 'type': self.type.value, - 'name': self.display_name, - 'description': str(self.description), - 'required': self.required, - } - - if self.choices: - base['choices'] = [choice.to_dict() for choice in self.choices] - if self.channel_types: - base['channel_types'] = [t.value for t in self.channel_types] - if self.autocomplete: - base['autocomplete'] = True - - min_key, max_key = ( - ('min_value', 'max_value') if self.type is not AppCommandOptionType.string else ('min_length', 'max_length') - ) - if self.min_value is not None: - base[min_key] = self.min_value - if self.max_value is not None: - base[max_key] = self.max_value - - return base - - def _convert_to_locale_strings(self) -> None: - if self._rename is MISSING: - self._rename = locale_str(self.name) - elif isinstance(self._rename, str): - self._rename = locale_str(self._rename) - - if isinstance(self.description, str): - self.description = locale_str(self.description) - - if self.choices: - for choice in self.choices: - if choice._locale_name is None: - choice._locale_name = locale_str(choice.name) - - def is_choice_annotation(self) -> bool: - return getattr(self._annotation, '__discord_app_commands_is_choice__', False) - - async def transform(self, interaction: Interaction, value: Any, /) -> Any: - if hasattr(self._annotation, '__discord_app_commands_transformer__'): - # This one needs special handling for type safety reasons - if self._annotation.__discord_app_commands_is_choice__: - choice = next((c for c in self.choices if c.value == value), None) - if choice is None: - raise TransformerError(value, self.type, self._annotation) - return choice - - try: - # ParamSpec doesn't understand that transform is a callable since it's unbound - return await maybe_coroutine(self._annotation.transform, interaction, value) # type: ignore - except AppCommandError: - raise - except Exception as e: - raise TransformerError(value, self.type, self._annotation) from e - - return value - - @property - def display_name(self) -> str: - """:class:`str`: The name of the parameter as it should be displayed to the user.""" - return self.name if self._rename is MISSING else str(self._rename) - - -class Transformer: - """The base class that allows a type annotation in an application command parameter - to map into a :class:`~discord.AppCommandOptionType` and transform the raw value into one - from this type. - - This class is customisable through the overriding of methods and properties in the class - and by using it as the second type parameter of the :class:`~discord.app_commands.Transform` - class. For example, to convert a string into a custom pair type: - - .. code-block:: python3 - - class Point(typing.NamedTuple): - x: int - y: int - - class PointTransformer(app_commands.Transformer): - async def transform(self, interaction: discord.Interaction, value: str) -> Point: - (x, _, y) = value.partition(',') - return Point(x=int(x.strip()), y=int(y.strip())) - - @app_commands.command() - async def graph( - interaction: discord.Interaction, - point: app_commands.Transform[Point, PointTransformer], - ): - await interaction.response.send_message(str(point)) - - If a class is passed instead of an instance to the second type parameter, then it is - constructed with no arguments passed to the ``__init__`` method. - - .. versionadded:: 2.0 - """ - - __discord_app_commands_transformer__: ClassVar[bool] = True - __discord_app_commands_is_choice__: ClassVar[bool] = False - - # This is needed to pass typing's type checks. - # e.g. Optional[MyTransformer] - def __call__(self) -> None: - pass - - def __or__(self, rhs: Any) -> Any: - return Union[self, rhs] # type: ignore - - @property - def type(self) -> AppCommandOptionType: - """:class:`~discord.AppCommandOptionType`: The option type associated with this transformer. - - This must be a :obj:`property`. - - Defaults to :attr:`~discord.AppCommandOptionType.string`. - """ - return AppCommandOptionType.string - - @property - def channel_types(self) -> List[ChannelType]: - """List[:class:`~discord.ChannelType`]: A list of channel types that are allowed to this parameter. - - Only valid if the :meth:`type` returns :attr:`~discord.AppCommandOptionType.channel`. - - This must be a :obj:`property`. - - Defaults to an empty list. - """ - return [] - - @property - def min_value(self) -> Optional[Union[int, float]]: - """Optional[:class:`int`]: The minimum supported value for this parameter. - - Only valid if the :meth:`type` returns :attr:`~discord.AppCommandOptionType.number` - :attr:`~discord.AppCommandOptionType.integer`, or :attr:`~discord.AppCommandOptionType.string`. - - This must be a :obj:`property`. - - Defaults to ``None``. - """ - return None - - @property - def max_value(self) -> Optional[Union[int, float]]: - """Optional[:class:`int`]: The maximum supported value for this parameter. - - Only valid if the :meth:`type` returns :attr:`~discord.AppCommandOptionType.number` - :attr:`~discord.AppCommandOptionType.integer`, or :attr:`~discord.AppCommandOptionType.string`. - - This must be a :obj:`property`. - - Defaults to ``None``. - """ - return None - - @property - def choices(self) -> Optional[List[Choice[Union[int, float, str]]]]: - """Optional[List[:class:`~discord.app_commands.Choice`]]: A list of choices that are allowed to this parameter. - - Only valid if the :meth:`type` returns :attr:`~discord.AppCommandOptionType.number` - :attr:`~discord.AppCommandOptionType.integer`, or :attr:`~discord.AppCommandOptionType.string`. - - This must be a :obj:`property`. - - Defaults to ``None``. - """ - return None - - @property - def _error_display_name(self) -> str: - name = self.__class__.__name__ - if name.endswith('Transformer'): - return name[:-11] - else: - return name - - async def transform(self, interaction: Interaction, value: Any, /) -> Any: - """|maybecoro| - - Transforms the converted option value into another value. - - The value passed into this transform function is the same as the - one in the :class:`conversion table `. - - Parameters - ----------- - interaction: :class:`~discord.Interaction` - The interaction being handled. - value: Any - The value of the given argument after being resolved. - See the :class:`conversion table ` - for how certain option types correspond to certain values. - """ - raise NotImplementedError('Derived classes need to implement this.') - - async def autocomplete( - self, interaction: Interaction, value: Union[int, float, str], / - ) -> List[Choice[Union[int, float, str]]]: - """|coro| - - An autocomplete prompt handler to be automatically used by options using this transformer. - - .. note:: - - Autocomplete is only supported for options with a :meth:`~discord.app_commands.Transformer.type` - of :attr:`~discord.AppCommandOptionType.string`, :attr:`~discord.AppCommandOptionType.integer`, - or :attr:`~discord.AppCommandOptionType.number`. - - Parameters - ----------- - interaction: :class:`~discord.Interaction` - The autocomplete interaction being handled. - value: Union[:class:`str`, :class:`int`, :class:`float`] - The current value entered by the user. - - Returns - -------- - List[:class:`~discord.app_commands.Choice`] - A list of choices to be displayed to the user, a maximum of 25. - - """ - raise NotImplementedError('Derived classes can implement this.') - - -class IdentityTransformer(Transformer): - def __init__(self, type: AppCommandOptionType) -> None: - self._type = type - - @property - def type(self) -> AppCommandOptionType: - return self._type - - async def transform(self, interaction: Interaction, value: Any, /) -> Any: - return value - - -class RangeTransformer(IdentityTransformer): - def __init__( - self, - opt_type: AppCommandOptionType, - *, - min: Optional[Union[int, float]] = None, - max: Optional[Union[int, float]] = None, - ) -> None: - if min and max and min > max: - raise TypeError('minimum cannot be larger than maximum') - - self._min: Optional[Union[int, float]] = min - self._max: Optional[Union[int, float]] = max - super().__init__(opt_type) - - @property - def min_value(self) -> Optional[Union[int, float]]: - return self._min - - @property - def max_value(self) -> Optional[Union[int, float]]: - return self._max - - -class LiteralTransformer(IdentityTransformer): - def __init__(self, values: Tuple[Any, ...]) -> None: - first = type(values[0]) - if first is int: - opt_type = AppCommandOptionType.integer - elif first is float: - opt_type = AppCommandOptionType.number - elif first is str: - opt_type = AppCommandOptionType.string - else: - raise TypeError(f'expected int, str, or float values not {first!r}') - - self._choices = [Choice(name=str(v), value=v) for v in values] - super().__init__(opt_type) - - @property - def choices(self): - return self._choices - - -class ChoiceTransformer(IdentityTransformer): - __discord_app_commands_is_choice__: ClassVar[bool] = True - - def __init__(self, inner_type: Any) -> None: - if inner_type is int: - opt_type = AppCommandOptionType.integer - elif inner_type is float: - opt_type = AppCommandOptionType.number - elif inner_type is str: - opt_type = AppCommandOptionType.string - else: - raise TypeError(f'expected int, str, or float values not {inner_type!r}') - - super().__init__(opt_type) - - -class EnumValueTransformer(Transformer): - def __init__(self, enum: Any) -> None: - super().__init__() - - values = list(enum) - if len(values) < 2: - raise TypeError(f'enum.Enum requires at least two values.') - - first = type(values[0].value) - if first is int: - opt_type = AppCommandOptionType.integer - elif first is float: - opt_type = AppCommandOptionType.number - elif first is str: - opt_type = AppCommandOptionType.string - else: - raise TypeError(f'expected int, str, or float values not {first!r}') - - self._type: AppCommandOptionType = opt_type - self._enum: Any = enum - self._choices = [Choice(name=v.name, value=v.value) for v in values] - - @property - def _error_display_name(self) -> str: - return self._enum.__name__ - - @property - def type(self) -> AppCommandOptionType: - return self._type - - @property - def choices(self): - return self._choices - - async def transform(self, interaction: Interaction, value: Any, /) -> Any: - return self._enum(value) - - -class EnumNameTransformer(Transformer): - def __init__(self, enum: Any) -> None: - super().__init__() - - values = list(enum) - if len(values) < 2: - raise TypeError(f'enum.Enum requires at least two values.') - - self._enum: Any = enum - self._choices = [Choice(name=v.name, value=v.name) for v in values] - - @property - def _error_display_name(self) -> str: - return self._enum.__name__ - - @property - def type(self) -> AppCommandOptionType: - return AppCommandOptionType.string - - @property - def choices(self): - return self._choices - - async def transform(self, interaction: Interaction, value: Any, /) -> Any: - return self._enum[value] - - -class InlineTransformer(Transformer): - def __init__(self, annotation: Any) -> None: - super().__init__() - self.annotation: Any = annotation - - @property - def _error_display_name(self) -> str: - return self.annotation.__name__ - - @property - def type(self) -> AppCommandOptionType: - return AppCommandOptionType.string - - async def transform(self, interaction: Interaction, value: Any, /) -> Any: - return await self.annotation.transform(interaction, value) - - -if TYPE_CHECKING: - from typing_extensions import Annotated as Transform - from typing_extensions import Annotated as Range -else: - - class Transform: - """A type annotation that can be applied to a parameter to customise the behaviour of - an option type by transforming with the given :class:`Transformer`. This requires - the usage of two generic parameters, the first one is the type you're converting to and the second - one is the type of the :class:`Transformer` actually doing the transformation. - - During type checking time this is equivalent to :obj:`typing.Annotated` so type checkers understand - the intent of the code. - - For example usage, check :class:`Transformer`. - - .. versionadded:: 2.0 - """ - - def __class_getitem__(cls, items) -> _TransformMetadata: - if not isinstance(items, tuple): - raise TypeError(f'expected tuple for arguments, received {items.__class__!r} instead') - - if len(items) != 2: - raise TypeError(f'Transform only accepts exactly two arguments') - - _, transformer = items - - if inspect.isclass(transformer): - if not issubclass(transformer, Transformer): - raise TypeError(f'second argument of Transform must be a Transformer class not {transformer!r}') - transformer = transformer() - elif not isinstance(transformer, Transformer): - raise TypeError(f'second argument of Transform must be a Transformer not {transformer.__class__!r}') - - return transformer - - class Range: - """A type annotation that can be applied to a parameter to require a numeric or string - type to fit within the range provided. - - During type checking time this is equivalent to :obj:`typing.Annotated` so type checkers understand - the intent of the code. - - Some example ranges: - - - ``Range[int, 10]`` means the minimum is 10 with no maximum. - - ``Range[int, None, 10]`` means the maximum is 10 with no minimum. - - ``Range[int, 1, 10]`` means the minimum is 1 and the maximum is 10. - - .. versionadded:: 2.0 - - Examples - ---------- - - .. code-block:: python3 - - @app_commands.command() - async def range(interaction: discord.Interaction, value: app_commands.Range[int, 10, 12]): - await interaction.response.send_message(f'Your value is {value}', ephemeral=True) - """ - - def __class_getitem__(cls, obj) -> _TransformMetadata: - if not isinstance(obj, tuple): - raise TypeError(f'expected tuple for arguments, received {obj.__class__!r} instead') - - if len(obj) == 2: - obj = (*obj, None) - elif len(obj) != 3: - raise TypeError('Range accepts either two or three arguments with the first being the type of range.') - - obj_type, min, max = obj - - if min is None and max is None: - raise TypeError('Range must not be empty') - - if min is not None and max is not None: - # At this point max and min are both not none - if type(min) != type(max): - raise TypeError('Both min and max in Range must be the same type') - - if obj_type is int: - opt_type = AppCommandOptionType.integer - elif obj_type is float: - opt_type = AppCommandOptionType.number - elif obj_type is str: - opt_type = AppCommandOptionType.string - else: - raise TypeError(f'expected int, float, or str as range type, received {obj_type!r} instead') - - if obj_type in (str, int): - cast = int - else: - cast = float - - transformer = RangeTransformer( - opt_type, - min=cast(min) if min is not None else None, - max=cast(max) if max is not None else None, - ) - return transformer - - -class MemberTransformer(Transformer): - @property - def type(self) -> AppCommandOptionType: - return AppCommandOptionType.user - - async def transform(self, interaction: Interaction, value: Any, /) -> Member: - if not isinstance(value, Member): - raise TransformerError(value, self.type, self) - return value - - -class BaseChannelTransformer(Transformer): - def __init__(self, *channel_types: Type[Any]) -> None: - super().__init__() - if len(channel_types) == 1: - display_name = channel_types[0].__name__ - types = CHANNEL_TO_TYPES[channel_types[0]] - else: - display_name = '{}, and {}'.format(', '.join(t.__name__ for t in channel_types[:-1]), channel_types[-1].__name__) - types = [] - - for t in channel_types: - try: - types.extend(CHANNEL_TO_TYPES[t]) - except KeyError: - raise TypeError(f'Union type of channels must be entirely made up of channels') from None - - self._types: Tuple[Type[Any]] = channel_types - self._channel_types: List[ChannelType] = types - self._display_name = display_name - - @property - def _error_display_name(self) -> str: - return self._display_name - - @property - def type(self) -> AppCommandOptionType: - return AppCommandOptionType.channel - - @property - def channel_types(self) -> List[ChannelType]: - return self._channel_types - - async def transform(self, interaction: Interaction, value: Any, /): - resolved = value.resolve() - if resolved is None or not isinstance(resolved, self._types): - raise TransformerError(value, AppCommandOptionType.channel, self) - return resolved - - -class RawChannelTransformer(BaseChannelTransformer): - async def transform(self, interaction: Interaction, value: Any, /): - if not isinstance(value, self._types): - raise TransformerError(value, AppCommandOptionType.channel, self) - return value - - -class UnionChannelTransformer(BaseChannelTransformer): - async def transform(self, interaction: Interaction, value: Any, /): - if isinstance(value, self._types): - return value - - resolved = value.resolve() - if resolved is None or not isinstance(resolved, self._types): - raise TransformerError(value, AppCommandOptionType.channel, self) - return resolved - - -CHANNEL_TO_TYPES: Dict[Any, List[ChannelType]] = { - AppCommandChannel: [ - ChannelType.stage_voice, - ChannelType.voice, - ChannelType.text, - ChannelType.news, - ChannelType.category, - ], - GuildChannel: [ - ChannelType.stage_voice, - ChannelType.voice, - ChannelType.text, - ChannelType.news, - ChannelType.category, - ], - AppCommandThread: [ChannelType.news_thread, ChannelType.private_thread, ChannelType.public_thread], - Thread: [ChannelType.news_thread, ChannelType.private_thread, ChannelType.public_thread], - StageChannel: [ChannelType.stage_voice], - VoiceChannel: [ChannelType.voice], - TextChannel: [ChannelType.text, ChannelType.news], - CategoryChannel: [ChannelType.category], -} - -BUILT_IN_TRANSFORMERS: Dict[Any, Transformer] = { - str: IdentityTransformer(AppCommandOptionType.string), - int: IdentityTransformer(AppCommandOptionType.integer), - float: IdentityTransformer(AppCommandOptionType.number), - bool: IdentityTransformer(AppCommandOptionType.boolean), - User: IdentityTransformer(AppCommandOptionType.user), - Member: MemberTransformer(), - Role: IdentityTransformer(AppCommandOptionType.role), - AppCommandChannel: RawChannelTransformer(AppCommandChannel), - AppCommandThread: RawChannelTransformer(AppCommandThread), - GuildChannel: BaseChannelTransformer(GuildChannel), - Thread: BaseChannelTransformer(Thread), - StageChannel: BaseChannelTransformer(StageChannel), - VoiceChannel: BaseChannelTransformer(VoiceChannel), - TextChannel: BaseChannelTransformer(TextChannel), - CategoryChannel: BaseChannelTransformer(CategoryChannel), - Attachment: IdentityTransformer(AppCommandOptionType.attachment), -} - -ALLOWED_DEFAULTS: Dict[AppCommandOptionType, Tuple[Type[Any], ...]] = { - AppCommandOptionType.string: (str, NoneType), - AppCommandOptionType.integer: (int, NoneType), - AppCommandOptionType.boolean: (bool, NoneType), - AppCommandOptionType.number: (float, NoneType), -} - - -def get_supported_annotation( - annotation: Any, - *, - _none: type = NoneType, - _mapping: Dict[Any, Transformer] = BUILT_IN_TRANSFORMERS, -) -> Tuple[Any, Any, bool]: - """Returns an appropriate, yet supported, annotation along with an optional default value. - - The third boolean element of the tuple indicates if default values should be validated. - - This differs from the built in mapping by supporting a few more things. - Likewise, this returns a "transformed" annotation that is ready to use with CommandParameter.transform. - """ - - try: - return (_mapping[annotation], MISSING, True) - except KeyError: - pass - - if isinstance(annotation, Transformer): - return (annotation, MISSING, False) - - if inspect.isclass(annotation): - if issubclass(annotation, Transformer): - return (annotation(), MISSING, False) - if issubclass(annotation, (Enum, InternalEnum)): - if all(isinstance(v.value, (str, int, float)) for v in annotation): - return (EnumValueTransformer(annotation), MISSING, False) - else: - return (EnumNameTransformer(annotation), MISSING, False) - if annotation is Choice: - raise TypeError(f'Choice requires a type argument of int, str, or float') - - # Check if a transform @classmethod is given to the class - # These flatten into simple "inline" transformers with implicit strings - transform_classmethod = annotation.__dict__.get('transform', None) - if isinstance(transform_classmethod, classmethod): - params = inspect.signature(transform_classmethod.__func__).parameters - if len(params) != 3: - raise TypeError(f'Inline transformer with transform classmethod requires 3 parameters') - if not inspect.iscoroutinefunction(transform_classmethod.__func__): - raise TypeError(f'Inline transformer with transform classmethod must be a coroutine') - return (InlineTransformer(annotation), MISSING, False) - - # Check if there's an origin - origin = getattr(annotation, '__origin__', None) - if origin is Literal: - args = annotation.__args__ # type: ignore - return (LiteralTransformer(args), MISSING, True) - - if origin is Choice: - arg = annotation.__args__[0] # type: ignore - return (ChoiceTransformer(arg), MISSING, True) - - if origin is not Union: - # Only Union/Optional is supported right now so bail early - raise TypeError(f'unsupported type annotation {annotation!r}') - - default = MISSING - args = annotation.__args__ # type: ignore - if args[-1] is _none: - if len(args) == 2: - underlying = args[0] - inner, _, validate_default = get_supported_annotation(underlying) - if inner is None: - raise TypeError(f'unsupported inner optional type {underlying!r}') - return (inner, None, validate_default) - else: - args = args[:-1] - default = None - - # Check for channel union types - if any(arg in CHANNEL_TO_TYPES for arg in args): - # If any channel type is given, then *all* must be channel types - return (UnionChannelTransformer(*args), default, True) - - # The only valid transformations here are: - # [Member, User] => user - # [Member, User, Role] => mentionable - # [Member | User, Role] => mentionable - supported_types: Set[Any] = {Role, Member, User} - if not all(arg in supported_types for arg in args): - raise TypeError(f'unsupported types given inside {annotation!r}') - if args == (User, Member) or args == (Member, User): - return (IdentityTransformer(AppCommandOptionType.user), default, True) - - return (IdentityTransformer(AppCommandOptionType.mentionable), default, True) - - -def annotation_to_parameter(annotation: Any, parameter: inspect.Parameter) -> CommandParameter: - """Returns the appropriate :class:`CommandParameter` for the given annotation. - - The resulting ``_annotation`` attribute might not match the one given here and might - be transformed in order to be easier to call from the ``transform`` asynchronous function - of a command parameter. - """ - - (inner, default, validate_default) = get_supported_annotation(annotation) - type = inner.type - - if default is MISSING or default is None: - param_default = parameter.default - if param_default is not parameter.empty: - default = param_default - - # Verify validity of the default parameter - if default is not MISSING and validate_default: - valid_types: Tuple[Any, ...] = ALLOWED_DEFAULTS.get(type, (NoneType,)) - if not isinstance(default, valid_types): - raise TypeError(f'invalid default parameter type given ({default.__class__}), expected {valid_types}') - - result = CommandParameter( - type=type, - _annotation=inner, - default=default, - required=default is MISSING, - name=parameter.name, - ) - - choices = inner.choices - if choices is not None: - result.choices = choices - - # These methods should be duck typed - if type in (AppCommandOptionType.number, AppCommandOptionType.string, AppCommandOptionType.integer): - result.min_value = inner.min_value - result.max_value = inner.max_value - - if type is AppCommandOptionType.channel: - result.channel_types = inner.channel_types - - if parameter.kind in (parameter.POSITIONAL_ONLY, parameter.VAR_KEYWORD, parameter.VAR_POSITIONAL): - raise TypeError(f'unsupported parameter kind in callback: {parameter.kind!s}') - - # Check if the method is overridden - if inner.autocomplete.__func__ is not Transformer.autocomplete: - from .commands import _validate_auto_complete_callback - - result.autocomplete = _validate_auto_complete_callback(inner.autocomplete) - - return result diff --git a/.venv/Lib/site-packages/discord/app_commands/translator.py b/.venv/Lib/site-packages/discord/app_commands/translator.py deleted file mode 100644 index 1741054..0000000 --- a/.venv/Lib/site-packages/discord/app_commands/translator.py +++ /dev/null @@ -1,305 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations -from typing import TYPE_CHECKING, Any, Generic, Literal, Optional, TypeVar, Union, overload -from .errors import TranslationError -from ..enums import Enum, Locale - - -if TYPE_CHECKING: - from .commands import Command, ContextMenu, Group, Parameter - from .models import Choice - - -__all__ = ( - 'TranslationContextLocation', - 'TranslationContextTypes', - 'TranslationContext', - 'Translator', - 'locale_str', -) - - -class TranslationContextLocation(Enum): - command_name = 0 - command_description = 1 - group_name = 2 - group_description = 3 - parameter_name = 4 - parameter_description = 5 - choice_name = 6 - other = 7 - - -_L = TypeVar('_L', bound=TranslationContextLocation) -_D = TypeVar('_D') - - -class TranslationContext(Generic[_L, _D]): - """A class that provides context for the :class:`locale_str` being translated. - - This is useful to determine where exactly the string is located and aid in looking - up the actual translation. - - Attributes - ----------- - location: :class:`TranslationContextLocation` - The location where this string is located. - data: Any - The extraneous data that is being translated. - """ - - __slots__ = ('location', 'data') - - @overload - def __init__( - self, location: Literal[TranslationContextLocation.command_name], data: Union[Command[Any, ..., Any], ContextMenu] - ) -> None: - ... - - @overload - def __init__( - self, location: Literal[TranslationContextLocation.command_description], data: Command[Any, ..., Any] - ) -> None: - ... - - @overload - def __init__( - self, - location: Literal[TranslationContextLocation.group_name, TranslationContextLocation.group_description], - data: Group, - ) -> None: - ... - - @overload - def __init__( - self, - location: Literal[TranslationContextLocation.parameter_name, TranslationContextLocation.parameter_description], - data: Parameter, - ) -> None: - ... - - @overload - def __init__(self, location: Literal[TranslationContextLocation.choice_name], data: Choice[Any]) -> None: - ... - - @overload - def __init__(self, location: Literal[TranslationContextLocation.other], data: Any) -> None: - ... - - def __init__(self, location: _L, data: _D) -> None: - self.location: _L = location - self.data: _D = data - - -# For type checking purposes, it makes sense to allow the user to leverage type narrowing -# So code like this works as expected: -# -# if context.type == TranslationContextLocation.command_name: -# reveal_type(context.data) # Revealed type is Command | ContextMenu -# -# This requires a union of types -CommandNameTranslationContext = TranslationContext[ - Literal[TranslationContextLocation.command_name], Union['Command[Any, ..., Any]', 'ContextMenu'] -] -CommandDescriptionTranslationContext = TranslationContext[ - Literal[TranslationContextLocation.command_description], 'Command[Any, ..., Any]' -] -GroupTranslationContext = TranslationContext[ - Literal[TranslationContextLocation.group_name, TranslationContextLocation.group_description], 'Group' -] -ParameterTranslationContext = TranslationContext[ - Literal[TranslationContextLocation.parameter_name, TranslationContextLocation.parameter_description], 'Parameter' -] -ChoiceTranslationContext = TranslationContext[Literal[TranslationContextLocation.choice_name], 'Choice[Any]'] -OtherTranslationContext = TranslationContext[Literal[TranslationContextLocation.other], Any] - -TranslationContextTypes = Union[ - CommandNameTranslationContext, - CommandDescriptionTranslationContext, - GroupTranslationContext, - ParameterTranslationContext, - ChoiceTranslationContext, - OtherTranslationContext, -] - - -class Translator: - """A class that handles translations for commands, parameters, and choices. - - Translations are done lazily in order to allow for async enabled translations as well - as supporting a wide array of translation systems such as :mod:`gettext` and - `Project Fluent `_. - - In order for a translator to be used, it must be set using the :meth:`CommandTree.set_translator` - method. The translation flow for a string is as follows: - - 1. Use :class:`locale_str` instead of :class:`str` in areas of a command you want to be translated. - - Currently, these are command names, command descriptions, parameter names, parameter descriptions, and choice names. - - This can also be used inside the :func:`~discord.app_commands.describe` decorator. - 2. Call :meth:`CommandTree.set_translator` to the translator instance that will handle the translations. - 3. Call :meth:`CommandTree.sync` - 4. The library will call :meth:`Translator.translate` on all the relevant strings being translated. - - .. versionadded:: 2.0 - """ - - async def load(self) -> None: - """|coro| - - An asynchronous setup function for loading the translation system. - - The default implementation does nothing. - - This is invoked when :meth:`CommandTree.set_translator` is called. - """ - pass - - async def unload(self) -> None: - """|coro| - - An asynchronous teardown function for unloading the translation system. - - The default implementation does nothing. - - This is invoked when :meth:`CommandTree.set_translator` is called - if a tree already has a translator or when :meth:`discord.Client.close` is called. - """ - pass - - async def _checked_translate( - self, string: locale_str, locale: Locale, context: TranslationContextTypes - ) -> Optional[str]: - try: - return await self.translate(string, locale, context) - except TranslationError: - raise - except Exception as e: - raise TranslationError(string=string, locale=locale, context=context) from e - - async def translate(self, string: locale_str, locale: Locale, context: TranslationContextTypes) -> Optional[str]: - """|coro| - - Translates the given string to the specified locale. - - If the string cannot be translated, ``None`` should be returned. - - The default implementation returns ``None``. - - If an exception is raised in this method, it should inherit from :exc:`TranslationError`. - If it doesn't, then when this is called the exception will be chained with it instead. - - Parameters - ------------ - string: :class:`locale_str` - The string being translated. - locale: :class:`~discord.Locale` - The locale being requested for translation. - context: :class:`TranslationContext` - The translation context where the string originated from. - For better type checking ergonomics, the ``TranslationContextTypes`` - type can be used instead to aid with type narrowing. It is functionally - equivalent to :class:`TranslationContext`. - """ - - return None - - -class locale_str: - """Marks a string as ready for translation. - - This is done lazily and is not actually translated until :meth:`CommandTree.sync` is called. - - The sync method then ultimately defers the responsibility of translating to the :class:`Translator` - instance used by the :class:`CommandTree`. For more information on the translation flow, see the - :class:`Translator` documentation. - - .. container:: operations - - .. describe:: str(x) - - Returns the message passed to the string. - - .. describe:: x == y - - Checks if the string is equal to another string. - - .. describe:: x != y - - Checks if the string is not equal to another string. - - .. describe:: hash(x) - - Returns the hash of the string. - - .. versionadded:: 2.0 - - Attributes - ------------ - message: :class:`str` - The message being translated. Once set, this cannot be changed. - - .. warning:: - - This must be the default "message" that you send to Discord. - Discord sends this message back to the library and the library - uses it to access the data in order to dispatch commands. - - For example, in a command name context, if the command - name is ``foo`` then the message *must* also be ``foo``. - For other translation systems that require a message ID such - as Fluent, consider using a keyword argument to pass it in. - extras: :class:`dict` - A dict of user provided extras to attach to the translated string. - This can be used to add more context, information, or any metadata necessary - to aid in actually translating the string. - - Since these are passed via keyword arguments, the keys are strings. - """ - - __slots__ = ('__message', 'extras') - - def __init__(self, message: str, /, **kwargs: Any) -> None: - self.__message: str = message - self.extras: dict[str, Any] = kwargs - - @property - def message(self) -> str: - return self.__message - - def __str__(self) -> str: - return self.__message - - def __repr__(self) -> str: - kwargs = ', '.join(f'{k}={v!r}' for k, v in self.extras.items()) - if kwargs: - return f'{self.__class__.__name__}({self.__message!r}, {kwargs})' - return f'{self.__class__.__name__}({self.__message!r})' - - def __eq__(self, obj: object) -> bool: - return isinstance(obj, locale_str) and self.message == obj.message - - def __hash__(self) -> int: - return hash(self.__message) diff --git a/.venv/Lib/site-packages/discord/app_commands/tree.py b/.venv/Lib/site-packages/discord/app_commands/tree.py deleted file mode 100644 index 5ee4a6a..0000000 --- a/.venv/Lib/site-packages/discord/app_commands/tree.py +++ /dev/null @@ -1,1247 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations -import logging -import inspect - -from typing import ( - Any, - TYPE_CHECKING, - Callable, - Coroutine, - Dict, - Generator, - Generic, - List, - Literal, - Optional, - Sequence, - Set, - Tuple, - TypeVar, - Union, - overload, -) -from collections import Counter - - -from .namespace import Namespace, ResolveKey -from .models import AppCommand -from .commands import Command, ContextMenu, Group, _shorten -from .errors import ( - AppCommandError, - CommandAlreadyRegistered, - CommandNotFound, - CommandSignatureMismatch, - CommandLimitReached, - CommandSyncFailure, - MissingApplicationID, -) -from .translator import Translator, locale_str -from ..errors import ClientException, HTTPException -from ..enums import AppCommandType, InteractionType -from ..utils import MISSING, _get_as_snowflake, _is_submodule - -if TYPE_CHECKING: - from ..types.interactions import ApplicationCommandInteractionData, ApplicationCommandInteractionDataOption - from ..interactions import Interaction - from ..client import Client - from ..abc import Snowflake - from .commands import ContextMenuCallback, CommandCallback, P, T - - ErrorFunc = Callable[ - [Interaction, AppCommandError], - Coroutine[Any, Any, Any], - ] - -__all__ = ('CommandTree',) - -ClientT = TypeVar('ClientT', bound='Client') - -_log = logging.getLogger(__name__) - - -def _retrieve_guild_ids( - command: Any, guild: Optional[Snowflake] = MISSING, guilds: Sequence[Snowflake] = MISSING -) -> Optional[Set[int]]: - if guild is not MISSING and guilds is not MISSING: - raise TypeError('cannot mix guild and guilds keyword arguments') - - # guilds=[] or guilds=[...] - if guild is MISSING: - # If no arguments are given then it should default to the ones - # given to the guilds(...) decorator or None for global. - if guilds is MISSING: - return getattr(command, '_guild_ids', None) - - # guilds=[] is the same as global - if len(guilds) == 0: - return None - - return {g.id for g in guilds} - - # At this point it should be... - # guild=None or guild=Object - if guild is None: - return None - return {guild.id} - - -class CommandTree(Generic[ClientT]): - """Represents a container that holds application command information. - - Parameters - ----------- - client: :class:`~discord.Client` - The client instance to get application command information from. - fallback_to_global: :class:`bool` - If a guild-specific command is not found when invoked, then try falling back into - a global command in the tree. For example, if the tree locally has a ``/ping`` command - under the global namespace but the guild has a guild-specific ``/ping``, instead of failing - to find the guild-specific ``/ping`` command it will fall back to the global ``/ping`` command. - This has the potential to raise more :exc:`~discord.app_commands.CommandSignatureMismatch` errors - than usual. Defaults to ``True``. - """ - - def __init__(self, client: ClientT, *, fallback_to_global: bool = True): - self.client: ClientT = client - self._http = client.http - self._state = client._connection - - if self._state._command_tree is not None: - raise ClientException('This client already has an associated command tree.') - - self._state._command_tree = self - self.fallback_to_global: bool = fallback_to_global - self._guild_commands: Dict[int, Dict[str, Union[Command, Group]]] = {} - self._global_commands: Dict[str, Union[Command, Group]] = {} - # (name, guild_id, command_type): Command - # The above two mappings can use this structure too but we need fast retrieval - # by name and guild_id in the above case while here it isn't as important since - # it's uncommon and N=5 anyway. - self._context_menus: Dict[Tuple[str, Optional[int], int], ContextMenu] = {} - - async def fetch_command(self, command_id: int, /, *, guild: Optional[Snowflake] = None) -> AppCommand: - """|coro| - - Fetches an application command from the application. - - Parameters - ----------- - command_id: :class:`int` - The ID of the command to fetch. - guild: Optional[:class:`~discord.abc.Snowflake`] - The guild to fetch the command from. If not passed then the global command - is fetched instead. - - Raises - ------- - HTTPException - Fetching the command failed. - MissingApplicationID - The application ID could not be found. - NotFound - The application command was not found. - This could also be because the command is a guild command - and the guild was not specified and vice versa. - - Returns - -------- - :class:`~discord.app_commands.AppCommand` - The application command. - """ - if self.client.application_id is None: - raise MissingApplicationID - - if guild is None: - command = await self._http.get_global_command(self.client.application_id, command_id) - else: - command = await self._http.get_guild_command(self.client.application_id, guild.id, command_id) - - return AppCommand(data=command, state=self._state) - - async def fetch_commands(self, *, guild: Optional[Snowflake] = None) -> List[AppCommand]: - """|coro| - - Fetches the application's current commands. - - If no guild is passed then global commands are fetched, otherwise - the guild's commands are fetched instead. - - .. note:: - - This includes context menu commands. - - Parameters - ----------- - guild: Optional[:class:`~discord.abc.Snowflake`] - The guild to fetch the commands from. If not passed then global commands - are fetched instead. - - Raises - ------- - HTTPException - Fetching the commands failed. - MissingApplicationID - The application ID could not be found. - - Returns - -------- - List[:class:`~discord.app_commands.AppCommand`] - The application's commands. - """ - if self.client.application_id is None: - raise MissingApplicationID - - if guild is None: - commands = await self._http.get_global_commands(self.client.application_id) - else: - commands = await self._http.get_guild_commands(self.client.application_id, guild.id) - - return [AppCommand(data=data, state=self._state) for data in commands] - - def copy_global_to(self, *, guild: Snowflake) -> None: - """Copies all global commands to the specified guild. - - This method is mainly available for development purposes, as it allows you - to copy your global commands over to a testing guild easily. - - Note that this method will *override* pre-existing guild commands that would conflict. - - Parameters - ----------- - guild: :class:`~discord.abc.Snowflake` - The guild to copy the commands to. - - Raises - -------- - CommandLimitReached - The maximum number of commands was reached for that guild. - This is currently 100 for slash commands and 5 for context menu commands. - """ - - try: - mapping = self._guild_commands[guild.id].copy() - except KeyError: - mapping = {} - - mapping.update(self._global_commands) - if len(mapping) > 100: - raise CommandLimitReached(guild_id=guild.id, limit=100) - - ctx_menu: Dict[Tuple[str, Optional[int], int], ContextMenu] = { - (name, guild.id, cmd_type): cmd - for ((name, g, cmd_type), cmd) in self._context_menus.items() - if g is None or g == guild.id - } - - counter = Counter(cmd_type for _, _, cmd_type in ctx_menu) - for cmd_type, count in counter.items(): - if count > 5: - as_enum = AppCommandType(cmd_type) - raise CommandLimitReached(guild_id=guild.id, limit=5, type=as_enum) - - self._context_menus.update(ctx_menu) - self._guild_commands[guild.id] = mapping - - def add_command( - self, - command: Union[Command[Any, ..., Any], ContextMenu, Group], - /, - *, - guild: Optional[Snowflake] = MISSING, - guilds: Sequence[Snowflake] = MISSING, - override: bool = False, - ) -> None: - """Adds an application command to the tree. - - This only adds the command locally -- in order to sync the commands - and enable them in the client, :meth:`sync` must be called. - - The root parent of the command is added regardless of the type passed. - - Parameters - ----------- - command: Union[:class:`Command`, :class:`Group`] - The application command or group to add. - guild: Optional[:class:`~discord.abc.Snowflake`] - The guild to add the command to. If not given or ``None`` then it - becomes a global command instead. - guilds: List[:class:`~discord.abc.Snowflake`] - The list of guilds to add the command to. This cannot be mixed - with the ``guild`` parameter. If no guilds are given at all - then it becomes a global command instead. - override: :class:`bool` - Whether to override a command with the same name. If ``False`` - an exception is raised. Default is ``False``. - - Raises - -------- - ~discord.app_commands.CommandAlreadyRegistered - The command was already registered and no override was specified. - TypeError - The application command passed is not a valid application command. - Or, ``guild`` and ``guilds`` were both given. - CommandLimitReached - The maximum number of commands was reached globally or for that guild. - This is currently 100 for slash commands and 5 for context menu commands. - """ - - guild_ids = _retrieve_guild_ids(command, guild, guilds) - if isinstance(command, ContextMenu): - type = command.type.value - name = command.name - - def _context_menu_add_helper( - guild_id: Optional[int], - data: Dict[Tuple[str, Optional[int], int], ContextMenu], - name: str = name, - type: int = type, - ) -> None: - key = (name, guild_id, type) - found = key in self._context_menus - if found and not override: - raise CommandAlreadyRegistered(name, guild_id) - - # If the key is found and overridden then it shouldn't count as an extra addition - # read as `0 if override and found else 1` if confusing - to_add = not (override and found) - total = sum(1 for _, g, t in self._context_menus if g == guild_id and t == type) - if total + to_add > 5: - raise CommandLimitReached(guild_id=guild_id, limit=5, type=AppCommandType(type)) - data[key] = command - - if guild_ids is None: - _context_menu_add_helper(None, self._context_menus) - else: - current: Dict[Tuple[str, Optional[int], int], ContextMenu] = {} - for guild_id in guild_ids: - _context_menu_add_helper(guild_id, current) - - # Update at the end in order to make sure the update is atomic. - # An error during addition could end up making the context menu mapping - # have a partial state - self._context_menus.update(current) - return - elif not isinstance(command, (Command, Group)): - raise TypeError(f'Expected an application command, received {command.__class__!r} instead') - - # todo: validate application command groups having children (required) - - root = command.root_parent or command - name = root.name - if guild_ids is not None: - # Validate that the command can be added first, before actually - # adding it into the mapping. This ensures atomicity. - for guild_id in guild_ids: - commands = self._guild_commands.get(guild_id, {}) - found = name in commands - if found and not override: - raise CommandAlreadyRegistered(name, guild_id) - - to_add = not (override and found) - if len(commands) + to_add > 100: - raise CommandLimitReached(guild_id=guild_id, limit=100) - - # Actually add the command now that it has been verified to be okay. - for guild_id in guild_ids: - commands = self._guild_commands.setdefault(guild_id, {}) - commands[name] = root - else: - found = name in self._global_commands - if found and not override: - raise CommandAlreadyRegistered(name, None) - - to_add = not (override and found) - if len(self._global_commands) + to_add > 100: - raise CommandLimitReached(guild_id=None, limit=100) - self._global_commands[name] = root - - @overload - def remove_command( - self, - command: str, - /, - *, - guild: Optional[Snowflake] = ..., - type: Literal[AppCommandType.message, AppCommandType.user], - ) -> Optional[ContextMenu]: - ... - - @overload - def remove_command( - self, - command: str, - /, - *, - guild: Optional[Snowflake] = ..., - type: Literal[AppCommandType.chat_input] = ..., - ) -> Optional[Union[Command[Any, ..., Any], Group]]: - ... - - @overload - def remove_command( - self, - command: str, - /, - *, - guild: Optional[Snowflake] = ..., - type: AppCommandType, - ) -> Optional[Union[Command[Any, ..., Any], ContextMenu, Group]]: - ... - - def remove_command( - self, - command: str, - /, - *, - guild: Optional[Snowflake] = None, - type: AppCommandType = AppCommandType.chat_input, - ) -> Optional[Union[Command[Any, ..., Any], ContextMenu, Group]]: - """Removes an application command from the tree. - - This only removes the command locally -- in order to sync the commands - and remove them in the client, :meth:`sync` must be called. - - Parameters - ----------- - command: :class:`str` - The name of the root command to remove. - guild: Optional[:class:`~discord.abc.Snowflake`] - The guild to remove the command from. If not given or ``None`` then it - removes a global command instead. - type: :class:`~discord.AppCommandType` - The type of command to remove. Defaults to :attr:`~discord.AppCommandType.chat_input`, - i.e. slash commands. - - Returns - --------- - Optional[Union[:class:`Command`, :class:`ContextMenu`, :class:`Group`]] - The application command that got removed. - If nothing was removed then ``None`` is returned instead. - """ - - if type is AppCommandType.chat_input: - if guild is None: - return self._global_commands.pop(command, None) - else: - try: - commands = self._guild_commands[guild.id] - except KeyError: - return None - else: - return commands.pop(command, None) - elif type in (AppCommandType.user, AppCommandType.message): - guild_id = None if guild is None else guild.id - key = (command, guild_id, type.value) - return self._context_menus.pop(key, None) - - def clear_commands(self, *, guild: Optional[Snowflake], type: Optional[AppCommandType] = None) -> None: - """Clears all application commands from the tree. - - This only removes the commands locally -- in order to sync the commands - and remove them in the client, :meth:`sync` must be called. - - Parameters - ----------- - guild: Optional[:class:`~discord.abc.Snowflake`] - The guild to remove the commands from. If ``None`` then it - removes all global commands instead. - type: :class:`~discord.AppCommandType` - The type of command to clear. If not given or ``None`` then it removes all commands - regardless of the type. - """ - - if type is None or type is AppCommandType.chat_input: - if guild is None: - self._global_commands.clear() - else: - try: - commands = self._guild_commands[guild.id] - except KeyError: - pass - else: - commands.clear() - - guild_id = None if guild is None else guild.id - if type is None: - self._context_menus = { - (name, _guild_id, value): cmd - for (name, _guild_id, value), cmd in self._context_menus.items() - if _guild_id != guild_id - } - elif type in (AppCommandType.user, AppCommandType.message): - self._context_menus = { - (name, _guild_id, value): cmd - for (name, _guild_id, value), cmd in self._context_menus.items() - if _guild_id != guild_id or value != type.value - } - - @overload - def get_command( - self, - command: str, - /, - *, - guild: Optional[Snowflake] = ..., - type: Literal[AppCommandType.message, AppCommandType.user], - ) -> Optional[ContextMenu]: - ... - - @overload - def get_command( - self, - command: str, - /, - *, - guild: Optional[Snowflake] = ..., - type: Literal[AppCommandType.chat_input] = ..., - ) -> Optional[Union[Command[Any, ..., Any], Group]]: - ... - - @overload - def get_command( - self, - command: str, - /, - *, - guild: Optional[Snowflake] = ..., - type: AppCommandType, - ) -> Optional[Union[Command[Any, ..., Any], ContextMenu, Group]]: - ... - - def get_command( - self, - command: str, - /, - *, - guild: Optional[Snowflake] = None, - type: AppCommandType = AppCommandType.chat_input, - ) -> Optional[Union[Command[Any, ..., Any], ContextMenu, Group]]: - """Gets an application command from the tree. - - Parameters - ----------- - command: :class:`str` - The name of the root command to get. - guild: Optional[:class:`~discord.abc.Snowflake`] - The guild to get the command from. If not given or ``None`` then it - gets a global command instead. - type: :class:`~discord.AppCommandType` - The type of command to get. Defaults to :attr:`~discord.AppCommandType.chat_input`, - i.e. slash commands. - - Returns - --------- - Optional[Union[:class:`Command`, :class:`ContextMenu`, :class:`Group`]] - The application command that was found. - If nothing was found then ``None`` is returned instead. - """ - - if type is AppCommandType.chat_input: - if guild is None: - return self._global_commands.get(command) - else: - try: - commands = self._guild_commands[guild.id] - except KeyError: - return None - else: - return commands.get(command) - elif type in (AppCommandType.user, AppCommandType.message): - guild_id = None if guild is None else guild.id - key = (command, guild_id, type.value) - return self._context_menus.get(key) - - @overload - def get_commands( - self, - *, - guild: Optional[Snowflake] = ..., - type: Literal[AppCommandType.message, AppCommandType.user], - ) -> List[ContextMenu]: - ... - - @overload - def get_commands( - self, - *, - guild: Optional[Snowflake] = ..., - type: Literal[AppCommandType.chat_input], - ) -> List[Union[Command[Any, ..., Any], Group]]: - ... - - @overload - def get_commands( - self, - *, - guild: Optional[Snowflake] = ..., - type: AppCommandType, - ) -> Union[List[Union[Command[Any, ..., Any], Group]], List[ContextMenu]]: - ... - - @overload - def get_commands( - self, - *, - guild: Optional[Snowflake] = ..., - type: Optional[AppCommandType] = ..., - ) -> List[Union[Command[Any, ..., Any], Group, ContextMenu]]: - ... - - def get_commands( - self, - *, - guild: Optional[Snowflake] = None, - type: Optional[AppCommandType] = None, - ) -> Union[ - List[ContextMenu], - List[Union[Command[Any, ..., Any], Group]], - List[Union[Command[Any, ..., Any], Group, ContextMenu]], - ]: - """Gets all application commands from the tree. - - Parameters - ----------- - guild: Optional[:class:`~discord.abc.Snowflake`] - The guild to get the commands from, not including global commands. - If not given or ``None`` then only global commands are returned. - type: Optional[:class:`~discord.AppCommandType`] - The type of commands to get. When not given or ``None``, then all - command types are returned. - - Returns - --------- - List[Union[:class:`ContextMenu`, :class:`Command`, :class:`Group`]] - The application commands from the tree. - """ - if type is None: - return self._get_all_commands(guild=guild) - - if type is AppCommandType.chat_input: - if guild is None: - return list(self._global_commands.values()) - else: - try: - commands = self._guild_commands[guild.id] - except KeyError: - return [] - else: - return list(commands.values()) - else: - guild_id = None if guild is None else guild.id - value = type.value - return [command for ((_, g, t), command) in self._context_menus.items() if g == guild_id and t == value] - - @overload - def walk_commands( - self, - *, - guild: Optional[Snowflake] = ..., - type: Literal[AppCommandType.message, AppCommandType.user], - ) -> Generator[ContextMenu, None, None]: - ... - - @overload - def walk_commands( - self, - *, - guild: Optional[Snowflake] = ..., - type: Literal[AppCommandType.chat_input] = ..., - ) -> Generator[Union[Command[Any, ..., Any], Group], None, None]: - ... - - @overload - def walk_commands( - self, - *, - guild: Optional[Snowflake] = ..., - type: AppCommandType, - ) -> Union[Generator[Union[Command[Any, ..., Any], Group], None, None], Generator[ContextMenu, None, None]]: - ... - - def walk_commands( - self, - *, - guild: Optional[Snowflake] = None, - type: AppCommandType = AppCommandType.chat_input, - ) -> Union[Generator[Union[Command[Any, ..., Any], Group], None, None], Generator[ContextMenu, None, None]]: - """An iterator that recursively walks through all application commands and child commands from the tree. - - Parameters - ----------- - guild: Optional[:class:`~discord.abc.Snowflake`] - The guild to iterate the commands from, not including global commands. - If not given or ``None`` then only global commands are iterated. - type: :class:`~discord.AppCommandType` - The type of commands to iterate over. Defaults to :attr:`~discord.AppCommandType.chat_input`, - i.e. slash commands. - - Yields - --------- - Union[:class:`ContextMenu`, :class:`Command`, :class:`Group`] - The application commands from the tree. - """ - - if type is AppCommandType.chat_input: - if guild is None: - for cmd in self._global_commands.values(): - yield cmd - if isinstance(cmd, Group): - yield from cmd.walk_commands() - else: - try: - commands = self._guild_commands[guild.id] - except KeyError: - return - else: - for cmd in commands.values(): - yield cmd - if isinstance(cmd, Group): - yield from cmd.walk_commands() - else: - guild_id = None if guild is None else guild.id - value = type.value - for ((_, g, t), command) in self._context_menus.items(): - if g == guild_id and t == value: - yield command - - def _get_all_commands( - self, *, guild: Optional[Snowflake] = None - ) -> List[Union[Command[Any, ..., Any], Group, ContextMenu]]: - if guild is None: - base: List[Union[Command[Any, ..., Any], Group, ContextMenu]] = list(self._global_commands.values()) - base.extend(cmd for ((_, g, _), cmd) in self._context_menus.items() if g is None) - return base - else: - try: - commands = self._guild_commands[guild.id] - except KeyError: - guild_id = guild.id - return [cmd for ((_, g, _), cmd) in self._context_menus.items() if g == guild_id] - else: - base: List[Union[Command[Any, ..., Any], Group, ContextMenu]] = list(commands.values()) - guild_id = guild.id - base.extend(cmd for ((_, g, _), cmd) in self._context_menus.items() if g == guild_id) - return base - - def _remove_with_module(self, name: str) -> None: - remove: List[Any] = [] - for key, cmd in self._context_menus.items(): - if cmd.module is not None and _is_submodule(name, cmd.module): - remove.append(key) - - for key in remove: - del self._context_menus[key] - - remove = [] - for key, cmd in self._global_commands.items(): - if cmd.module is not None and _is_submodule(name, cmd.module): - remove.append(key) - - for key in remove: - del self._global_commands[key] - - for mapping in self._guild_commands.values(): - remove = [] - for key, cmd in mapping.items(): - if cmd.module is not None and _is_submodule(name, cmd.module): - remove.append(key) - - for key in remove: - del mapping[key] - - async def on_error(self, interaction: Interaction, error: AppCommandError, /) -> None: - """|coro| - - A callback that is called when any command raises an :exc:`AppCommandError`. - - The default implementation logs the exception using the library logger - if the command does not have any error handlers attached to it. - - To get the command that failed, :attr:`discord.Interaction.command` should - be used. - - Parameters - ----------- - interaction: :class:`~discord.Interaction` - The interaction that is being handled. - error: :exc:`AppCommandError` - The exception that was raised. - """ - - command = interaction.command - if command is not None: - if command._has_any_error_handlers(): - return - - _log.error('Ignoring exception in command %r', command.name, exc_info=error) - else: - _log.error('Ignoring exception in command tree', exc_info=error) - - def error(self, coro: ErrorFunc) -> ErrorFunc: - """A decorator that registers a coroutine as a local error handler. - - This must match the signature of the :meth:`on_error` callback. - - The error passed will be derived from :exc:`AppCommandError`. - - Parameters - ----------- - coro: :ref:`coroutine ` - The coroutine to register as the local error handler. - - Raises - ------- - TypeError - The coroutine passed is not actually a coroutine or does - not match the signature. - """ - - if not inspect.iscoroutinefunction(coro): - raise TypeError('The error handler must be a coroutine.') - - params = inspect.signature(coro).parameters - if len(params) != 2: - raise TypeError('error handler must have 2 parameters') - - self.on_error = coro - return coro - - def command( - self, - *, - name: Union[str, locale_str] = MISSING, - description: Union[str, locale_str] = MISSING, - nsfw: bool = False, - guild: Optional[Snowflake] = MISSING, - guilds: Sequence[Snowflake] = MISSING, - auto_locale_strings: bool = True, - extras: Dict[Any, Any] = MISSING, - ) -> Callable[[CommandCallback[Group, P, T]], Command[Group, P, T]]: - """A decorator that creates an application command from a regular function directly under this tree. - - Parameters - ------------ - name: Union[:class:`str`, :class:`locale_str`] - The name of the application command. If not given, it defaults to a lower-case - version of the callback name. - description: Union[:class:`str`, :class:`locale_str`] - The description of the application command. This shows up in the UI to describe - the application command. If not given, it defaults to the first line of the docstring - of the callback shortened to 100 characters. - nsfw: :class:`bool` - Whether the command is NSFW and should only work in NSFW channels. Defaults to ``False``. - - Due to a Discord limitation, this does not work on subcommands. - guild: Optional[:class:`~discord.abc.Snowflake`] - The guild to add the command to. If not given or ``None`` then it - becomes a global command instead. - guilds: List[:class:`~discord.abc.Snowflake`] - The list of guilds to add the command to. This cannot be mixed - with the ``guild`` parameter. If no guilds are given at all - then it becomes a global command instead. - auto_locale_strings: :class:`bool` - If this is set to ``True``, then all translatable strings will implicitly - be wrapped into :class:`locale_str` rather than :class:`str`. This could - avoid some repetition and be more ergonomic for certain defaults such - as default command names, command descriptions, and parameter names. - Defaults to ``True``. - extras: :class:`dict` - A dictionary that can be used to store extraneous data. - The library will not touch any values or keys within this dictionary. - """ - - def decorator(func: CommandCallback[Group, P, T]) -> Command[Group, P, T]: - if not inspect.iscoroutinefunction(func): - raise TypeError('command function must be a coroutine function') - - if description is MISSING: - if func.__doc__ is None: - desc = '…' - else: - desc = _shorten(func.__doc__) - else: - desc = description - - command = Command( - name=name if name is not MISSING else func.__name__, - description=desc, - callback=func, - nsfw=nsfw, - parent=None, - auto_locale_strings=auto_locale_strings, - extras=extras, - ) - self.add_command(command, guild=guild, guilds=guilds) - return command - - return decorator - - def context_menu( - self, - *, - name: Union[str, locale_str] = MISSING, - nsfw: bool = False, - guild: Optional[Snowflake] = MISSING, - guilds: Sequence[Snowflake] = MISSING, - auto_locale_strings: bool = True, - extras: Dict[Any, Any] = MISSING, - ) -> Callable[[ContextMenuCallback], ContextMenu]: - """A decorator that creates an application command context menu from a regular function directly under this tree. - - This function must have a signature of :class:`~discord.Interaction` as its first parameter - and taking either a :class:`~discord.Member`, :class:`~discord.User`, or :class:`~discord.Message`, - or a :obj:`typing.Union` of ``Member`` and ``User`` as its second parameter. - - Examples - --------- - - .. code-block:: python3 - - @app_commands.context_menu() - async def react(interaction: discord.Interaction, message: discord.Message): - await interaction.response.send_message('Very cool message!', ephemeral=True) - - @app_commands.context_menu() - async def ban(interaction: discord.Interaction, user: discord.Member): - await interaction.response.send_message(f'Should I actually ban {user}...', ephemeral=True) - - Parameters - ------------ - name: Union[:class:`str`, :class:`locale_str`] - The name of the context menu command. If not given, it defaults to a title-case - version of the callback name. Note that unlike regular slash commands this can - have spaces and upper case characters in the name. - nsfw: :class:`bool` - Whether the command is NSFW and should only work in NSFW channels. Defaults to ``False``. - - Due to a Discord limitation, this does not work on subcommands. - guild: Optional[:class:`~discord.abc.Snowflake`] - The guild to add the command to. If not given or ``None`` then it - becomes a global command instead. - guilds: List[:class:`~discord.abc.Snowflake`] - The list of guilds to add the command to. This cannot be mixed - with the ``guild`` parameter. If no guilds are given at all - then it becomes a global command instead. - auto_locale_strings: :class:`bool` - If this is set to ``True``, then all translatable strings will implicitly - be wrapped into :class:`locale_str` rather than :class:`str`. This could - avoid some repetition and be more ergonomic for certain defaults such - as default command names, command descriptions, and parameter names. - Defaults to ``True``. - extras: :class:`dict` - A dictionary that can be used to store extraneous data. - The library will not touch any values or keys within this dictionary. - """ - - def decorator(func: ContextMenuCallback) -> ContextMenu: - if not inspect.iscoroutinefunction(func): - raise TypeError('context menu function must be a coroutine function') - - actual_name = func.__name__.title() if name is MISSING else name - context_menu = ContextMenu( - name=actual_name, - nsfw=nsfw, - callback=func, - auto_locale_strings=auto_locale_strings, - extras=extras, - ) - self.add_command(context_menu, guild=guild, guilds=guilds) - return context_menu - - return decorator - - @property - def translator(self) -> Optional[Translator]: - """Optional[:class:`Translator`]: The translator, if any, responsible for handling translation of commands. - - To change the translator, use :meth:`set_translator`. - """ - return self._state._translator - - async def set_translator(self, translator: Optional[Translator]) -> None: - """Sets the translator to use for translating commands. - - If a translator was previously set, it will be unloaded using its - :meth:`Translator.unload` method. - - When a translator is set, it will be loaded using its :meth:`Translator.load` method. - - Parameters - ------------ - translator: Optional[:class:`Translator`] - The translator to use. If ``None`` then the translator is just removed and unloaded. - - Raises - ------- - TypeError - The translator was not ``None`` or a :class:`Translator` instance. - """ - - if translator is not None and not isinstance(translator, Translator): - raise TypeError(f'expected None or Translator instance, received {translator.__class__!r} instead') - - old_translator = self._state._translator - if old_translator is not None: - await old_translator.unload() - - if translator is None: - self._state._translator = None - else: - await translator.load() - self._state._translator = translator - - async def sync(self, *, guild: Optional[Snowflake] = None) -> List[AppCommand]: - """|coro| - - Syncs the application commands to Discord. - - This also runs the translator to get the translated strings necessary for - feeding back into Discord. - - This must be called for the application commands to show up. - - Parameters - ----------- - guild: Optional[:class:`~discord.abc.Snowflake`] - The guild to sync the commands to. If ``None`` then it - syncs all global commands instead. - - Raises - ------- - HTTPException - Syncing the commands failed. - CommandSyncFailure - Syncing the commands failed due to a user related error, typically because - the command has invalid data. This is equivalent to an HTTP status code of - 400. - Forbidden - The client does not have the ``applications.commands`` scope in the guild. - MissingApplicationID - The client does not have an application ID. - TranslationError - An error occurred while translating the commands. - - Returns - -------- - List[:class:`AppCommand`] - The application's commands that got synced. - """ - - if self.client.application_id is None: - raise MissingApplicationID - - commands = self._get_all_commands(guild=guild) - - translator = self.translator - if translator: - payload = [await command.get_translated_payload(translator) for command in commands] - else: - payload = [command.to_dict() for command in commands] - - try: - if guild is None: - data = await self._http.bulk_upsert_global_commands(self.client.application_id, payload=payload) - else: - data = await self._http.bulk_upsert_guild_commands(self.client.application_id, guild.id, payload=payload) - except HTTPException as e: - if e.status == 400: - raise CommandSyncFailure(e, commands) from None - raise - - return [AppCommand(data=d, state=self._state) for d in data] - - async def _dispatch_error(self, interaction: Interaction, error: AppCommandError, /) -> None: - command = interaction.command - interaction.command_failed = True - try: - if isinstance(command, Command): - await command._invoke_error_handlers(interaction, error) - finally: - await self.on_error(interaction, error) - - def _from_interaction(self, interaction: Interaction) -> None: - async def wrapper(): - try: - await self._call(interaction) - except AppCommandError as e: - await self._dispatch_error(interaction, e) - - self.client.loop.create_task(wrapper(), name='CommandTree-invoker') - - def _get_context_menu(self, data: ApplicationCommandInteractionData) -> Optional[ContextMenu]: - name = data['name'] - guild_id = _get_as_snowflake(data, 'guild_id') - t = data.get('type', 1) - cmd = self._context_menus.get((name, guild_id, t)) - if cmd is None and self.fallback_to_global: - return self._context_menus.get((name, None, t)) - return cmd - - def _get_app_command_options( - self, data: ApplicationCommandInteractionData - ) -> Tuple[Command[Any, ..., Any], List[ApplicationCommandInteractionDataOption]]: - parents: List[str] = [] - name = data['name'] - - command_guild_id = _get_as_snowflake(data, 'guild_id') - if command_guild_id: - try: - guild_commands = self._guild_commands[command_guild_id] - except KeyError: - command = None if not self.fallback_to_global else self._global_commands.get(name) - else: - command = guild_commands.get(name) - if command is None and self.fallback_to_global: - command = self._global_commands.get(name) - else: - command = self._global_commands.get(name) - - # If it's not found at this point then it's not gonna be found at any point - if command is None: - raise CommandNotFound(name, parents) - - # This could be done recursively but it'd be a bother due to the state needed - # to be tracked above like the parents, the actual command type, and the - # resulting options we care about - searching = True - options: List[ApplicationCommandInteractionDataOption] = data.get('options', []) - while searching: - for option in options: - # Find subcommands - if option.get('type', 0) in (1, 2): - parents.append(name) - name = option['name'] - command = command._get_internal_command(name) - if command is None: - raise CommandNotFound(name, parents) - options = option.get('options', []) - break - else: - searching = False - break - else: - break - - if isinstance(command, Group): - # Right now, groups can't be invoked. This is a Discord limitation in how they - # do slash commands. So if we're here and we have a Group rather than a Command instance - # then something in the code is out of date from the data that Discord has. - raise CommandSignatureMismatch(command) - - return (command, options) - - async def _call_context_menu(self, interaction: Interaction, data: ApplicationCommandInteractionData, type: int) -> None: - name = data['name'] - guild_id = _get_as_snowflake(data, 'guild_id') - ctx_menu = self._context_menus.get((name, guild_id, type)) - if ctx_menu is None and self.fallback_to_global: - ctx_menu = self._context_menus.get((name, None, type)) - - # Pre-fill the cached slot to prevent re-computation - interaction._cs_command = ctx_menu - - if ctx_menu is None: - raise CommandNotFound(name, [], AppCommandType(type)) - - resolved = Namespace._get_resolved_items(interaction, data.get('resolved', {})) - - # This is annotated as str | int but realistically this will always be str - target_id: Optional[Union[str, int]] = data.get('target_id') - # Right now, the only types are message and user - # Therefore, there's no conflict with snowflakes - - # This will always work at runtime - key = ResolveKey.any_with(target_id) # type: ignore - value = resolved.get(key) - if ctx_menu.type.value != type: - raise CommandSignatureMismatch(ctx_menu) - - if value is None: - raise AppCommandError('This should not happen if Discord sent well-formed data.') - - # I assume I don't have to type check here. - try: - await ctx_menu._invoke(interaction, value) - except AppCommandError as e: - if ctx_menu.on_error is not None: - await ctx_menu.on_error(interaction, e) - await self.on_error(interaction, e) - else: - self.client.dispatch('app_command_completion', interaction, ctx_menu) - - async def interaction_check(self, interaction: Interaction, /) -> bool: - """|coro| - - A global check to determine if an :class:`~discord.Interaction` should - be processed by the tree. - - The default implementation returns True (all interactions are processed), - but can be overridden if custom behaviour is desired. - """ - return True - - async def _call(self, interaction: Interaction) -> None: - if not await self.interaction_check(interaction): - interaction.command_failed = True - return - - data: ApplicationCommandInteractionData = interaction.data # type: ignore - type = data.get('type', 1) - if type != 1: - # Context menu command... - await self._call_context_menu(interaction, data, type) - return - - command, options = self._get_app_command_options(data) - - # Pre-fill the cached slot to prevent re-computation - interaction._cs_command = command - - # At this point options refers to the arguments of the command - # and command refers to the class type we care about - namespace = Namespace(interaction, data.get('resolved', {}), options) - - # Same pre-fill as above - interaction._cs_namespace = namespace - - # Auto complete handles the namespace differently... so at this point this is where we decide where that is. - if interaction.type is InteractionType.autocomplete: - focused = next((opt['name'] for opt in options if opt.get('focused')), None) - if focused is None: - raise AppCommandError('This should not happen, but there is no focused element. This is a Discord bug.') - await command._invoke_autocomplete(interaction, focused, namespace) - return - - try: - await command._invoke_with_namespace(interaction, namespace) - except AppCommandError as e: - interaction.command_failed = True - await command._invoke_error_handlers(interaction, e) - await self.on_error(interaction, e) - else: - if not interaction.command_failed: - self.client.dispatch('app_command_completion', interaction, command) diff --git a/.venv/Lib/site-packages/discord/appinfo.py b/.venv/Lib/site-packages/discord/appinfo.py deleted file mode 100644 index 98c2cd3..0000000 --- a/.venv/Lib/site-packages/discord/appinfo.py +++ /dev/null @@ -1,315 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations - -from typing import List, TYPE_CHECKING, Optional - -from . import utils -from .asset import Asset -from .flags import ApplicationFlags -from .permissions import Permissions - -if TYPE_CHECKING: - from .guild import Guild - from .types.appinfo import ( - AppInfo as AppInfoPayload, - PartialAppInfo as PartialAppInfoPayload, - Team as TeamPayload, - InstallParams as InstallParamsPayload, - ) - from .user import User - from .state import ConnectionState - -__all__ = ( - 'AppInfo', - 'PartialAppInfo', - 'AppInstallParams', -) - - -class AppInfo: - """Represents the application info for the bot provided by Discord. - - - Attributes - ------------- - id: :class:`int` - The application ID. - name: :class:`str` - The application name. - owner: :class:`User` - The application owner. - team: Optional[:class:`Team`] - The application's team. - - .. versionadded:: 1.3 - - description: :class:`str` - The application description. - bot_public: :class:`bool` - Whether the bot can be invited by anyone or if it is locked - to the application owner. - bot_require_code_grant: :class:`bool` - Whether the bot requires the completion of the full oauth2 code - grant flow to join. - rpc_origins: Optional[List[:class:`str`]] - A list of RPC origin URLs, if RPC is enabled. - - verify_key: :class:`str` - The hex encoded key for verification in interactions and the - GameSDK's :ddocs:`GetTicket `. - - .. versionadded:: 1.3 - - guild_id: Optional[:class:`int`] - If this application is a game sold on Discord, - this field will be the guild to which it has been linked to. - - .. versionadded:: 1.3 - - primary_sku_id: Optional[:class:`int`] - If this application is a game sold on Discord, - this field will be the id of the "Game SKU" that is created, - if it exists. - - .. versionadded:: 1.3 - - slug: Optional[:class:`str`] - If this application is a game sold on Discord, - this field will be the URL slug that links to the store page. - - .. versionadded:: 1.3 - - terms_of_service_url: Optional[:class:`str`] - The application's terms of service URL, if set. - - .. versionadded:: 2.0 - - privacy_policy_url: Optional[:class:`str`] - The application's privacy policy URL, if set. - - .. versionadded:: 2.0 - - tags: List[:class:`str`] - The list of tags describing the functionality of the application. - - .. versionadded:: 2.0 - - custom_install_url: List[:class:`str`] - The custom authorization URL for the application, if enabled. - - .. versionadded:: 2.0 - - install_params: Optional[:class:`AppInstallParams`] - The settings for custom authorization URL of application, if enabled. - - .. versionadded:: 2.0 - """ - - __slots__ = ( - '_state', - 'description', - 'id', - 'name', - 'rpc_origins', - 'bot_public', - 'bot_require_code_grant', - 'owner', - '_icon', - 'verify_key', - 'team', - 'guild_id', - 'primary_sku_id', - 'slug', - '_cover_image', - '_flags', - 'terms_of_service_url', - 'privacy_policy_url', - 'tags', - 'custom_install_url', - 'install_params', - ) - - def __init__(self, state: ConnectionState, data: AppInfoPayload): - from .team import Team - - self._state: ConnectionState = state - self.id: int = int(data['id']) - self.name: str = data['name'] - self.description: str = data['description'] - self._icon: Optional[str] = data['icon'] - self.rpc_origins: List[str] = data['rpc_origins'] - self.bot_public: bool = data['bot_public'] - self.bot_require_code_grant: bool = data['bot_require_code_grant'] - self.owner: User = state.create_user(data['owner']) - - team: Optional[TeamPayload] = data.get('team') - self.team: Optional[Team] = Team(state, team) if team else None - - self.verify_key: str = data['verify_key'] - - self.guild_id: Optional[int] = utils._get_as_snowflake(data, 'guild_id') - - self.primary_sku_id: Optional[int] = utils._get_as_snowflake(data, 'primary_sku_id') - self.slug: Optional[str] = data.get('slug') - self._flags: int = data.get('flags', 0) - self._cover_image: Optional[str] = data.get('cover_image') - self.terms_of_service_url: Optional[str] = data.get('terms_of_service_url') - self.privacy_policy_url: Optional[str] = data.get('privacy_policy_url') - self.tags: List[str] = data.get('tags', []) - self.custom_install_url: Optional[str] = data.get('custom_install_url') - - params = data.get('install_params') - self.install_params: Optional[AppInstallParams] = AppInstallParams(params) if params else None - - def __repr__(self) -> str: - return ( - f'<{self.__class__.__name__} id={self.id} name={self.name!r} ' - f'description={self.description!r} public={self.bot_public} ' - f'owner={self.owner!r}>' - ) - - @property - def icon(self) -> Optional[Asset]: - """Optional[:class:`.Asset`]: Retrieves the application's icon asset, if any.""" - if self._icon is None: - return None - return Asset._from_icon(self._state, self.id, self._icon, path='app') - - @property - def cover_image(self) -> Optional[Asset]: - """Optional[:class:`.Asset`]: Retrieves the cover image on a store embed, if any. - - This is only available if the application is a game sold on Discord. - """ - if self._cover_image is None: - return None - return Asset._from_cover_image(self._state, self.id, self._cover_image) - - @property - def guild(self) -> Optional[Guild]: - """Optional[:class:`Guild`]: If this application is a game sold on Discord, - this field will be the guild to which it has been linked - - .. versionadded:: 1.3 - """ - return self._state._get_guild(self.guild_id) - - @property - def flags(self) -> ApplicationFlags: - """:class:`ApplicationFlags`: The application's flags. - - .. versionadded:: 2.0 - """ - return ApplicationFlags._from_value(self._flags) - - -class PartialAppInfo: - """Represents a partial AppInfo given by :func:`~discord.abc.GuildChannel.create_invite` - - .. versionadded:: 2.0 - - Attributes - ------------- - id: :class:`int` - The application ID. - name: :class:`str` - The application name. - description: :class:`str` - The application description. - rpc_origins: Optional[List[:class:`str`]] - A list of RPC origin URLs, if RPC is enabled. - verify_key: :class:`str` - The hex encoded key for verification in interactions and the - GameSDK's :ddocs:`GetTicket `. - terms_of_service_url: Optional[:class:`str`] - The application's terms of service URL, if set. - privacy_policy_url: Optional[:class:`str`] - The application's privacy policy URL, if set. - """ - - __slots__ = ( - '_state', - 'id', - 'name', - 'description', - 'rpc_origins', - 'verify_key', - 'terms_of_service_url', - 'privacy_policy_url', - '_icon', - '_flags', - ) - - def __init__(self, *, state: ConnectionState, data: PartialAppInfoPayload): - self._state: ConnectionState = state - self.id: int = int(data['id']) - self.name: str = data['name'] - self._icon: Optional[str] = data.get('icon') - self._flags: int = data.get('flags', 0) - self.description: str = data['description'] - self.rpc_origins: Optional[List[str]] = data.get('rpc_origins') - self.verify_key: str = data['verify_key'] - self.terms_of_service_url: Optional[str] = data.get('terms_of_service_url') - self.privacy_policy_url: Optional[str] = data.get('privacy_policy_url') - - def __repr__(self) -> str: - return f'<{self.__class__.__name__} id={self.id} name={self.name!r} description={self.description!r}>' - - @property - def icon(self) -> Optional[Asset]: - """Optional[:class:`.Asset`]: Retrieves the application's icon asset, if any.""" - if self._icon is None: - return None - return Asset._from_icon(self._state, self.id, self._icon, path='app') - - @property - def flags(self) -> ApplicationFlags: - """:class:`ApplicationFlags`: The application's flags. - - .. versionadded:: 2.0 - """ - return ApplicationFlags._from_value(self._flags) - - -class AppInstallParams: - """Represents the settings for custom authorization URL of an application. - - .. versionadded:: 2.0 - - Attributes - ---------- - scopes: List[:class:`str`] - The list of :ddocs:`OAuth2 scopes ` - to add the application to a guild with. - permissions: :class:`Permissions` - The permissions to give to application in the guild. - """ - - __slots__ = ('scopes', 'permissions') - - def __init__(self, data: InstallParamsPayload) -> None: - self.scopes: List[str] = data.get('scopes', []) - self.permissions: Permissions = Permissions(int(data['permissions'])) diff --git a/.venv/Lib/site-packages/discord/asset.py b/.venv/Lib/site-packages/discord/asset.py deleted file mode 100644 index d88ebb9..0000000 --- a/.venv/Lib/site-packages/discord/asset.py +++ /dev/null @@ -1,516 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations - -import io -import os -from typing import Any, Literal, Optional, TYPE_CHECKING, Tuple, Union -from .errors import DiscordException -from . import utils -from .file import File - -import yarl - -# fmt: off -__all__ = ( - 'Asset', -) -# fmt: on - -if TYPE_CHECKING: - from typing_extensions import Self - - from .state import ConnectionState - from .webhook.async_ import _WebhookState - - _State = Union[ConnectionState, _WebhookState] - - ValidStaticFormatTypes = Literal['webp', 'jpeg', 'jpg', 'png'] - ValidAssetFormatTypes = Literal['webp', 'jpeg', 'jpg', 'png', 'gif'] - -VALID_STATIC_FORMATS = frozenset({"jpeg", "jpg", "webp", "png"}) -VALID_ASSET_FORMATS = VALID_STATIC_FORMATS | {"gif"} - - -MISSING = utils.MISSING - - -class AssetMixin: - __slots__ = () - url: str - _state: Optional[Any] - - async def read(self) -> bytes: - """|coro| - - Retrieves the content of this asset as a :class:`bytes` object. - - Raises - ------ - DiscordException - There was no internal connection state. - HTTPException - Downloading the asset failed. - NotFound - The asset was deleted. - - Returns - ------- - :class:`bytes` - The content of the asset. - """ - if self._state is None: - raise DiscordException('Invalid state (no ConnectionState provided)') - - return await self._state.http.get_from_cdn(self.url) - - async def save(self, fp: Union[str, bytes, os.PathLike[Any], io.BufferedIOBase], *, seek_begin: bool = True) -> int: - """|coro| - - Saves this asset into a file-like object. - - Parameters - ---------- - fp: Union[:class:`io.BufferedIOBase`, :class:`os.PathLike`] - The file-like object to save this asset to or the filename - to use. If a filename is passed then a file is created with that - filename and used instead. - seek_begin: :class:`bool` - Whether to seek to the beginning of the file after saving is - successfully done. - - Raises - ------ - DiscordException - There was no internal connection state. - HTTPException - Downloading the asset failed. - NotFound - The asset was deleted. - - Returns - -------- - :class:`int` - The number of bytes written. - """ - - data = await self.read() - if isinstance(fp, io.BufferedIOBase): - written = fp.write(data) - if seek_begin: - fp.seek(0) - return written - else: - with open(fp, 'wb') as f: - return f.write(data) - - async def to_file( - self, - *, - filename: Optional[str] = MISSING, - description: Optional[str] = None, - spoiler: bool = False, - ) -> File: - """|coro| - - Converts the asset into a :class:`File` suitable for sending via - :meth:`abc.Messageable.send`. - - .. versionadded:: 2.0 - - Parameters - ----------- - filename: Optional[:class:`str`] - The filename of the file. If not provided, then the filename from - the asset's URL is used. - description: Optional[:class:`str`] - The description for the file. - spoiler: :class:`bool` - Whether the file is a spoiler. - - Raises - ------ - DiscordException - The asset does not have an associated state. - ValueError - The asset is a unicode emoji. - TypeError - The asset is a sticker with lottie type. - HTTPException - Downloading the asset failed. - NotFound - The asset was deleted. - - Returns - ------- - :class:`File` - The asset as a file suitable for sending. - """ - - data = await self.read() - file_filename = filename if filename is not MISSING else yarl.URL(self.url).name - return File(io.BytesIO(data), filename=file_filename, description=description, spoiler=spoiler) - - -class Asset(AssetMixin): - """Represents a CDN asset on Discord. - - .. container:: operations - - .. describe:: str(x) - - Returns the URL of the CDN asset. - - .. describe:: len(x) - - Returns the length of the CDN asset's URL. - - .. describe:: x == y - - Checks if the asset is equal to another asset. - - .. describe:: x != y - - Checks if the asset is not equal to another asset. - - .. describe:: hash(x) - - Returns the hash of the asset. - """ - - __slots__: Tuple[str, ...] = ( - '_state', - '_url', - '_animated', - '_key', - ) - - BASE = 'https://cdn.discordapp.com' - - def __init__(self, state: _State, *, url: str, key: str, animated: bool = False) -> None: - self._state: _State = state - self._url: str = url - self._animated: bool = animated - self._key: str = key - - @classmethod - def _from_default_avatar(cls, state: _State, index: int) -> Self: - return cls( - state, - url=f'{cls.BASE}/embed/avatars/{index}.png', - key=str(index), - animated=False, - ) - - @classmethod - def _from_avatar(cls, state: _State, user_id: int, avatar: str) -> Self: - animated = avatar.startswith('a_') - format = 'gif' if animated else 'png' - return cls( - state, - url=f'{cls.BASE}/avatars/{user_id}/{avatar}.{format}?size=1024', - key=avatar, - animated=animated, - ) - - @classmethod - def _from_guild_avatar(cls, state: _State, guild_id: int, member_id: int, avatar: str) -> Self: - animated = avatar.startswith('a_') - format = 'gif' if animated else 'png' - return cls( - state, - url=f"{cls.BASE}/guilds/{guild_id}/users/{member_id}/avatars/{avatar}.{format}?size=1024", - key=avatar, - animated=animated, - ) - - @classmethod - def _from_icon(cls, state: _State, object_id: int, icon_hash: str, path: str) -> Self: - return cls( - state, - url=f'{cls.BASE}/{path}-icons/{object_id}/{icon_hash}.png?size=1024', - key=icon_hash, - animated=False, - ) - - @classmethod - def _from_app_icon( - cls, state: _State, object_id: int, icon_hash: str, asset_type: Literal['icon', 'cover_image'] - ) -> Self: - return cls( - state, - url=f'{cls.BASE}/app-icons/{object_id}/{asset_type}.png?size=1024', - key=icon_hash, - animated=False, - ) - - @classmethod - def _from_cover_image(cls, state: _State, object_id: int, cover_image_hash: str) -> Self: - return cls( - state, - url=f'{cls.BASE}/app-assets/{object_id}/store/{cover_image_hash}.png?size=1024', - key=cover_image_hash, - animated=False, - ) - - @classmethod - def _from_scheduled_event_cover_image(cls, state: _State, scheduled_event_id: int, cover_image_hash: str) -> Self: - return cls( - state, - url=f'{cls.BASE}/guild-events/{scheduled_event_id}/{cover_image_hash}.png?size=1024', - key=cover_image_hash, - animated=False, - ) - - @classmethod - def _from_guild_image(cls, state: _State, guild_id: int, image: str, path: str) -> Self: - animated = image.startswith('a_') - format = 'gif' if animated else 'png' - return cls( - state, - url=f'{cls.BASE}/{path}/{guild_id}/{image}.{format}?size=1024', - key=image, - animated=animated, - ) - - @classmethod - def _from_guild_icon(cls, state: _State, guild_id: int, icon_hash: str) -> Self: - animated = icon_hash.startswith('a_') - format = 'gif' if animated else 'png' - return cls( - state, - url=f'{cls.BASE}/icons/{guild_id}/{icon_hash}.{format}?size=1024', - key=icon_hash, - animated=animated, - ) - - @classmethod - def _from_sticker_banner(cls, state: _State, banner: int) -> Self: - return cls( - state, - url=f'{cls.BASE}/app-assets/710982414301790216/store/{banner}.png', - key=str(banner), - animated=False, - ) - - @classmethod - def _from_user_banner(cls, state: _State, user_id: int, banner_hash: str) -> Self: - animated = banner_hash.startswith('a_') - format = 'gif' if animated else 'png' - return cls( - state, - url=f'{cls.BASE}/banners/{user_id}/{banner_hash}.{format}?size=512', - key=banner_hash, - animated=animated, - ) - - def __str__(self) -> str: - return self._url - - def __len__(self) -> int: - return len(self._url) - - def __repr__(self) -> str: - shorten = self._url.replace(self.BASE, '') - return f'' - - def __eq__(self, other: object) -> bool: - return isinstance(other, Asset) and self._url == other._url - - def __hash__(self) -> int: - return hash(self._url) - - @property - def url(self) -> str: - """:class:`str`: Returns the underlying URL of the asset.""" - return self._url - - @property - def key(self) -> str: - """:class:`str`: Returns the identifying key of the asset.""" - return self._key - - def is_animated(self) -> bool: - """:class:`bool`: Returns whether the asset is animated.""" - return self._animated - - def replace( - self, - *, - size: int = MISSING, - format: ValidAssetFormatTypes = MISSING, - static_format: ValidStaticFormatTypes = MISSING, - ) -> Self: - """Returns a new asset with the passed components replaced. - - - .. versionchanged:: 2.0 - ``static_format`` is now preferred over ``format`` - if both are present and the asset is not animated. - - .. versionchanged:: 2.0 - This function will now raise :exc:`ValueError` instead of - ``InvalidArgument``. - - Parameters - ----------- - size: :class:`int` - The new size of the asset. - format: :class:`str` - The new format to change it to. Must be either - 'webp', 'jpeg', 'jpg', 'png', or 'gif' if it's animated. - static_format: :class:`str` - The new format to change it to if the asset isn't animated. - Must be either 'webp', 'jpeg', 'jpg', or 'png'. - - Raises - ------- - ValueError - An invalid size or format was passed. - - Returns - -------- - :class:`Asset` - The newly updated asset. - """ - url = yarl.URL(self._url) - path, _ = os.path.splitext(url.path) - - if format is not MISSING: - if self._animated: - if format not in VALID_ASSET_FORMATS: - raise ValueError(f'format must be one of {VALID_ASSET_FORMATS}') - else: - if static_format is MISSING and format not in VALID_STATIC_FORMATS: - raise ValueError(f'format must be one of {VALID_STATIC_FORMATS}') - url = url.with_path(f'{path}.{format}') - - if static_format is not MISSING and not self._animated: - if static_format not in VALID_STATIC_FORMATS: - raise ValueError(f'static_format must be one of {VALID_STATIC_FORMATS}') - url = url.with_path(f'{path}.{static_format}') - - if size is not MISSING: - if not utils.valid_icon_size(size): - raise ValueError('size must be a power of 2 between 16 and 4096') - url = url.with_query(size=size) - else: - url = url.with_query(url.raw_query_string) - - url = str(url) - return Asset(state=self._state, url=url, key=self._key, animated=self._animated) - - def with_size(self, size: int, /) -> Self: - """Returns a new asset with the specified size. - - .. versionchanged:: 2.0 - This function will now raise :exc:`ValueError` instead of - ``InvalidArgument``. - - Parameters - ------------ - size: :class:`int` - The new size of the asset. - - Raises - ------- - ValueError - The asset had an invalid size. - - Returns - -------- - :class:`Asset` - The new updated asset. - """ - if not utils.valid_icon_size(size): - raise ValueError('size must be a power of 2 between 16 and 4096') - - url = str(yarl.URL(self._url).with_query(size=size)) - return Asset(state=self._state, url=url, key=self._key, animated=self._animated) - - def with_format(self, format: ValidAssetFormatTypes, /) -> Self: - """Returns a new asset with the specified format. - - .. versionchanged:: 2.0 - This function will now raise :exc:`ValueError` instead of - ``InvalidArgument``. - - Parameters - ------------ - format: :class:`str` - The new format of the asset. - - Raises - ------- - ValueError - The asset had an invalid format. - - Returns - -------- - :class:`Asset` - The new updated asset. - """ - - if self._animated: - if format not in VALID_ASSET_FORMATS: - raise ValueError(f'format must be one of {VALID_ASSET_FORMATS}') - else: - if format not in VALID_STATIC_FORMATS: - raise ValueError(f'format must be one of {VALID_STATIC_FORMATS}') - - url = yarl.URL(self._url) - path, _ = os.path.splitext(url.path) - url = str(url.with_path(f'{path}.{format}').with_query(url.raw_query_string)) - return Asset(state=self._state, url=url, key=self._key, animated=self._animated) - - def with_static_format(self, format: ValidStaticFormatTypes, /) -> Self: - """Returns a new asset with the specified static format. - - This only changes the format if the underlying asset is - not animated. Otherwise, the asset is not changed. - - .. versionchanged:: 2.0 - This function will now raise :exc:`ValueError` instead of - ``InvalidArgument``. - - Parameters - ------------ - format: :class:`str` - The new static format of the asset. - - Raises - ------- - ValueError - The asset had an invalid format. - - Returns - -------- - :class:`Asset` - The new updated asset. - """ - - if self._animated: - return self - return self.with_format(format) diff --git a/.venv/Lib/site-packages/discord/audit_logs.py b/.venv/Lib/site-packages/discord/audit_logs.py deleted file mode 100644 index 4d51de6..0000000 --- a/.venv/Lib/site-packages/discord/audit_logs.py +++ /dev/null @@ -1,774 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations - -from typing import TYPE_CHECKING, Any, Callable, ClassVar, Dict, Generator, List, Optional, Tuple, Type, TypeVar, Union - -from . import enums, flags, utils -from .asset import Asset -from .colour import Colour -from .invite import Invite -from .mixins import Hashable -from .object import Object -from .permissions import PermissionOverwrite, Permissions -from .automod import AutoModTrigger, AutoModRuleAction, AutoModPresets, AutoModRule -from .role import Role -from .emoji import Emoji -from .member import Member -from .scheduled_event import ScheduledEvent -from .stage_instance import StageInstance -from .sticker import GuildSticker -from .threads import Thread -from .integrations import PartialIntegration -from .channel import StageChannel - -__all__ = ( - 'AuditLogDiff', - 'AuditLogChanges', - 'AuditLogEntry', -) - - -if TYPE_CHECKING: - import datetime - - from . import abc - from .guild import Guild - from .state import ConnectionState - from .types.audit_log import ( - AuditLogChange as AuditLogChangePayload, - AuditLogEntry as AuditLogEntryPayload, - ) - from .types.channel import ( - PermissionOverwrite as PermissionOverwritePayload, - ) - from .types.invite import Invite as InvitePayload - from .types.role import Role as RolePayload - from .types.snowflake import Snowflake - from .types.command import ApplicationCommandPermissions - from .types.automod import AutoModerationTriggerMetadata, AutoModerationAction - from .user import User - from .app_commands import AppCommand - - TargetType = Union[ - Guild, - abc.GuildChannel, - Member, - User, - Role, - Invite, - Emoji, - StageInstance, - GuildSticker, - Thread, - Object, - PartialIntegration, - AutoModRule, - None, - ] - - -def _transform_timestamp(entry: AuditLogEntry, data: Optional[str]) -> Optional[datetime.datetime]: - return utils.parse_time(data) - - -def _transform_color(entry: AuditLogEntry, data: int) -> Colour: - return Colour(data) - - -def _transform_snowflake(entry: AuditLogEntry, data: Snowflake) -> int: - return int(data) - - -def _transform_channel(entry: AuditLogEntry, data: Optional[Snowflake]) -> Optional[Union[abc.GuildChannel, Object]]: - if data is None: - return None - return entry.guild.get_channel(int(data)) or Object(id=data) - - -def _transform_channels_or_threads( - entry: AuditLogEntry, data: List[Snowflake] -) -> List[Union[abc.GuildChannel, Thread, Object]]: - return [entry.guild.get_channel_or_thread(int(data)) or Object(id=data) for data in data] - - -def _transform_member_id(entry: AuditLogEntry, data: Optional[Snowflake]) -> Union[Member, User, None]: - if data is None: - return None - return entry._get_member(int(data)) - - -def _transform_guild_id(entry: AuditLogEntry, data: Optional[Snowflake]) -> Optional[Guild]: - if data is None: - return None - return entry._state._get_guild(int(data)) - - -def _transform_roles(entry: AuditLogEntry, data: List[Snowflake]) -> List[Union[Role, Object]]: - return [entry.guild.get_role(int(role_id)) or Object(role_id, type=Role) for role_id in data] - - -def _transform_overwrites( - entry: AuditLogEntry, data: List[PermissionOverwritePayload] -) -> List[Tuple[Object, PermissionOverwrite]]: - overwrites = [] - for elem in data: - allow = Permissions(int(elem['allow'])) - deny = Permissions(int(elem['deny'])) - ow = PermissionOverwrite.from_pair(allow, deny) - - ow_type = elem['type'] - ow_id = int(elem['id']) - target = None - if ow_type == '0': - target = entry.guild.get_role(ow_id) - elif ow_type == '1': - target = entry._get_member(ow_id) - - if target is None: - target = Object(id=ow_id, type=Role if ow_type == '0' else Member) - - overwrites.append((target, ow)) - - return overwrites - - -def _transform_icon(entry: AuditLogEntry, data: Optional[str]) -> Optional[Asset]: - if data is None: - return None - if entry.action is enums.AuditLogAction.guild_update: - return Asset._from_guild_icon(entry._state, entry.guild.id, data) - else: - return Asset._from_icon(entry._state, entry._target_id, data, path='role') # type: ignore # target_id won't be None in this case - - -def _transform_avatar(entry: AuditLogEntry, data: Optional[str]) -> Optional[Asset]: - if data is None: - return None - return Asset._from_avatar(entry._state, entry._target_id, data) # type: ignore # target_id won't be None in this case - - -def _transform_cover_image(entry: AuditLogEntry, data: Optional[str]) -> Optional[Asset]: - if data is None: - return None - return Asset._from_scheduled_event_cover_image(entry._state, entry._target_id, data) # type: ignore # target_id won't be None in this case - - -def _guild_hash_transformer(path: str) -> Callable[[AuditLogEntry, Optional[str]], Optional[Asset]]: - def _transform(entry: AuditLogEntry, data: Optional[str]) -> Optional[Asset]: - if data is None: - return None - return Asset._from_guild_image(entry._state, entry.guild.id, data, path=path) - - return _transform - - -def _transform_automod_trigger_metadata( - entry: AuditLogEntry, data: AutoModerationTriggerMetadata -) -> Optional[AutoModTrigger]: - - if isinstance(entry.target, AutoModRule): - # Trigger type cannot be changed, so type should be the same before and after updates. - # Avoids checking which keys are in data to guess trigger type - # or returning None if data is empty. - try: - return AutoModTrigger.from_data(type=entry.target.trigger.type.value, data=data) - except Exception: - pass - - # If cannot get trigger type from the rule and data is empty, then cannot determine trigger type - if not data: - return None - - # Try to infer trigger type from available keys in data - if 'presets' in data: - return AutoModTrigger( - type=enums.AutoModRuleTriggerType.keyword_preset, - presets=AutoModPresets._from_value(data['presets']), # type: ignore - allow_list=data.get('allow_list'), - ) - elif 'keyword_filter' in data: - return AutoModTrigger(type=enums.AutoModRuleTriggerType.keyword, keyword_filter=data['keyword_filter']) # type: ignore - elif 'mention_total_limit' in data: - return AutoModTrigger(type=enums.AutoModRuleTriggerType.mention_spam, mention_limit=data['mention_total_limit']) # type: ignore - - -def _transform_automod_actions(entry: AuditLogEntry, data: List[AutoModerationAction]) -> List[AutoModRuleAction]: - return [AutoModRuleAction.from_data(action) for action in data] - - -E = TypeVar('E', bound=enums.Enum) - - -def _enum_transformer(enum: Type[E]) -> Callable[[AuditLogEntry, int], E]: - def _transform(entry: AuditLogEntry, data: int) -> E: - return enums.try_enum(enum, data) - - return _transform - - -F = TypeVar('F', bound=flags.BaseFlags) - - -def _flag_transformer(cls: Type[F]) -> Callable[[AuditLogEntry, Union[int, str]], F]: - def _transform(entry: AuditLogEntry, data: Union[int, str]) -> F: - return cls._from_value(int(data)) - - return _transform - - -def _transform_type(entry: AuditLogEntry, data: int) -> Union[enums.ChannelType, enums.StickerType]: - if entry.action.name.startswith('sticker_'): - return enums.try_enum(enums.StickerType, data) - else: - return enums.try_enum(enums.ChannelType, data) - - -class AuditLogDiff: - def __len__(self) -> int: - return len(self.__dict__) - - def __iter__(self) -> Generator[Tuple[str, Any], None, None]: - yield from self.__dict__.items() - - def __repr__(self) -> str: - values = ' '.join('%s=%r' % item for item in self.__dict__.items()) - return f'' - - if TYPE_CHECKING: - - def __getattr__(self, item: str) -> Any: - ... - - def __setattr__(self, key: str, value: Any) -> Any: - ... - - -Transformer = Callable[["AuditLogEntry", Any], Any] - - -class AuditLogChanges: - # fmt: off - TRANSFORMERS: ClassVar[Dict[str, Tuple[Optional[str], Optional[Transformer]]]] = { - 'verification_level': (None, _enum_transformer(enums.VerificationLevel)), - 'explicit_content_filter': (None, _enum_transformer(enums.ContentFilter)), - 'allow': (None, _flag_transformer(Permissions)), - 'deny': (None, _flag_transformer(Permissions)), - 'permissions': (None, _flag_transformer(Permissions)), - 'id': (None, _transform_snowflake), - 'color': ('colour', _transform_color), - 'owner_id': ('owner', _transform_member_id), - 'inviter_id': ('inviter', _transform_member_id), - 'channel_id': ('channel', _transform_channel), - 'afk_channel_id': ('afk_channel', _transform_channel), - 'system_channel_id': ('system_channel', _transform_channel), - 'system_channel_flags': (None, _flag_transformer(flags.SystemChannelFlags)), - 'widget_channel_id': ('widget_channel', _transform_channel), - 'rules_channel_id': ('rules_channel', _transform_channel), - 'public_updates_channel_id': ('public_updates_channel', _transform_channel), - 'permission_overwrites': ('overwrites', _transform_overwrites), - 'splash_hash': ('splash', _guild_hash_transformer('splashes')), - 'banner_hash': ('banner', _guild_hash_transformer('banners')), - 'discovery_splash_hash': ('discovery_splash', _guild_hash_transformer('discovery-splashes')), - 'icon_hash': ('icon', _transform_icon), - 'avatar_hash': ('avatar', _transform_avatar), - 'rate_limit_per_user': ('slowmode_delay', None), - 'guild_id': ('guild', _transform_guild_id), - 'tags': ('emoji', None), - 'default_message_notifications': ('default_notifications', _enum_transformer(enums.NotificationLevel)), - 'video_quality_mode': (None, _enum_transformer(enums.VideoQualityMode)), - 'privacy_level': (None, _enum_transformer(enums.PrivacyLevel)), - 'format_type': (None, _enum_transformer(enums.StickerFormatType)), - 'type': (None, _transform_type), - 'communication_disabled_until': ('timed_out_until', _transform_timestamp), - 'expire_behavior': (None, _enum_transformer(enums.ExpireBehaviour)), - 'mfa_level': (None, _enum_transformer(enums.MFALevel)), - 'status': (None, _enum_transformer(enums.EventStatus)), - 'entity_type': (None, _enum_transformer(enums.EntityType)), - 'preferred_locale': (None, _enum_transformer(enums.Locale)), - 'image_hash': ('cover_image', _transform_cover_image), - 'trigger_type': (None, _enum_transformer(enums.AutoModRuleTriggerType)), - 'event_type': (None, _enum_transformer(enums.AutoModRuleEventType)), - 'trigger_metadata': ('trigger', _transform_automod_trigger_metadata), - 'actions': (None, _transform_automod_actions), - 'exempt_channels': (None, _transform_channels_or_threads), - 'exempt_roles': (None, _transform_roles), - } - # fmt: on - - def __init__(self, entry: AuditLogEntry, data: List[AuditLogChangePayload]): - self.before: AuditLogDiff = AuditLogDiff() - self.after: AuditLogDiff = AuditLogDiff() - # special case entire process since each - # element in data is a different target - # key is the target id - if entry.action is enums.AuditLogAction.app_command_permission_update: - self.before.app_command_permissions = [] - self.after.app_command_permissions = [] - - for elem in data: - self._handle_app_command_permissions( - self.before, - entry, - elem.get('old_value'), # type: ignore # value will be an ApplicationCommandPermissions if present - ) - - self._handle_app_command_permissions( - self.after, - entry, - elem.get('new_value'), # type: ignore # value will be an ApplicationCommandPermissions if present - ) - return - - for elem in data: - attr = elem['key'] - - # special cases for role add/remove - if attr == '$add': - self._handle_role(self.before, self.after, entry, elem['new_value']) # type: ignore # new_value is a list of roles in this case - continue - elif attr == '$remove': - self._handle_role(self.after, self.before, entry, elem['new_value']) # type: ignore # new_value is a list of roles in this case - continue - - try: - key, transformer = self.TRANSFORMERS[attr] - except (ValueError, KeyError): - transformer = None - else: - if key: - attr = key - - transformer: Optional[Transformer] - - try: - before = elem['old_value'] - except KeyError: - before = None - else: - if transformer: - before = transformer(entry, before) - - setattr(self.before, attr, before) - - try: - after = elem['new_value'] - except KeyError: - after = None - else: - if transformer: - after = transformer(entry, after) - - setattr(self.after, attr, after) - - # add an alias - if hasattr(self.after, 'colour'): - self.after.color = self.after.colour - self.before.color = self.before.colour - if hasattr(self.after, 'expire_behavior'): - self.after.expire_behaviour = self.after.expire_behavior - self.before.expire_behaviour = self.before.expire_behavior - - def __repr__(self) -> str: - return f'' - - def _handle_role(self, first: AuditLogDiff, second: AuditLogDiff, entry: AuditLogEntry, elem: List[RolePayload]) -> None: - if not hasattr(first, 'roles'): - setattr(first, 'roles', []) - - data = [] - g: Guild = entry.guild - - for e in elem: - role_id = int(e['id']) - role = g.get_role(role_id) - - if role is None: - role = Object(id=role_id, type=Role) - role.name = e['name'] # type: ignore # Object doesn't usually have name - - data.append(role) - - setattr(second, 'roles', data) - - def _handle_app_command_permissions( - self, - diff: AuditLogDiff, - entry: AuditLogEntry, - data: Optional[ApplicationCommandPermissions], - ): - if data is None: - return - - # avoid circular import - from discord.app_commands import AppCommandPermissions - - state = entry._state - guild = entry.guild - diff.app_command_permissions.append(AppCommandPermissions(data=data, guild=guild, state=state)) - - -class _AuditLogProxy: - def __init__(self, **kwargs: Any) -> None: - for k, v in kwargs.items(): - setattr(self, k, v) - - -class _AuditLogProxyMemberPrune(_AuditLogProxy): - delete_member_days: int - members_removed: int - - -class _AuditLogProxyMemberMoveOrMessageDelete(_AuditLogProxy): - channel: Union[abc.GuildChannel, Thread] - count: int - - -class _AuditLogProxyMemberDisconnect(_AuditLogProxy): - count: int - - -class _AuditLogProxyPinAction(_AuditLogProxy): - channel: Union[abc.GuildChannel, Thread] - message_id: int - - -class _AuditLogProxyStageInstanceAction(_AuditLogProxy): - channel: abc.GuildChannel - - -class _AuditLogProxyMessageBulkDelete(_AuditLogProxy): - count: int - - -class _AuditLogProxyAutoModAction(_AuditLogProxy): - automod_rule_name: str - automod_rule_trigger_type: str - channel: Union[abc.GuildChannel, Thread] - - -class AuditLogEntry(Hashable): - r"""Represents an Audit Log entry. - - You retrieve these via :meth:`Guild.audit_logs`. - - .. container:: operations - - .. describe:: x == y - - Checks if two entries are equal. - - .. describe:: x != y - - Checks if two entries are not equal. - - .. describe:: hash(x) - - Returns the entry's hash. - - .. versionchanged:: 1.7 - Audit log entries are now comparable and hashable. - - Attributes - ----------- - action: :class:`AuditLogAction` - The action that was done. - user: :class:`abc.User` - The user who initiated this action. Usually a :class:`Member`\, unless gone - then it's a :class:`User`. - id: :class:`int` - The entry ID. - target: Any - The target that got changed. The exact type of this depends on - the action being done. - reason: Optional[:class:`str`] - The reason this action was done. - extra: Any - Extra information that this entry has that might be useful. - For most actions, this is ``None``. However in some cases it - contains extra information. See :class:`AuditLogAction` for - which actions have this field filled out. - """ - - def __init__( - self, - *, - users: Dict[int, User], - integrations: Dict[int, PartialIntegration], - app_commands: Dict[int, AppCommand], - automod_rules: Dict[int, AutoModRule], - data: AuditLogEntryPayload, - guild: Guild, - ): - self._state: ConnectionState = guild._state - self.guild: Guild = guild - self._users: Dict[int, User] = users - self._integrations: Dict[int, PartialIntegration] = integrations - self._app_commands: Dict[int, AppCommand] = app_commands - self._automod_rules: Dict[int, AutoModRule] = automod_rules - self._from_data(data) - - def _from_data(self, data: AuditLogEntryPayload) -> None: - self.action: enums.AuditLogAction = enums.try_enum(enums.AuditLogAction, data['action_type']) - self.id: int = int(data['id']) - - # this key is technically not usually present - self.reason: Optional[str] = data.get('reason') - extra = data.get('options') - - # fmt: off - self.extra: Union[ - _AuditLogProxyMemberPrune, - _AuditLogProxyMemberMoveOrMessageDelete, - _AuditLogProxyMemberDisconnect, - _AuditLogProxyPinAction, - _AuditLogProxyStageInstanceAction, - _AuditLogProxyMessageBulkDelete, - _AuditLogProxyAutoModAction, - Member, User, None, PartialIntegration, - Role, Object - ] = None - # fmt: on - - if isinstance(self.action, enums.AuditLogAction) and extra: - if self.action is enums.AuditLogAction.member_prune: - # member prune has two keys with useful information - self.extra = _AuditLogProxyMemberPrune( - delete_member_days=int(extra['delete_member_days']), - members_removed=int(extra['members_removed']), - ) - elif self.action is enums.AuditLogAction.member_move or self.action is enums.AuditLogAction.message_delete: - channel_id = int(extra['channel_id']) - self.extra = _AuditLogProxyMemberMoveOrMessageDelete( - count=int(extra['count']), - channel=self.guild.get_channel_or_thread(channel_id) or Object(id=channel_id), - ) - elif self.action is enums.AuditLogAction.member_disconnect: - # The member disconnect action has a dict with some information - self.extra = _AuditLogProxyMemberDisconnect(count=int(extra['count'])) - elif self.action is enums.AuditLogAction.message_bulk_delete: - # The bulk message delete action has the number of messages deleted - self.extra = _AuditLogProxyMessageBulkDelete(count=int(extra['count'])) - elif self.action.name.endswith('pin'): - # the pin actions have a dict with some information - channel_id = int(extra['channel_id']) - self.extra = _AuditLogProxyPinAction( - channel=self.guild.get_channel_or_thread(channel_id) or Object(id=channel_id), - message_id=int(extra['message_id']), - ) - elif self.action is enums.AuditLogAction.automod_block_message: - channel_id = int(extra['channel_id']) - self.extra = _AuditLogProxyAutoModAction( - automod_rule_name=extra['auto_moderation_rule_name'], - automod_rule_trigger_type=enums.try_enum( - enums.AutoModRuleTriggerType, extra['auto_moderation_rule_trigger_type'] - ), - channel=self.guild.get_channel_or_thread(channel_id) or Object(id=channel_id), - ) - - elif self.action.name.startswith('overwrite_'): - # the overwrite_ actions have a dict with some information - instance_id = int(extra['id']) - the_type = extra.get('type') - if the_type == '1': - self.extra = self._get_member(instance_id) - elif the_type == '0': - role = self.guild.get_role(instance_id) - if role is None: - role = Object(id=instance_id, type=Role) - role.name = extra.get('role_name') # type: ignore # Object doesn't usually have name - self.extra = role - elif self.action.name.startswith('stage_instance'): - channel_id = int(extra['channel_id']) - self.extra = _AuditLogProxyStageInstanceAction( - channel=self.guild.get_channel(channel_id) or Object(id=channel_id, type=StageChannel) - ) - elif self.action.name.startswith('app_command'): - app_id = int(extra['application_id']) - self.extra = self._get_integration_by_app_id(app_id) or Object(app_id, type=PartialIntegration) - - # this key is not present when the above is present, typically. - # It's a list of { new_value: a, old_value: b, key: c } - # where new_value and old_value are not guaranteed to be there depending - # on the action type, so let's just fetch it for now and only turn it - # into meaningful data when requested - self._changes = data.get('changes', []) - - user_id = utils._get_as_snowflake(data, 'user_id') - self.user: Optional[Union[User, Member]] = self._get_member(user_id) - self._target_id = utils._get_as_snowflake(data, 'target_id') - - def _get_member(self, user_id: Optional[int]) -> Union[Member, User, None]: - if user_id is None: - return None - - return self.guild.get_member(user_id) or self._users.get(user_id) - - def _get_integration(self, integration_id: Optional[int]) -> Optional[PartialIntegration]: - if integration_id is None: - return None - - return self._integrations.get(integration_id) - - def _get_integration_by_app_id(self, application_id: Optional[int]) -> Optional[PartialIntegration]: - if application_id is None: - return None - - # get PartialIntegration by application id - return utils.get(self._integrations.values(), application_id=application_id) - - def _get_app_command(self, app_command_id: Optional[int]) -> Optional[AppCommand]: - if app_command_id is None: - return None - - return self._app_commands.get(app_command_id) - - def __repr__(self) -> str: - return f'' - - @utils.cached_property - def created_at(self) -> datetime.datetime: - """:class:`datetime.datetime`: Returns the entry's creation time in UTC.""" - return utils.snowflake_time(self.id) - - @utils.cached_property - def target(self) -> TargetType: - if self.action.target_type is None: - return None - - try: - converter = getattr(self, '_convert_target_' + self.action.target_type) - except AttributeError: - if self._target_id is None: - return None - return Object(id=self._target_id) - else: - return converter(self._target_id) - - @utils.cached_property - def category(self) -> Optional[enums.AuditLogActionCategory]: - """Optional[:class:`AuditLogActionCategory`]: The category of the action, if applicable.""" - return self.action.category - - @utils.cached_property - def changes(self) -> AuditLogChanges: - """:class:`AuditLogChanges`: The list of changes this entry has.""" - obj = AuditLogChanges(self, self._changes) - del self._changes - return obj - - @utils.cached_property - def before(self) -> AuditLogDiff: - """:class:`AuditLogDiff`: The target's prior state.""" - return self.changes.before - - @utils.cached_property - def after(self) -> AuditLogDiff: - """:class:`AuditLogDiff`: The target's subsequent state.""" - return self.changes.after - - def _convert_target_guild(self, target_id: int) -> Guild: - return self.guild - - def _convert_target_channel(self, target_id: int) -> Union[abc.GuildChannel, Object]: - return self.guild.get_channel(target_id) or Object(id=target_id) - - def _convert_target_user(self, target_id: int) -> Union[Member, User, None]: - return self._get_member(target_id) - - def _convert_target_role(self, target_id: int) -> Union[Role, Object]: - return self.guild.get_role(target_id) or Object(id=target_id, type=Role) - - def _convert_target_invite(self, target_id: None) -> Invite: - # invites have target_id set to null - # so figure out which change has the full invite data - changeset = self.before if self.action is enums.AuditLogAction.invite_delete else self.after - - fake_payload: InvitePayload = { - 'max_age': changeset.max_age, - 'max_uses': changeset.max_uses, - 'code': changeset.code, - 'temporary': changeset.temporary, - 'uses': changeset.uses, - 'channel': None, # type: ignore # the channel is passed to the Invite constructor directly - } - - obj = Invite(state=self._state, data=fake_payload, guild=self.guild, channel=changeset.channel) - try: - obj.inviter = changeset.inviter - except AttributeError: - pass - return obj - - def _convert_target_emoji(self, target_id: int) -> Union[Emoji, Object]: - return self._state.get_emoji(target_id) or Object(id=target_id, type=Emoji) - - def _convert_target_message(self, target_id: int) -> Union[Member, User, None]: - return self._get_member(target_id) - - def _convert_target_stage_instance(self, target_id: int) -> Union[StageInstance, Object]: - return self.guild.get_stage_instance(target_id) or Object(id=target_id, type=StageInstance) - - def _convert_target_sticker(self, target_id: int) -> Union[GuildSticker, Object]: - return self._state.get_sticker(target_id) or Object(id=target_id, type=GuildSticker) - - def _convert_target_thread(self, target_id: int) -> Union[Thread, Object]: - return self.guild.get_thread(target_id) or Object(id=target_id, type=Thread) - - def _convert_target_guild_scheduled_event(self, target_id: int) -> Union[ScheduledEvent, Object]: - return self.guild.get_scheduled_event(target_id) or Object(id=target_id, type=ScheduledEvent) - - def _convert_target_integration(self, target_id: int) -> Union[PartialIntegration, Object]: - return self._get_integration(target_id) or Object(target_id, type=PartialIntegration) - - def _convert_target_app_command(self, target_id: int) -> Union[AppCommand, Object]: - target = self._get_app_command(target_id) - if not target: - # circular import - from .app_commands import AppCommand - - target = Object(target_id, type=AppCommand) - - return target - - def _convert_target_integration_or_app_command(self, target_id: int) -> Union[PartialIntegration, AppCommand, Object]: - target = self._get_integration_by_app_id(target_id) or self._get_app_command(target_id) - if not target: - try: - # get application id from extras - # if it matches target id, type should be integration - target_app = self.extra - # extra should be an Object or PartialIntegration - app_id = target_app.application_id if isinstance(target_app, PartialIntegration) else target_app.id # type: ignore - type = PartialIntegration if target_id == app_id else AppCommand - except AttributeError: - return Object(target_id) - else: - return Object(target_id, type=type) - - return target - - def _convert_target_auto_moderation(self, target_id: int) -> Union[AutoModRule, Object]: - return self._automod_rules.get(target_id) or Object(target_id, type=AutoModRule) diff --git a/.venv/Lib/site-packages/discord/automod.py b/.venv/Lib/site-packages/discord/automod.py deleted file mode 100644 index 5c40629..0000000 --- a/.venv/Lib/site-packages/discord/automod.py +++ /dev/null @@ -1,540 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations -import datetime - -from typing import TYPE_CHECKING, Any, Dict, Optional, List, Sequence, Set, Union, Sequence - - -from .enums import AutoModRuleTriggerType, AutoModRuleActionType, AutoModRuleEventType, try_enum -from .flags import AutoModPresets -from . import utils -from .utils import MISSING, cached_slot_property - -if TYPE_CHECKING: - from typing_extensions import Self - from .abc import Snowflake, GuildChannel - from .threads import Thread - from .guild import Guild - from .member import Member - from .state import ConnectionState - from .types.automod import ( - AutoModerationRule as AutoModerationRulePayload, - AutoModerationTriggerMetadata as AutoModerationTriggerMetadataPayload, - AutoModerationAction as AutoModerationActionPayload, - AutoModerationActionExecution as AutoModerationActionExecutionPayload, - ) - from .role import Role - -__all__ = ( - 'AutoModRuleAction', - 'AutoModTrigger', - 'AutoModRule', - 'AutoModAction', -) - - -class AutoModRuleAction: - """Represents an auto moderation's rule action. - - .. versionadded:: 2.0 - - Attributes - ----------- - type: :class:`AutoModRuleActionType` - The type of action to take. - Defaults to :attr:`~AutoModRuleActionType.block_message`. - channel_id: Optional[:class:`int`] - The ID of the channel or thread to send the alert message to, if any. - Passing this sets :attr:`type` to :attr:`~AutoModRuleActionType.send_alert_message`. - duration: Optional[:class:`datetime.timedelta`] - The duration of the timeout to apply, if any. - Has a maximum of 28 days. - Passing this sets :attr:`type` to :attr:`~AutoModRuleActionType.timeout`. - """ - - __slots__ = ('type', 'channel_id', 'duration') - - def __init__(self, *, channel_id: Optional[int] = None, duration: Optional[datetime.timedelta] = None) -> None: - self.channel_id: Optional[int] = channel_id - self.duration: Optional[datetime.timedelta] = duration - if channel_id and duration: - raise ValueError('Please provide only one of ``channel`` or ``duration``') - - if channel_id: - self.type = AutoModRuleActionType.send_alert_message - elif duration: - self.type = AutoModRuleActionType.timeout - else: - self.type = AutoModRuleActionType.block_message - - def __repr__(self) -> str: - return f'' - - @classmethod - def from_data(cls, data: AutoModerationActionPayload) -> Self: - type_ = try_enum(AutoModRuleActionType, data['type']) - if data['type'] == AutoModRuleActionType.timeout.value: - duration_seconds = data['metadata']['duration_seconds'] - return cls(duration=datetime.timedelta(seconds=duration_seconds)) - elif data['type'] == AutoModRuleActionType.send_alert_message.value: - channel_id = int(data['metadata']['channel_id']) - return cls(channel_id=channel_id) - return cls() - - def to_dict(self) -> Dict[str, Any]: - ret = {'type': self.type.value, 'metadata': {}} - if self.type is AutoModRuleActionType.timeout: - ret['metadata'] = {'duration_seconds': int(self.duration.total_seconds())} # type: ignore # duration cannot be None here - elif self.type is AutoModRuleActionType.send_alert_message: - ret['metadata'] = {'channel_id': str(self.channel_id)} - return ret - - -class AutoModTrigger: - r"""Represents a trigger for an auto moderation rule. - - The following table illustrates relevant attributes for each :class:`AutoModRuleTriggerType`: - - +-----------------------------------------------+--------------------------------------+ - | Type | Attributes | - +===============================================+======================================+ - | :attr:`AutoModRuleTriggerType.keyword` | :attr:`keyword_filter` | - +-----------------------------------------------+--------------------------------------+ - | :attr:`AutoModRuleTriggerType.spam` | | - +-----------------------------------------------+--------------------------------------+ - | :attr:`AutoModRuleTriggerType.keyword_preset` | :attr:`presets`\, :attr:`allow_list` | - +-----------------------------------------------+--------------------------------------+ - | :attr:`AutoModRuleTriggerType.mention_spam` | :attr:`mention_limit` | - +-----------------------------------------------+--------------------------------------+ - - .. versionadded:: 2.0 - - Attributes - ----------- - type: :class:`AutoModRuleTriggerType` - The type of trigger. - keyword_filter: List[:class:`str`] - The list of strings that will trigger the keyword filter. - presets: :class:`AutoModPresets` - The presets used with the preset keyword filter. - allow_list: List[:class:`str`] - The list of words that are exempt from the commonly flagged words. - mention_limit: :class:`int` - The total number of user and role mentions a message can contain. - Has a maximum of 50. - """ - - __slots__ = ( - 'type', - 'keyword_filter', - 'presets', - 'allow_list', - 'mention_limit', - ) - - def __init__( - self, - *, - type: Optional[AutoModRuleTriggerType] = None, - keyword_filter: Optional[List[str]] = None, - presets: Optional[AutoModPresets] = None, - allow_list: Optional[List[str]] = None, - mention_limit: Optional[int] = None, - ) -> None: - if type is None and sum(arg is not None for arg in (keyword_filter, presets, mention_limit)) > 1: - raise ValueError('Please pass only one of keyword_filter, presets, or mention_limit.') - - if type is not None: - self.type = type - elif keyword_filter is not None: - self.type = AutoModRuleTriggerType.keyword - elif presets is not None: - self.type = AutoModRuleTriggerType.keyword_preset - elif mention_limit is not None: - self.type = AutoModRuleTriggerType.mention_spam - else: - raise ValueError( - 'Please pass the trigger type explicitly if not using keyword_filter, presets, or mention_limit.' - ) - - self.keyword_filter: List[str] = keyword_filter if keyword_filter is not None else [] - self.presets: AutoModPresets = presets if presets is not None else AutoModPresets() - self.allow_list: List[str] = allow_list if allow_list is not None else [] - self.mention_limit: int = mention_limit if mention_limit is not None else 0 - - @classmethod - def from_data(cls, type: int, data: Optional[AutoModerationTriggerMetadataPayload]) -> Self: - type_ = try_enum(AutoModRuleTriggerType, type) - if data is None: - return cls(type=type_) - elif type_ is AutoModRuleTriggerType.keyword: - return cls(type=type_, keyword_filter=data.get('keyword_filter')) - elif type_ is AutoModRuleTriggerType.keyword_preset: - return cls( - type=type_, presets=AutoModPresets._from_value(data.get('presets', [])), allow_list=data.get('allow_list') - ) - elif type_ is AutoModRuleTriggerType.mention_spam: - return cls(type=type_, mention_limit=data.get('mention_total_limit')) - else: - return cls(type=type_) - - def to_metadata_dict(self) -> Optional[Dict[str, Any]]: - if self.type is AutoModRuleTriggerType.keyword: - return {'keyword_filter': self.keyword_filter} - elif self.type is AutoModRuleTriggerType.keyword_preset: - return {'presets': self.presets.to_array(), 'allow_list': self.allow_list} - elif self.type is AutoModRuleTriggerType.mention_spam: - return {'mention_total_limit': self.mention_limit} - - -class AutoModRule: - """Represents an auto moderation rule. - - .. versionadded:: 2.0 - - Attributes - ----------- - id: :class:`int` - The ID of the rule. - guild: :class:`Guild` - The guild the rule is for. - name: :class:`str` - The name of the rule. - creator_id: :class:`int` - The ID of the user that created the rule. - trigger: :class:`AutoModTrigger` - The rule's trigger. - enabled: :class:`bool` - Whether the rule is enabled. - exempt_role_ids: Set[:class:`int`] - The IDs of the roles that are exempt from the rule. - exempt_channel_ids: Set[:class:`int`] - The IDs of the channels that are exempt from the rule. - """ - - __slots__ = ( - '_state', - '_cs_exempt_roles', - '_cs_exempt_channels', - '_cs_actions', - 'id', - 'guild', - 'name', - 'creator_id', - 'event_type', - 'trigger', - 'enabled', - 'exempt_role_ids', - 'exempt_channel_ids', - '_actions', - ) - - def __init__(self, *, data: AutoModerationRulePayload, guild: Guild, state: ConnectionState) -> None: - self._state: ConnectionState = state - self.guild: Guild = guild - self.id: int = int(data['id']) - self.name: str = data['name'] - self.creator_id = int(data['creator_id']) - self.event_type: AutoModRuleEventType = try_enum(AutoModRuleEventType, data['event_type']) - self.trigger: AutoModTrigger = AutoModTrigger.from_data(data['trigger_type'], data=data.get('trigger_metadata')) - self.enabled: bool = data['enabled'] - self.exempt_role_ids: Set[int] = {int(role_id) for role_id in data['exempt_roles']} - self.exempt_channel_ids: Set[int] = {int(channel_id) for channel_id in data['exempt_channels']} - self._actions: List[AutoModerationActionPayload] = data['actions'] - - def __repr__(self) -> str: - return f'' - - def to_dict(self) -> AutoModerationRulePayload: - ret: AutoModerationRulePayload = { - 'id': str(self.id), - 'guild_id': str(self.guild.id), - 'name': self.name, - 'creator_id': str(self.creator_id), - 'event_type': self.event_type.value, - 'trigger_type': self.trigger.type.value, - 'trigger_metadata': self.trigger.to_metadata_dict(), - 'actions': [action.to_dict() for action in self.actions], - 'enabled': self.enabled, - 'exempt_roles': [str(role_id) for role_id in self.exempt_role_ids], - 'exempt_channels': [str(channel_id) for channel_id in self.exempt_channel_ids], - } # type: ignore # trigger types break the flow here. - - return ret - - @property - def creator(self) -> Optional[Member]: - """Optional[:class:`Member`]: The member that created this rule.""" - return self.guild.get_member(self.creator_id) - - @cached_slot_property('_cs_exempt_roles') - def exempt_roles(self) -> List[Role]: - """List[:class:`Role`]: The roles that are exempt from this rule.""" - result = [] - get_role = self.guild.get_role - for role_id in self.exempt_role_ids: - role = get_role(role_id) - if role is not None: - result.append(role) - - return utils._unique(result) - - @cached_slot_property('_cs_exempt_channels') - def exempt_channels(self) -> List[Union[GuildChannel, Thread]]: - """List[Union[:class:`abc.GuildChannel`, :class:`Thread`]]: The channels that are exempt from this rule.""" - it = filter(None, map(self.guild._resolve_channel, self.exempt_channel_ids)) - return utils._unique(it) - - @cached_slot_property('_cs_actions') - def actions(self) -> List[AutoModRuleAction]: - """List[:class:`AutoModRuleAction`]: The actions that are taken when this rule is triggered.""" - return [AutoModRuleAction.from_data(action) for action in self._actions] - - def is_exempt(self, obj: Snowflake, /) -> bool: - """Check if an object is exempt from the automod rule. - - Parameters - ----------- - obj: :class:`abc.Snowflake` - The role, channel, or thread to check. - - Returns - -------- - :class:`bool` - Whether the object is exempt from the automod rule. - """ - return obj.id in self.exempt_channel_ids or obj.id in self.exempt_role_ids - - async def edit( - self, - *, - name: str = MISSING, - event_type: AutoModRuleEventType = MISSING, - actions: List[AutoModRuleAction] = MISSING, - trigger: AutoModTrigger = MISSING, - enabled: bool = MISSING, - exempt_roles: Sequence[Snowflake] = MISSING, - exempt_channels: Sequence[Snowflake] = MISSING, - reason: str = MISSING, - ) -> Self: - """|coro| - - Edits this auto moderation rule. - - You must have :attr:`Permissions.manage_guild` to edit rules. - - Parameters - ----------- - name: :class:`str` - The new name to change to. - event_type: :class:`AutoModRuleEventType` - The new event type to change to. - actions: List[:class:`AutoModRuleAction`] - The new rule actions to update. - trigger: :class:`AutoModTrigger` - The new trigger to update. - You can only change the trigger metadata, not the type. - enabled: :class:`bool` - Whether the rule should be enabled or not. - exempt_roles: Sequence[:class:`abc.Snowflake`] - The new roles to exempt from the rule. - exempt_channels: Sequence[:class:`abc.Snowflake`] - The new channels to exempt from the rule. - reason: :class:`str` - The reason for updating this rule. Shows up on the audit log. - - Raises - ------- - Forbidden - You do not have permission to edit this rule. - HTTPException - Editing the rule failed. - - Returns - -------- - :class:`AutoModRule` - The updated auto moderation rule. - """ - payload = {} - if actions is not MISSING: - payload['actions'] = [action.to_dict() for action in actions] - - if name is not MISSING: - payload['name'] = name - - if event_type is not MISSING: - payload['event_type'] = event_type - - if trigger is not MISSING: - trigger_metadata = trigger.to_metadata_dict() - if trigger_metadata is not None: - payload['trigger_metadata'] = trigger_metadata - - if enabled is not MISSING: - payload['enabled'] = enabled - - if exempt_roles is not MISSING: - payload['exempt_roles'] = exempt_roles - - if exempt_channels is not MISSING: - payload['exempt_channels'] = exempt_channels - - data = await self._state.http.edit_auto_moderation_rule( - self.guild.id, - self.id, - reason=reason, - **payload, - ) - - return AutoModRule(data=data, guild=self.guild, state=self._state) - - async def delete(self, *, reason: str = MISSING) -> None: - """|coro| - - Deletes the auto moderation rule. - - You must have :attr:`Permissions.manage_guild` to delete rules. - - Parameters - ----------- - reason: :class:`str` - The reason for deleting this rule. Shows up on the audit log. - - Raises - ------- - Forbidden - You do not have permissions to delete the rule. - HTTPException - Deleting the rule failed. - """ - await self._state.http.delete_auto_moderation_rule(self.guild.id, self.id, reason=reason) - - -class AutoModAction: - """Represents an action that was taken as the result of a moderation rule. - - .. versionadded:: 2.0 - - Attributes - ----------- - action: :class:`AutoModRuleAction` - The action that was taken. - message_id: Optional[:class:`int`] - The message ID that triggered the action. This is only available if the - action is done on an edited message. - rule_id: :class:`int` - The ID of the rule that was triggered. - rule_trigger_type: :class:`AutoModRuleTriggerType` - The trigger type of the rule that was triggered. - guild_id: :class:`int` - The ID of the guild where the rule was triggered. - user_id: :class:`int` - The ID of the user that triggered the rule. - channel_id: :class:`int` - The ID of the channel where the rule was triggered. - alert_system_message_id: Optional[:class:`int`] - The ID of the system message that was sent to the predefined alert channel. - content: :class:`str` - The content of the message that triggered the rule. - Requires the :attr:`Intents.message_content` or it will always return an empty string. - matched_keyword: Optional[:class:`str`] - The matched keyword from the triggering message. - matched_content: Optional[:class:`str`] - The matched content from the triggering message. - Requires the :attr:`Intents.message_content` or it will always return ``None``. - """ - - __slots__ = ( - '_state', - 'action', - 'rule_id', - 'rule_trigger_type', - 'guild_id', - 'user_id', - 'channel_id', - 'message_id', - 'alert_system_message_id', - 'content', - 'matched_keyword', - 'matched_content', - ) - - def __init__(self, *, data: AutoModerationActionExecutionPayload, state: ConnectionState) -> None: - self._state: ConnectionState = state - self.message_id: Optional[int] = utils._get_as_snowflake(data, 'message_id') - self.action: AutoModRuleAction = AutoModRuleAction.from_data(data['action']) - self.rule_id: int = int(data['rule_id']) - self.rule_trigger_type: AutoModRuleTriggerType = try_enum(AutoModRuleTriggerType, data['rule_trigger_type']) - self.guild_id: int = int(data['guild_id']) - self.channel_id: Optional[int] = utils._get_as_snowflake(data, 'channel_id') - self.user_id: int = int(data['user_id']) - self.alert_system_message_id: Optional[int] = utils._get_as_snowflake(data, 'alert_system_message_id') - self.content: str = data.get('content', '') - self.matched_keyword: Optional[str] = data['matched_keyword'] - self.matched_content: Optional[str] = data.get('matched_content') - - def __repr__(self) -> str: - return f'' - - @property - def guild(self) -> Guild: - """:class:`Guild`: The guild this action was taken in.""" - return self._state._get_or_create_unavailable_guild(self.guild_id) - - @property - def channel(self) -> Optional[Union[GuildChannel, Thread]]: - """Optional[Union[:class:`abc.GuildChannel`, :class:`Thread`]]: The channel this action was taken in.""" - if self.channel_id: - return self.guild.get_channel_or_thread(self.channel_id) - return None - - @property - def member(self) -> Optional[Member]: - """Optional[:class:`Member`]: The member this action was taken against /who triggered this rule.""" - return self.guild.get_member(self.user_id) - - async def fetch_rule(self) -> AutoModRule: - """|coro| - - Fetch the rule whose action was taken. - - You must have the :attr:`Permissions.manage_guild` permission to use this. - - Raises - ------- - Forbidden - You do not have permissions to view the rule. - HTTPException - Fetching the rule failed. - - Returns - -------- - :class:`AutoModRule` - The rule that was executed. - """ - - data = await self._state.http.get_auto_moderation_rule(self.guild.id, self.rule_id) - return AutoModRule(data=data, guild=self.guild, state=self._state) diff --git a/.venv/Lib/site-packages/discord/backoff.py b/.venv/Lib/site-packages/discord/backoff.py deleted file mode 100644 index cfb93ad..0000000 --- a/.venv/Lib/site-packages/discord/backoff.py +++ /dev/null @@ -1,108 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations - - -import time -import random -from typing import Callable, Generic, Literal, TypeVar, overload, Union - -T = TypeVar('T', bool, Literal[True], Literal[False]) - -# fmt: off -__all__ = ( - 'ExponentialBackoff', -) -# fmt: on - - -class ExponentialBackoff(Generic[T]): - """An implementation of the exponential backoff algorithm - - Provides a convenient interface to implement an exponential backoff - for reconnecting or retrying transmissions in a distributed network. - - Once instantiated, the delay method will return the next interval to - wait for when retrying a connection or transmission. The maximum - delay increases exponentially with each retry up to a maximum of - 2^10 * base, and is reset if no more attempts are needed in a period - of 2^11 * base seconds. - - Parameters - ---------- - base: :class:`int` - The base delay in seconds. The first retry-delay will be up to - this many seconds. - integral: :class:`bool` - Set to ``True`` if whole periods of base is desirable, otherwise any - number in between may be returned. - """ - - def __init__(self, base: int = 1, *, integral: T = False): - self._base: int = base - - self._exp: int = 0 - self._max: int = 10 - self._reset_time: int = base * 2**11 - self._last_invocation: float = time.monotonic() - - # Use our own random instance to avoid messing with global one - rand = random.Random() - rand.seed() - - self._randfunc: Callable[..., Union[int, float]] = rand.randrange if integral else rand.uniform - - @overload - def delay(self: ExponentialBackoff[Literal[False]]) -> float: - ... - - @overload - def delay(self: ExponentialBackoff[Literal[True]]) -> int: - ... - - @overload - def delay(self: ExponentialBackoff[bool]) -> Union[int, float]: - ... - - def delay(self) -> Union[int, float]: - """Compute the next delay - - Returns the next delay to wait according to the exponential - backoff algorithm. This is a value between 0 and base * 2^exp - where exponent starts off at 1 and is incremented at every - invocation of this method up to a maximum of 10. - - If a period of more than base * 2^11 has passed since the last - retry, the exponent is reset to 1. - """ - invocation = time.monotonic() - interval = invocation - self._last_invocation - self._last_invocation = invocation - - if interval > self._reset_time: - self._exp = 0 - - self._exp = min(self._exp + 1, self._max) - return self._randfunc(0, self._base * 2**self._exp) diff --git a/.venv/Lib/site-packages/discord/bin/libopus-0.x64.dll b/.venv/Lib/site-packages/discord/bin/libopus-0.x64.dll deleted file mode 100644 index 74a8e35..0000000 Binary files a/.venv/Lib/site-packages/discord/bin/libopus-0.x64.dll and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/bin/libopus-0.x86.dll b/.venv/Lib/site-packages/discord/bin/libopus-0.x86.dll deleted file mode 100644 index ee71317..0000000 Binary files a/.venv/Lib/site-packages/discord/bin/libopus-0.x86.dll and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/channel.py b/.venv/Lib/site-packages/discord/channel.py deleted file mode 100644 index f9c4f2c..0000000 --- a/.venv/Lib/site-packages/discord/channel.py +++ /dev/null @@ -1,2848 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations - -from typing import ( - Any, - AsyncIterator, - Callable, - Dict, - Iterable, - List, - Literal, - Mapping, - NamedTuple, - Optional, - TYPE_CHECKING, - Sequence, - Tuple, - TypeVar, - Union, - overload, -) -import datetime - -import discord.abc -from .scheduled_event import ScheduledEvent -from .permissions import PermissionOverwrite, Permissions -from .enums import ChannelType, PrivacyLevel, try_enum, VideoQualityMode, EntityType -from .mixins import Hashable -from . import utils -from .utils import MISSING -from .asset import Asset -from .errors import ClientException -from .stage_instance import StageInstance -from .threads import Thread -from .http import handle_message_parameters - -__all__ = ( - 'TextChannel', - 'VoiceChannel', - 'StageChannel', - 'DMChannel', - 'CategoryChannel', - 'ForumChannel', - 'GroupChannel', - 'PartialMessageable', -) - -if TYPE_CHECKING: - from typing_extensions import Self - - from .types.threads import ThreadArchiveDuration - from .role import Role - from .object import Object - from .member import Member, VoiceState - from .abc import Snowflake, SnowflakeTime - from .embeds import Embed - from .message import Message, PartialMessage - from .mentions import AllowedMentions - from .webhook import Webhook - from .state import ConnectionState - from .sticker import GuildSticker, StickerItem - from .file import File - from .user import ClientUser, User, BaseUser - from .guild import Guild, GuildChannel as GuildChannelType - from .ui.view import View - from .types.channel import ( - TextChannel as TextChannelPayload, - NewsChannel as NewsChannelPayload, - VoiceChannel as VoiceChannelPayload, - StageChannel as StageChannelPayload, - DMChannel as DMChannelPayload, - CategoryChannel as CategoryChannelPayload, - GroupDMChannel as GroupChannelPayload, - ForumChannel as ForumChannelPayload, - ) - from .types.snowflake import SnowflakeList - - OverwriteKeyT = TypeVar('OverwriteKeyT', Role, BaseUser, Object, Union[Role, Member, Object]) - - -class ThreadWithMessage(NamedTuple): - thread: Thread - message: Message - - -class TextChannel(discord.abc.Messageable, discord.abc.GuildChannel, Hashable): - """Represents a Discord guild text channel. - - .. container:: operations - - .. describe:: x == y - - Checks if two channels are equal. - - .. describe:: x != y - - Checks if two channels are not equal. - - .. describe:: hash(x) - - Returns the channel's hash. - - .. describe:: str(x) - - Returns the channel's name. - - Attributes - ----------- - name: :class:`str` - The channel name. - guild: :class:`Guild` - The guild the channel belongs to. - id: :class:`int` - The channel ID. - category_id: Optional[:class:`int`] - The category channel ID this channel belongs to, if applicable. - topic: Optional[:class:`str`] - The channel's topic. ``None`` if it doesn't exist. - position: :class:`int` - The position in the channel list. This is a number that starts at 0. e.g. the - top channel is position 0. - last_message_id: Optional[:class:`int`] - The last message ID of the message sent to this channel. It may - *not* point to an existing or valid message. - slowmode_delay: :class:`int` - The number of seconds a member must wait between sending messages - in this channel. A value of `0` denotes that it is disabled. - Bots and users with :attr:`~Permissions.manage_channels` or - :attr:`~Permissions.manage_messages` bypass slowmode. - nsfw: :class:`bool` - If the channel is marked as "not safe for work" or "age restricted". - default_auto_archive_duration: :class:`int` - The default auto archive duration in minutes for threads created in this channel. - - .. versionadded:: 2.0 - """ - - __slots__ = ( - 'name', - 'id', - 'guild', - 'topic', - '_state', - 'nsfw', - 'category_id', - 'position', - 'slowmode_delay', - '_overwrites', - '_type', - 'last_message_id', - 'default_auto_archive_duration', - ) - - def __init__(self, *, state: ConnectionState, guild: Guild, data: Union[TextChannelPayload, NewsChannelPayload]): - self._state: ConnectionState = state - self.id: int = int(data['id']) - self._type: Literal[0, 5] = data['type'] - self._update(guild, data) - - def __repr__(self) -> str: - attrs = [ - ('id', self.id), - ('name', self.name), - ('position', self.position), - ('nsfw', self.nsfw), - ('news', self.is_news()), - ('category_id', self.category_id), - ] - joined = ' '.join('%s=%r' % t for t in attrs) - return f'<{self.__class__.__name__} {joined}>' - - def _update(self, guild: Guild, data: Union[TextChannelPayload, NewsChannelPayload]) -> None: - self.guild: Guild = guild - self.name: str = data['name'] - self.category_id: Optional[int] = utils._get_as_snowflake(data, 'parent_id') - self.topic: Optional[str] = data.get('topic') - self.position: int = data['position'] - self.nsfw: bool = data.get('nsfw', False) - # Does this need coercion into `int`? No idea yet. - self.slowmode_delay: int = data.get('rate_limit_per_user', 0) - self.default_auto_archive_duration: ThreadArchiveDuration = data.get('default_auto_archive_duration', 1440) - self._type: Literal[0, 5] = data.get('type', self._type) - self.last_message_id: Optional[int] = utils._get_as_snowflake(data, 'last_message_id') - self._fill_overwrites(data) - - async def _get_channel(self) -> Self: - return self - - @property - def type(self) -> Literal[ChannelType.text, ChannelType.news]: - """:class:`ChannelType`: The channel's Discord type.""" - if self._type == 0: - return ChannelType.text - return ChannelType.news - - @property - def _sorting_bucket(self) -> int: - return ChannelType.text.value - - @property - def _scheduled_event_entity_type(self) -> Optional[EntityType]: - return None - - @utils.copy_doc(discord.abc.GuildChannel.permissions_for) - def permissions_for(self, obj: Union[Member, Role], /) -> Permissions: - base = super().permissions_for(obj) - - # text channels do not have voice related permissions - denied = Permissions.voice() - base.value &= ~denied.value - return base - - @property - def members(self) -> List[Member]: - """List[:class:`Member`]: Returns all members that can see this channel.""" - return [m for m in self.guild.members if self.permissions_for(m).read_messages] - - @property - def threads(self) -> List[Thread]: - """List[:class:`Thread`]: Returns all the threads that you can see. - - .. versionadded:: 2.0 - """ - return [thread for thread in self.guild._threads.values() if thread.parent_id == self.id] - - def is_nsfw(self) -> bool: - """:class:`bool`: Checks if the channel is NSFW.""" - return self.nsfw - - def is_news(self) -> bool: - """:class:`bool`: Checks if the channel is a news channel.""" - return self._type == ChannelType.news.value - - @property - def last_message(self) -> Optional[Message]: - """Retrieves the last message from this channel in cache. - - The message might not be valid or point to an existing message. - - .. admonition:: Reliable Fetching - :class: helpful - - For a slightly more reliable method of fetching the - last message, consider using either :meth:`history` - or :meth:`fetch_message` with the :attr:`last_message_id` - attribute. - - Returns - --------- - Optional[:class:`Message`] - The last message in this channel or ``None`` if not found. - """ - return self._state._get_message(self.last_message_id) if self.last_message_id else None - - @overload - async def edit(self) -> Optional[TextChannel]: - ... - - @overload - async def edit(self, *, position: int, reason: Optional[str] = ...) -> None: - ... - - @overload - async def edit( - self, - *, - reason: Optional[str] = ..., - name: str = ..., - topic: str = ..., - position: int = ..., - nsfw: bool = ..., - sync_permissions: bool = ..., - category: Optional[CategoryChannel] = ..., - slowmode_delay: int = ..., - default_auto_archive_duration: ThreadArchiveDuration = ..., - type: ChannelType = ..., - overwrites: Mapping[OverwriteKeyT, PermissionOverwrite] = ..., - ) -> TextChannel: - ... - - async def edit(self, *, reason: Optional[str] = None, **options: Any) -> Optional[TextChannel]: - """|coro| - - Edits the channel. - - You must have the :attr:`~Permissions.manage_channels` permission to - use this. - - .. versionchanged:: 1.3 - The ``overwrites`` keyword-only parameter was added. - - .. versionchanged:: 1.4 - The ``type`` keyword-only parameter was added. - - .. versionchanged:: 2.0 - Edits are no longer in-place, the newly edited channel is returned instead. - - .. versionchanged:: 2.0 - This function will now raise :exc:`TypeError` or - :exc:`ValueError` instead of ``InvalidArgument``. - - Parameters - ---------- - name: :class:`str` - The new channel name. - topic: :class:`str` - The new channel's topic. - position: :class:`int` - The new channel's position. - nsfw: :class:`bool` - To mark the channel as NSFW or not. - sync_permissions: :class:`bool` - Whether to sync permissions with the channel's new or pre-existing - category. Defaults to ``False``. - category: Optional[:class:`CategoryChannel`] - The new category for this channel. Can be ``None`` to remove the - category. - slowmode_delay: :class:`int` - Specifies the slowmode rate limit for user in this channel, in seconds. - A value of `0` disables slowmode. The maximum value possible is `21600`. - type: :class:`ChannelType` - Change the type of this text channel. Currently, only conversion between - :attr:`ChannelType.text` and :attr:`ChannelType.news` is supported. This - is only available to guilds that contain ``NEWS`` in :attr:`Guild.features`. - reason: Optional[:class:`str`] - The reason for editing this channel. Shows up on the audit log. - overwrites: :class:`Mapping` - A :class:`Mapping` of target (either a role or a member) to - :class:`PermissionOverwrite` to apply to the channel. - default_auto_archive_duration: :class:`int` - The new default auto archive duration in minutes for threads created in this channel. - Must be one of ``60``, ``1440``, ``4320``, or ``10080``. - - Raises - ------ - ValueError - The new ``position`` is less than 0 or greater than the number of channels. - TypeError - The permission overwrite information is not in proper form. - Forbidden - You do not have permissions to edit the channel. - HTTPException - Editing the channel failed. - - Returns - -------- - Optional[:class:`.TextChannel`] - The newly edited text channel. If the edit was only positional - then ``None`` is returned instead. - """ - - payload = await self._edit(options, reason=reason) - if payload is not None: - # the payload will always be the proper channel payload - return self.__class__(state=self._state, guild=self.guild, data=payload) # type: ignore - - @utils.copy_doc(discord.abc.GuildChannel.clone) - async def clone(self, *, name: Optional[str] = None, reason: Optional[str] = None) -> TextChannel: - return await self._clone_impl( - {'topic': self.topic, 'nsfw': self.nsfw, 'rate_limit_per_user': self.slowmode_delay}, name=name, reason=reason - ) - - async def delete_messages(self, messages: Iterable[Snowflake], *, reason: Optional[str] = None) -> None: - """|coro| - - Deletes a list of messages. This is similar to :meth:`Message.delete` - except it bulk deletes multiple messages. - - As a special case, if the number of messages is 0, then nothing - is done. If the number of messages is 1 then single message - delete is done. If it's more than two, then bulk delete is used. - - You cannot bulk delete more than 100 messages or messages that - are older than 14 days old. - - You must have the :attr:`~Permissions.manage_messages` permission to - use this. - - .. versionchanged:: 2.0 - - ``messages`` parameter is now positional-only. - - The ``reason`` keyword-only parameter was added. - - Parameters - ----------- - messages: Iterable[:class:`abc.Snowflake`] - An iterable of messages denoting which ones to bulk delete. - reason: Optional[:class:`str`] - The reason for deleting the messages. Shows up on the audit log. - - Raises - ------ - ClientException - The number of messages to delete was more than 100. - Forbidden - You do not have proper permissions to delete the messages. - NotFound - If single delete, then the message was already deleted. - HTTPException - Deleting the messages failed. - """ - if not isinstance(messages, (list, tuple)): - messages = list(messages) - - if len(messages) == 0: - return # do nothing - - if len(messages) == 1: - message_id: int = messages[0].id - await self._state.http.delete_message(self.id, message_id) - return - - if len(messages) > 100: - raise ClientException('Can only bulk delete messages up to 100 messages') - - message_ids: SnowflakeList = [m.id for m in messages] - await self._state.http.delete_messages(self.id, message_ids, reason=reason) - - async def purge( - self, - *, - limit: Optional[int] = 100, - check: Callable[[Message], bool] = MISSING, - before: Optional[SnowflakeTime] = None, - after: Optional[SnowflakeTime] = None, - around: Optional[SnowflakeTime] = None, - oldest_first: Optional[bool] = None, - bulk: bool = True, - reason: Optional[str] = None, - ) -> List[Message]: - """|coro| - - Purges a list of messages that meet the criteria given by the predicate - ``check``. If a ``check`` is not provided then all messages are deleted - without discrimination. - - You must have the :attr:`~Permissions.manage_messages` permission to - delete messages even if they are your own. - The :attr:`~Permissions.read_message_history` permission is - also needed to retrieve message history. - - .. versionchanged:: 2.0 - - The ``reason`` keyword-only parameter was added. - - Examples - --------- - - Deleting bot's messages :: - - def is_me(m): - return m.author == client.user - - deleted = await channel.purge(limit=100, check=is_me) - await channel.send(f'Deleted {len(deleted)} message(s)') - - Parameters - ----------- - limit: Optional[:class:`int`] - The number of messages to search through. This is not the number - of messages that will be deleted, though it can be. - check: Callable[[:class:`Message`], :class:`bool`] - The function used to check if a message should be deleted. - It must take a :class:`Message` as its sole parameter. - before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] - Same as ``before`` in :meth:`history`. - after: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] - Same as ``after`` in :meth:`history`. - around: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] - Same as ``around`` in :meth:`history`. - oldest_first: Optional[:class:`bool`] - Same as ``oldest_first`` in :meth:`history`. - bulk: :class:`bool` - If ``True``, use bulk delete. Setting this to ``False`` is useful for mass-deleting - a bot's own messages without :attr:`Permissions.manage_messages`. When ``True``, will - fall back to single delete if messages are older than two weeks. - reason: Optional[:class:`str`] - The reason for purging the messages. Shows up on the audit log. - - Raises - ------- - Forbidden - You do not have proper permissions to do the actions required. - HTTPException - Purging the messages failed. - - Returns - -------- - List[:class:`.Message`] - The list of messages that were deleted. - """ - return await discord.abc._purge_helper( - self, - limit=limit, - check=check, - before=before, - after=after, - around=around, - oldest_first=oldest_first, - bulk=bulk, - reason=reason, - ) - - async def webhooks(self) -> List[Webhook]: - """|coro| - - Gets the list of webhooks from this channel. - - Requires :attr:`~.Permissions.manage_webhooks` permissions. - - Raises - ------- - Forbidden - You don't have permissions to get the webhooks. - - Returns - -------- - List[:class:`Webhook`] - The webhooks for this channel. - """ - - from .webhook import Webhook - - data = await self._state.http.channel_webhooks(self.id) - return [Webhook.from_state(d, state=self._state) for d in data] - - async def create_webhook(self, *, name: str, avatar: Optional[bytes] = None, reason: Optional[str] = None) -> Webhook: - """|coro| - - Creates a webhook for this channel. - - Requires :attr:`~.Permissions.manage_webhooks` permissions. - - .. versionchanged:: 1.1 - Added the ``reason`` keyword-only parameter. - - Parameters - ------------- - name: :class:`str` - The webhook's name. - avatar: Optional[:class:`bytes`] - A :term:`py:bytes-like object` representing the webhook's default avatar. - This operates similarly to :meth:`~ClientUser.edit`. - reason: Optional[:class:`str`] - The reason for creating this webhook. Shows up in the audit logs. - - Raises - ------- - HTTPException - Creating the webhook failed. - Forbidden - You do not have permissions to create a webhook. - - Returns - -------- - :class:`Webhook` - The created webhook. - """ - - from .webhook import Webhook - - if avatar is not None: - avatar = utils._bytes_to_base64_data(avatar) # type: ignore # Silence reassignment error - - data = await self._state.http.create_webhook(self.id, name=str(name), avatar=avatar, reason=reason) - return Webhook.from_state(data, state=self._state) - - async def follow(self, *, destination: TextChannel, reason: Optional[str] = None) -> Webhook: - """ - Follows a channel using a webhook. - - Only news channels can be followed. - - .. note:: - - The webhook returned will not provide a token to do webhook - actions, as Discord does not provide it. - - .. versionadded:: 1.3 - - .. versionchanged:: 2.0 - This function will now raise :exc:`TypeError` instead of - ``InvalidArgument``. - - Parameters - ----------- - destination: :class:`TextChannel` - The channel you would like to follow from. - reason: Optional[:class:`str`] - The reason for following the channel. Shows up on the destination guild's audit log. - - .. versionadded:: 1.4 - - Raises - ------- - HTTPException - Following the channel failed. - Forbidden - You do not have the permissions to create a webhook. - ClientException - The channel is not a news channel. - TypeError - The destination channel is not a text channel. - - Returns - -------- - :class:`Webhook` - The created webhook. - """ - - if not self.is_news(): - raise ClientException('The channel must be a news channel.') - - if not isinstance(destination, TextChannel): - raise TypeError(f'Expected TextChannel received {destination.__class__.__name__}') - - from .webhook import Webhook - - data = await self._state.http.follow_webhook(self.id, webhook_channel_id=destination.id, reason=reason) - return Webhook._as_follower(data, channel=destination, user=self._state.user) - - def get_partial_message(self, message_id: int, /) -> PartialMessage: - """Creates a :class:`PartialMessage` from the message ID. - - This is useful if you want to work with a message and only have its ID without - doing an unnecessary API call. - - .. versionadded:: 1.6 - - .. versionchanged:: 2.0 - - ``message_id`` parameter is now positional-only. - - Parameters - ------------ - message_id: :class:`int` - The message ID to create a partial message for. - - Returns - --------- - :class:`PartialMessage` - The partial message. - """ - - from .message import PartialMessage - - return PartialMessage(channel=self, id=message_id) - - def get_thread(self, thread_id: int, /) -> Optional[Thread]: - """Returns a thread with the given ID. - - .. note:: - - This does not always retrieve archived threads, as they are not retained in the internal - cache. Use :func:`Guild.fetch_channel` instead. - - .. versionadded:: 2.0 - - Parameters - ----------- - thread_id: :class:`int` - The ID to search for. - - Returns - -------- - Optional[:class:`Thread`] - The returned thread or ``None`` if not found. - """ - return self.guild.get_thread(thread_id) - - async def create_thread( - self, - *, - name: str, - message: Optional[Snowflake] = None, - auto_archive_duration: ThreadArchiveDuration = MISSING, - type: Optional[ChannelType] = None, - reason: Optional[str] = None, - invitable: bool = True, - slowmode_delay: Optional[int] = None, - ) -> Thread: - """|coro| - - Creates a thread in this text channel. - - To create a public thread, you must have :attr:`~discord.Permissions.create_public_threads`. - For a private thread, :attr:`~discord.Permissions.create_private_threads` is needed instead. - - .. versionadded:: 2.0 - - Parameters - ----------- - name: :class:`str` - The name of the thread. - message: Optional[:class:`abc.Snowflake`] - A snowflake representing the message to create the thread with. - If ``None`` is passed then a private thread is created. - Defaults to ``None``. - auto_archive_duration: :class:`int` - The duration in minutes before a thread is automatically archived for inactivity. - If not provided, the channel's default auto archive duration is used. - type: Optional[:class:`ChannelType`] - The type of thread to create. If a ``message`` is passed then this parameter - is ignored, as a thread created with a message is always a public thread. - By default this creates a private thread if this is ``None``. - reason: :class:`str` - The reason for creating a new thread. Shows up on the audit log. - invitable: :class:`bool` - Whether non-moderators can add users to the thread. Only applicable to private threads. - Defaults to ``True``. - slowmode_delay: Optional[:class:`int`] - Specifies the slowmode rate limit for user in this channel, in seconds. - The maximum value possible is `21600`. By default no slowmode rate limit - if this is ``None``. - - Raises - ------- - Forbidden - You do not have permissions to create a thread. - HTTPException - Starting the thread failed. - - Returns - -------- - :class:`Thread` - The created thread - """ - - if type is None: - type = ChannelType.private_thread - - if message is None: - data = await self._state.http.start_thread_without_message( - self.id, - name=name, - auto_archive_duration=auto_archive_duration or self.default_auto_archive_duration, - type=type.value, - reason=reason, - invitable=invitable, - rate_limit_per_user=slowmode_delay, - ) - else: - data = await self._state.http.start_thread_with_message( - self.id, - message.id, - name=name, - auto_archive_duration=auto_archive_duration or self.default_auto_archive_duration, - reason=reason, - rate_limit_per_user=slowmode_delay, - ) - - return Thread(guild=self.guild, state=self._state, data=data) - - async def archived_threads( - self, - *, - private: bool = False, - joined: bool = False, - limit: Optional[int] = 100, - before: Optional[Union[Snowflake, datetime.datetime]] = None, - ) -> AsyncIterator[Thread]: - """Returns an :term:`asynchronous iterator` that iterates over all archived threads in this text channel, - in order of decreasing ID for joined threads, and decreasing :attr:`Thread.archive_timestamp` otherwise. - - You must have :attr:`~Permissions.read_message_history` to use this. If iterating over private threads - then :attr:`~Permissions.manage_threads` is also required. - - .. versionadded:: 2.0 - - Parameters - ----------- - limit: Optional[:class:`bool`] - The number of threads to retrieve. - If ``None``, retrieves every archived thread in the channel. Note, however, - that this would make it a slow operation. - before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] - Retrieve archived channels before the given date or ID. - private: :class:`bool` - Whether to retrieve private archived threads. - joined: :class:`bool` - Whether to retrieve private archived threads that you've joined. - You cannot set ``joined`` to ``True`` and ``private`` to ``False``. - - Raises - ------ - Forbidden - You do not have permissions to get archived threads. - HTTPException - The request to get the archived threads failed. - ValueError - ``joined`` was set to ``True`` and ``private`` was set to ``False``. You cannot retrieve public archived - threads that you have joined. - - Yields - ------- - :class:`Thread` - The archived threads. - """ - if joined and not private: - raise ValueError('Cannot retrieve joined public archived threads') - - before_timestamp = None - - if isinstance(before, datetime.datetime): - if joined: - before_timestamp = str(utils.time_snowflake(before, high=False)) - else: - before_timestamp = before.isoformat() - elif before is not None: - if joined: - before_timestamp = str(before.id) - else: - before_timestamp = utils.snowflake_time(before.id).isoformat() - - update_before = lambda data: data['thread_metadata']['archive_timestamp'] - endpoint = self.guild._state.http.get_public_archived_threads - - if joined: - update_before = lambda data: data['id'] - endpoint = self.guild._state.http.get_joined_private_archived_threads - elif private: - endpoint = self.guild._state.http.get_private_archived_threads - - while True: - retrieve = 100 - if limit is not None: - if limit <= 0: - return - retrieve = max(2, min(retrieve, limit)) - - data = await endpoint(self.id, before=before_timestamp, limit=retrieve) - - threads = data.get('threads', []) - for raw_thread in threads: - yield Thread(guild=self.guild, state=self.guild._state, data=raw_thread) - # Currently the API doesn't let you request less than 2 threads. - # Bail out early if we had to retrieve more than what the limit was. - if limit is not None: - limit -= 1 - if limit <= 0: - return - - if not data.get('has_more', False): - return - - before_timestamp = update_before(threads[-1]) - - -class VocalGuildChannel(discord.abc.Connectable, discord.abc.GuildChannel, Hashable): - __slots__ = ( - 'name', - 'id', - 'guild', - 'nsfw', - 'bitrate', - 'user_limit', - '_state', - 'position', - '_overwrites', - 'category_id', - 'rtc_region', - 'video_quality_mode', - 'last_message_id', - ) - - def __init__(self, *, state: ConnectionState, guild: Guild, data: Union[VoiceChannelPayload, StageChannelPayload]): - self._state: ConnectionState = state - self.id: int = int(data['id']) - self._update(guild, data) - - def _get_voice_client_key(self) -> Tuple[int, str]: - return self.guild.id, 'guild_id' - - def _get_voice_state_pair(self) -> Tuple[int, int]: - return self.guild.id, self.id - - def _update(self, guild: Guild, data: Union[VoiceChannelPayload, StageChannelPayload]) -> None: - self.guild: Guild = guild - self.name: str = data['name'] - self.nsfw: bool = data.get('nsfw', False) - self.rtc_region: Optional[str] = data.get('rtc_region') - self.video_quality_mode: VideoQualityMode = try_enum(VideoQualityMode, data.get('video_quality_mode', 1)) - self.category_id: Optional[int] = utils._get_as_snowflake(data, 'parent_id') - self.last_message_id: Optional[int] = utils._get_as_snowflake(data, 'last_message_id') - self.position: int = data['position'] - self.bitrate: int = data['bitrate'] - self.user_limit: int = data['user_limit'] - self._fill_overwrites(data) - - @property - def _sorting_bucket(self) -> int: - return ChannelType.voice.value - - def is_nsfw(self) -> bool: - """:class:`bool`: Checks if the channel is NSFW. - - .. versionadded:: 2.0 - """ - return self.nsfw - - @property - def members(self) -> List[Member]: - """List[:class:`Member`]: Returns all members that are currently inside this voice channel.""" - ret = [] - for user_id, state in self.guild._voice_states.items(): - if state.channel and state.channel.id == self.id: - member = self.guild.get_member(user_id) - if member is not None: - ret.append(member) - return ret - - @property - def voice_states(self) -> Dict[int, VoiceState]: - """Returns a mapping of member IDs who have voice states in this channel. - - .. versionadded:: 1.3 - - .. note:: - - This function is intentionally low level to replace :attr:`members` - when the member cache is unavailable. - - Returns - -------- - Mapping[:class:`int`, :class:`VoiceState`] - The mapping of member ID to a voice state. - """ - # fmt: off - return { - key: value - for key, value in self.guild._voice_states.items() - if value.channel and value.channel.id == self.id - } - # fmt: on - - @property - def scheduled_events(self) -> List[ScheduledEvent]: - """List[:class:`ScheduledEvent`]: Returns all scheduled events for this channel. - - .. versionadded:: 2.0 - """ - return [event for event in self.guild.scheduled_events if event.channel_id == self.id] - - @utils.copy_doc(discord.abc.GuildChannel.permissions_for) - def permissions_for(self, obj: Union[Member, Role], /) -> Permissions: - base = super().permissions_for(obj) - - # voice channels cannot be edited by people who can't connect to them - # It also implicitly denies all other voice perms - if not base.connect: - denied = Permissions.voice() - denied.update(manage_channels=True, manage_roles=True) - base.value &= ~denied.value - return base - - -class VoiceChannel(discord.abc.Messageable, VocalGuildChannel): - """Represents a Discord guild voice channel. - - .. container:: operations - - .. describe:: x == y - - Checks if two channels are equal. - - .. describe:: x != y - - Checks if two channels are not equal. - - .. describe:: hash(x) - - Returns the channel's hash. - - .. describe:: str(x) - - Returns the channel's name. - - Attributes - ----------- - name: :class:`str` - The channel name. - guild: :class:`Guild` - The guild the channel belongs to. - id: :class:`int` - The channel ID. - nsfw: :class:`bool` - If the channel is marked as "not safe for work" or "age restricted". - - .. versionadded:: 2.0 - category_id: Optional[:class:`int`] - The category channel ID this channel belongs to, if applicable. - position: :class:`int` - The position in the channel list. This is a number that starts at 0. e.g. the - top channel is position 0. - bitrate: :class:`int` - The channel's preferred audio bitrate in bits per second. - user_limit: :class:`int` - The channel's limit for number of members that can be in a voice channel. - rtc_region: Optional[:class:`str`] - The region for the voice channel's voice communication. - A value of ``None`` indicates automatic voice region detection. - - .. versionadded:: 1.7 - - .. versionchanged:: 2.0 - The type of this attribute has changed to :class:`str`. - video_quality_mode: :class:`VideoQualityMode` - The camera video quality for the voice channel's participants. - - .. versionadded:: 2.0 - last_message_id: Optional[:class:`int`] - The last message ID of the message sent to this channel. It may - *not* point to an existing or valid message. - - .. versionadded:: 2.0 - """ - - __slots__ = () - - def __repr__(self) -> str: - attrs = [ - ('id', self.id), - ('name', self.name), - ('rtc_region', self.rtc_region), - ('position', self.position), - ('bitrate', self.bitrate), - ('video_quality_mode', self.video_quality_mode), - ('user_limit', self.user_limit), - ('category_id', self.category_id), - ] - joined = ' '.join('%s=%r' % t for t in attrs) - return f'<{self.__class__.__name__} {joined}>' - - async def _get_channel(self) -> Self: - return self - - @property - def _scheduled_event_entity_type(self) -> Optional[EntityType]: - return EntityType.voice - - @property - def type(self) -> Literal[ChannelType.voice]: - """:class:`ChannelType`: The channel's Discord type.""" - return ChannelType.voice - - @property - def last_message(self) -> Optional[Message]: - """Retrieves the last message from this channel in cache. - - The message might not be valid or point to an existing message. - - .. versionadded:: 2.0 - - .. admonition:: Reliable Fetching - :class: helpful - - For a slightly more reliable method of fetching the - last message, consider using either :meth:`history` - or :meth:`fetch_message` with the :attr:`last_message_id` - attribute. - - Returns - --------- - Optional[:class:`Message`] - The last message in this channel or ``None`` if not found. - """ - return self._state._get_message(self.last_message_id) if self.last_message_id else None - - def get_partial_message(self, message_id: int, /) -> PartialMessage: - """Creates a :class:`PartialMessage` from the message ID. - - This is useful if you want to work with a message and only have its ID without - doing an unnecessary API call. - - .. versionadded:: 2.0 - - Parameters - ------------ - message_id: :class:`int` - The message ID to create a partial message for. - - Returns - --------- - :class:`PartialMessage` - The partial message. - """ - - from .message import PartialMessage - - return PartialMessage(channel=self, id=message_id) - - async def delete_messages(self, messages: Iterable[Snowflake], *, reason: Optional[str] = None) -> None: - """|coro| - - Deletes a list of messages. This is similar to :meth:`Message.delete` - except it bulk deletes multiple messages. - - As a special case, if the number of messages is 0, then nothing - is done. If the number of messages is 1 then single message - delete is done. If it's more than two, then bulk delete is used. - - You cannot bulk delete more than 100 messages or messages that - are older than 14 days old. - - You must have the :attr:`~Permissions.manage_messages` permission to - use this. - - .. versionadded:: 2.0 - - Parameters - ----------- - messages: Iterable[:class:`abc.Snowflake`] - An iterable of messages denoting which ones to bulk delete. - reason: Optional[:class:`str`] - The reason for deleting the messages. Shows up on the audit log. - - Raises - ------ - ClientException - The number of messages to delete was more than 100. - Forbidden - You do not have proper permissions to delete the messages. - NotFound - If single delete, then the message was already deleted. - HTTPException - Deleting the messages failed. - """ - if not isinstance(messages, (list, tuple)): - messages = list(messages) - - if len(messages) == 0: - return # do nothing - - if len(messages) == 1: - message_id: int = messages[0].id - await self._state.http.delete_message(self.id, message_id) - return - - if len(messages) > 100: - raise ClientException('Can only bulk delete messages up to 100 messages') - - message_ids: SnowflakeList = [m.id for m in messages] - await self._state.http.delete_messages(self.id, message_ids, reason=reason) - - async def purge( - self, - *, - limit: Optional[int] = 100, - check: Callable[[Message], bool] = MISSING, - before: Optional[SnowflakeTime] = None, - after: Optional[SnowflakeTime] = None, - around: Optional[SnowflakeTime] = None, - oldest_first: Optional[bool] = None, - bulk: bool = True, - reason: Optional[str] = None, - ) -> List[Message]: - """|coro| - - Purges a list of messages that meet the criteria given by the predicate - ``check``. If a ``check`` is not provided then all messages are deleted - without discrimination. - - You must have the :attr:`~Permissions.manage_messages` permission to - delete messages even if they are your own. - The :attr:`~Permissions.read_message_history` permission is - also needed to retrieve message history. - - .. versionadded:: 2.0 - - Examples - --------- - - Deleting bot's messages :: - - def is_me(m): - return m.author == client.user - - deleted = await channel.purge(limit=100, check=is_me) - await channel.send(f'Deleted {len(deleted)} message(s)') - - Parameters - ----------- - limit: Optional[:class:`int`] - The number of messages to search through. This is not the number - of messages that will be deleted, though it can be. - check: Callable[[:class:`Message`], :class:`bool`] - The function used to check if a message should be deleted. - It must take a :class:`Message` as its sole parameter. - before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] - Same as ``before`` in :meth:`history`. - after: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] - Same as ``after`` in :meth:`history`. - around: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] - Same as ``around`` in :meth:`history`. - oldest_first: Optional[:class:`bool`] - Same as ``oldest_first`` in :meth:`history`. - bulk: :class:`bool` - If ``True``, use bulk delete. Setting this to ``False`` is useful for mass-deleting - a bot's own messages without :attr:`Permissions.manage_messages`. When ``True``, will - fall back to single delete if messages are older than two weeks. - reason: Optional[:class:`str`] - The reason for purging the messages. Shows up on the audit log. - - Raises - ------- - Forbidden - You do not have proper permissions to do the actions required. - HTTPException - Purging the messages failed. - - Returns - -------- - List[:class:`.Message`] - The list of messages that were deleted. - """ - - return await discord.abc._purge_helper( - self, - limit=limit, - check=check, - before=before, - after=after, - around=around, - oldest_first=oldest_first, - bulk=bulk, - reason=reason, - ) - - async def webhooks(self) -> List[Webhook]: - """|coro| - - Gets the list of webhooks from this channel. - - Requires :attr:`~.Permissions.manage_webhooks` permissions. - - .. versionadded:: 2.0 - - Raises - ------- - Forbidden - You don't have permissions to get the webhooks. - - Returns - -------- - List[:class:`Webhook`] - The webhooks for this channel. - """ - - from .webhook import Webhook - - data = await self._state.http.channel_webhooks(self.id) - return [Webhook.from_state(d, state=self._state) for d in data] - - async def create_webhook(self, *, name: str, avatar: Optional[bytes] = None, reason: Optional[str] = None) -> Webhook: - """|coro| - - Creates a webhook for this channel. - - Requires :attr:`~.Permissions.manage_webhooks` permissions. - - .. versionadded:: 2.0 - - Parameters - ------------- - name: :class:`str` - The webhook's name. - avatar: Optional[:class:`bytes`] - A :term:`py:bytes-like object` representing the webhook's default avatar. - This operates similarly to :meth:`~ClientUser.edit`. - reason: Optional[:class:`str`] - The reason for creating this webhook. Shows up in the audit logs. - - Raises - ------- - HTTPException - Creating the webhook failed. - Forbidden - You do not have permissions to create a webhook. - - Returns - -------- - :class:`Webhook` - The created webhook. - """ - - from .webhook import Webhook - - if avatar is not None: - avatar = utils._bytes_to_base64_data(avatar) # type: ignore # Silence reassignment error - - data = await self._state.http.create_webhook(self.id, name=str(name), avatar=avatar, reason=reason) - return Webhook.from_state(data, state=self._state) - - @utils.copy_doc(discord.abc.GuildChannel.clone) - async def clone(self, *, name: Optional[str] = None, reason: Optional[str] = None) -> VoiceChannel: - return await self._clone_impl({'bitrate': self.bitrate, 'user_limit': self.user_limit}, name=name, reason=reason) - - @overload - async def edit(self) -> None: - ... - - @overload - async def edit(self, *, position: int, reason: Optional[str] = ...) -> None: - ... - - @overload - async def edit( - self, - *, - name: str = ..., - nsfw: bool = ..., - bitrate: int = ..., - user_limit: int = ..., - position: int = ..., - sync_permissions: int = ..., - category: Optional[CategoryChannel] = ..., - overwrites: Mapping[OverwriteKeyT, PermissionOverwrite] = ..., - rtc_region: Optional[str] = ..., - video_quality_mode: VideoQualityMode = ..., - reason: Optional[str] = ..., - ) -> VoiceChannel: - ... - - async def edit(self, *, reason: Optional[str] = None, **options: Any) -> Optional[VoiceChannel]: - """|coro| - - Edits the channel. - - You must have the :attr:`~Permissions.manage_channels` permission to - use this. - - .. versionchanged:: 1.3 - The ``overwrites`` keyword-only parameter was added. - - .. versionchanged:: 2.0 - Edits are no longer in-place, the newly edited channel is returned instead. - - .. versionchanged:: 2.0 - The ``region`` parameter now accepts :class:`str` instead of an enum. - - .. versionchanged:: 2.0 - This function will now raise :exc:`TypeError` instead of - ``InvalidArgument``. - - Parameters - ---------- - name: :class:`str` - The new channel's name. - bitrate: :class:`int` - The new channel's bitrate. - nsfw: :class:`bool` - To mark the channel as NSFW or not. - user_limit: :class:`int` - The new channel's user limit. - position: :class:`int` - The new channel's position. - sync_permissions: :class:`bool` - Whether to sync permissions with the channel's new or pre-existing - category. Defaults to ``False``. - category: Optional[:class:`CategoryChannel`] - The new category for this channel. Can be ``None`` to remove the - category. - reason: Optional[:class:`str`] - The reason for editing this channel. Shows up on the audit log. - overwrites: :class:`Mapping` - A :class:`Mapping` of target (either a role or a member) to - :class:`PermissionOverwrite` to apply to the channel. - rtc_region: Optional[:class:`str`] - The new region for the voice channel's voice communication. - A value of ``None`` indicates automatic voice region detection. - - .. versionadded:: 1.7 - video_quality_mode: :class:`VideoQualityMode` - The camera video quality for the voice channel's participants. - - .. versionadded:: 2.0 - - Raises - ------ - TypeError - If the permission overwrite information is not in proper form. - Forbidden - You do not have permissions to edit the channel. - HTTPException - Editing the channel failed. - - Returns - -------- - Optional[:class:`.VoiceChannel`] - The newly edited voice channel. If the edit was only positional - then ``None`` is returned instead. - """ - - payload = await self._edit(options, reason=reason) - if payload is not None: - # the payload will always be the proper channel payload - return self.__class__(state=self._state, guild=self.guild, data=payload) # type: ignore - - -class StageChannel(VocalGuildChannel): - """Represents a Discord guild stage channel. - - .. versionadded:: 1.7 - - .. container:: operations - - .. describe:: x == y - - Checks if two channels are equal. - - .. describe:: x != y - - Checks if two channels are not equal. - - .. describe:: hash(x) - - Returns the channel's hash. - - .. describe:: str(x) - - Returns the channel's name. - - Attributes - ----------- - name: :class:`str` - The channel name. - guild: :class:`Guild` - The guild the channel belongs to. - id: :class:`int` - The channel ID. - nsfw: :class:`bool` - If the channel is marked as "not safe for work" or "age restricted". - - .. versionadded:: 2.0 - topic: Optional[:class:`str`] - The channel's topic. ``None`` if it isn't set. - category_id: Optional[:class:`int`] - The category channel ID this channel belongs to, if applicable. - position: :class:`int` - The position in the channel list. This is a number that starts at 0. e.g. the - top channel is position 0. - bitrate: :class:`int` - The channel's preferred audio bitrate in bits per second. - user_limit: :class:`int` - The channel's limit for number of members that can be in a stage channel. - rtc_region: Optional[:class:`str`] - The region for the stage channel's voice communication. - A value of ``None`` indicates automatic voice region detection. - video_quality_mode: :class:`VideoQualityMode` - The camera video quality for the stage channel's participants. - - .. versionadded:: 2.0 - """ - - __slots__ = ('topic',) - - def __repr__(self) -> str: - attrs = [ - ('id', self.id), - ('name', self.name), - ('topic', self.topic), - ('rtc_region', self.rtc_region), - ('position', self.position), - ('bitrate', self.bitrate), - ('video_quality_mode', self.video_quality_mode), - ('user_limit', self.user_limit), - ('category_id', self.category_id), - ] - joined = ' '.join('%s=%r' % t for t in attrs) - return f'<{self.__class__.__name__} {joined}>' - - def _update(self, guild: Guild, data: StageChannelPayload) -> None: - super()._update(guild, data) - self.topic: Optional[str] = data.get('topic') - - @property - def _scheduled_event_entity_type(self) -> Optional[EntityType]: - return EntityType.stage_instance - - @property - def requesting_to_speak(self) -> List[Member]: - """List[:class:`Member`]: A list of members who are requesting to speak in the stage channel.""" - return [member for member in self.members if member.voice and member.voice.requested_to_speak_at is not None] - - @property - def speakers(self) -> List[Member]: - """List[:class:`Member`]: A list of members who have been permitted to speak in the stage channel. - - .. versionadded:: 2.0 - """ - return [ - member - for member in self.members - if member.voice and not member.voice.suppress and member.voice.requested_to_speak_at is None - ] - - @property - def listeners(self) -> List[Member]: - """List[:class:`Member`]: A list of members who are listening in the stage channel. - - .. versionadded:: 2.0 - """ - return [member for member in self.members if member.voice and member.voice.suppress] - - @property - def moderators(self) -> List[Member]: - """List[:class:`Member`]: A list of members who are moderating the stage channel. - - .. versionadded:: 2.0 - """ - required_permissions = Permissions.stage_moderator() - return [member for member in self.members if self.permissions_for(member) >= required_permissions] - - @property - def type(self) -> Literal[ChannelType.stage_voice]: - """:class:`ChannelType`: The channel's Discord type.""" - return ChannelType.stage_voice - - @utils.copy_doc(discord.abc.GuildChannel.clone) - async def clone(self, *, name: Optional[str] = None, reason: Optional[str] = None) -> StageChannel: - return await self._clone_impl({}, name=name, reason=reason) - - @property - def instance(self) -> Optional[StageInstance]: - """Optional[:class:`StageInstance`]: The running stage instance of the stage channel. - - .. versionadded:: 2.0 - """ - return utils.get(self.guild.stage_instances, channel_id=self.id) - - async def create_instance( - self, *, topic: str, privacy_level: PrivacyLevel = MISSING, reason: Optional[str] = None - ) -> StageInstance: - """|coro| - - Create a stage instance. - - You must have the :attr:`~Permissions.manage_channels` permission to - use this. - - .. versionadded:: 2.0 - - Parameters - ----------- - topic: :class:`str` - The stage instance's topic. - privacy_level: :class:`PrivacyLevel` - The stage instance's privacy level. Defaults to :attr:`PrivacyLevel.guild_only`. - reason: :class:`str` - The reason the stage instance was created. Shows up on the audit log. - - Raises - ------ - TypeError - If the ``privacy_level`` parameter is not the proper type. - Forbidden - You do not have permissions to create a stage instance. - HTTPException - Creating a stage instance failed. - - Returns - -------- - :class:`StageInstance` - The newly created stage instance. - """ - - payload: Dict[str, Any] = {'channel_id': self.id, 'topic': topic} - - if privacy_level is not MISSING: - if not isinstance(privacy_level, PrivacyLevel): - raise TypeError('privacy_level field must be of type PrivacyLevel') - - payload['privacy_level'] = privacy_level.value - - data = await self._state.http.create_stage_instance(**payload, reason=reason) - return StageInstance(guild=self.guild, state=self._state, data=data) - - async def fetch_instance(self) -> StageInstance: - """|coro| - - Gets the running :class:`StageInstance`. - - .. versionadded:: 2.0 - - Raises - ------- - NotFound - The stage instance or channel could not be found. - HTTPException - Getting the stage instance failed. - - Returns - -------- - :class:`StageInstance` - The stage instance. - """ - data = await self._state.http.get_stage_instance(self.id) - return StageInstance(guild=self.guild, state=self._state, data=data) - - @overload - async def edit(self) -> None: - ... - - @overload - async def edit(self, *, position: int, reason: Optional[str] = ...) -> None: - ... - - @overload - async def edit( - self, - *, - name: str = ..., - nsfw: bool = ..., - position: int = ..., - sync_permissions: int = ..., - category: Optional[CategoryChannel] = ..., - overwrites: Mapping[OverwriteKeyT, PermissionOverwrite] = ..., - rtc_region: Optional[str] = ..., - video_quality_mode: VideoQualityMode = ..., - reason: Optional[str] = ..., - ) -> StageChannel: - ... - - async def edit(self, *, reason: Optional[str] = None, **options: Any) -> Optional[StageChannel]: - """|coro| - - Edits the channel. - - You must have the :attr:`~Permissions.manage_channels` permission to - use this. - - .. versionchanged:: 2.0 - The ``topic`` parameter must now be set via :attr:`create_instance`. - - .. versionchanged:: 2.0 - Edits are no longer in-place, the newly edited channel is returned instead. - - .. versionchanged:: 2.0 - The ``region`` parameter now accepts :class:`str` instead of an enum. - - .. versionchanged:: 2.0 - This function will now raise :exc:`TypeError` instead of - ``InvalidArgument``. - - Parameters - ---------- - name: :class:`str` - The new channel's name. - position: :class:`int` - The new channel's position. - nsfw: :class:`bool` - To mark the channel as NSFW or not. - sync_permissions: :class:`bool` - Whether to sync permissions with the channel's new or pre-existing - category. Defaults to ``False``. - category: Optional[:class:`CategoryChannel`] - The new category for this channel. Can be ``None`` to remove the - category. - reason: Optional[:class:`str`] - The reason for editing this channel. Shows up on the audit log. - overwrites: :class:`Mapping` - A :class:`Mapping` of target (either a role or a member) to - :class:`PermissionOverwrite` to apply to the channel. - rtc_region: Optional[:class:`str`] - The new region for the stage channel's voice communication. - A value of ``None`` indicates automatic voice region detection. - video_quality_mode: :class:`VideoQualityMode` - The camera video quality for the stage channel's participants. - - .. versionadded:: 2.0 - - Raises - ------ - ValueError - If the permission overwrite information is not in proper form. - Forbidden - You do not have permissions to edit the channel. - HTTPException - Editing the channel failed. - - Returns - -------- - Optional[:class:`.StageChannel`] - The newly edited stage channel. If the edit was only positional - then ``None`` is returned instead. - """ - - payload = await self._edit(options, reason=reason) - if payload is not None: - # the payload will always be the proper channel payload - return self.__class__(state=self._state, guild=self.guild, data=payload) # type: ignore - - -class CategoryChannel(discord.abc.GuildChannel, Hashable): - """Represents a Discord channel category. - - These are useful to group channels to logical compartments. - - .. container:: operations - - .. describe:: x == y - - Checks if two channels are equal. - - .. describe:: x != y - - Checks if two channels are not equal. - - .. describe:: hash(x) - - Returns the category's hash. - - .. describe:: str(x) - - Returns the category's name. - - Attributes - ----------- - name: :class:`str` - The category name. - guild: :class:`Guild` - The guild the category belongs to. - id: :class:`int` - The category channel ID. - position: :class:`int` - The position in the category list. This is a number that starts at 0. e.g. the - top category is position 0. - nsfw: :class:`bool` - If the channel is marked as "not safe for work". - - .. note:: - - To check if the channel or the guild of that channel are marked as NSFW, consider :meth:`is_nsfw` instead. - """ - - __slots__ = ('name', 'id', 'guild', 'nsfw', '_state', 'position', '_overwrites', 'category_id') - - def __init__(self, *, state: ConnectionState, guild: Guild, data: CategoryChannelPayload): - self._state: ConnectionState = state - self.id: int = int(data['id']) - self._update(guild, data) - - def __repr__(self) -> str: - return f'' - - def _update(self, guild: Guild, data: CategoryChannelPayload) -> None: - self.guild: Guild = guild - self.name: str = data['name'] - self.category_id: Optional[int] = utils._get_as_snowflake(data, 'parent_id') - self.nsfw: bool = data.get('nsfw', False) - self.position: int = data['position'] - self._fill_overwrites(data) - - @property - def _sorting_bucket(self) -> int: - return ChannelType.category.value - - @property - def _scheduled_event_entity_type(self) -> Optional[EntityType]: - return None - - @property - def type(self) -> Literal[ChannelType.category]: - """:class:`ChannelType`: The channel's Discord type.""" - return ChannelType.category - - def is_nsfw(self) -> bool: - """:class:`bool`: Checks if the category is NSFW.""" - return self.nsfw - - @utils.copy_doc(discord.abc.GuildChannel.clone) - async def clone(self, *, name: Optional[str] = None, reason: Optional[str] = None) -> CategoryChannel: - return await self._clone_impl({'nsfw': self.nsfw}, name=name, reason=reason) - - @overload - async def edit(self) -> None: - ... - - @overload - async def edit(self, *, position: int, reason: Optional[str] = ...) -> None: - ... - - @overload - async def edit( - self, - *, - name: str = ..., - position: int = ..., - nsfw: bool = ..., - overwrites: Mapping[OverwriteKeyT, PermissionOverwrite] = ..., - reason: Optional[str] = ..., - ) -> CategoryChannel: - ... - - async def edit(self, *, reason: Optional[str] = None, **options: Any) -> Optional[CategoryChannel]: - """|coro| - - Edits the channel. - - You must have the :attr:`~Permissions.manage_channels` permission to - use this. - - .. versionchanged:: 1.3 - The ``overwrites`` keyword-only parameter was added. - - .. versionchanged:: 2.0 - Edits are no longer in-place, the newly edited channel is returned instead. - - .. versionchanged:: 2.0 - This function will now raise :exc:`TypeError` or - :exc:`ValueError` instead of ``InvalidArgument``. - - Parameters - ---------- - name: :class:`str` - The new category's name. - position: :class:`int` - The new category's position. - nsfw: :class:`bool` - To mark the category as NSFW or not. - reason: Optional[:class:`str`] - The reason for editing this category. Shows up on the audit log. - overwrites: :class:`Mapping` - A :class:`Mapping` of target (either a role or a member) to - :class:`PermissionOverwrite` to apply to the channel. - - Raises - ------ - ValueError - If position is less than 0 or greater than the number of categories. - TypeError - The overwrite information is not in proper form. - Forbidden - You do not have permissions to edit the category. - HTTPException - Editing the category failed. - - Returns - -------- - Optional[:class:`.CategoryChannel`] - The newly edited category channel. If the edit was only positional - then ``None`` is returned instead. - """ - - payload = await self._edit(options, reason=reason) - if payload is not None: - # the payload will always be the proper channel payload - return self.__class__(state=self._state, guild=self.guild, data=payload) # type: ignore - - @utils.copy_doc(discord.abc.GuildChannel.move) - async def move(self, **kwargs: Any) -> None: - kwargs.pop('category', None) - await super().move(**kwargs) - - @property - def channels(self) -> List[GuildChannelType]: - """List[:class:`abc.GuildChannel`]: Returns the channels that are under this category. - - These are sorted by the official Discord UI, which places voice channels below the text channels. - """ - - def comparator(channel): - return (not isinstance(channel, TextChannel), channel.position) - - ret = [c for c in self.guild.channels if c.category_id == self.id] - ret.sort(key=comparator) - return ret - - @property - def text_channels(self) -> List[TextChannel]: - """List[:class:`TextChannel`]: Returns the text channels that are under this category.""" - ret = [c for c in self.guild.channels if c.category_id == self.id and isinstance(c, TextChannel)] - ret.sort(key=lambda c: (c.position, c.id)) - return ret - - @property - def voice_channels(self) -> List[VoiceChannel]: - """List[:class:`VoiceChannel`]: Returns the voice channels that are under this category.""" - ret = [c for c in self.guild.channels if c.category_id == self.id and isinstance(c, VoiceChannel)] - ret.sort(key=lambda c: (c.position, c.id)) - return ret - - @property - def stage_channels(self) -> List[StageChannel]: - """List[:class:`StageChannel`]: Returns the stage channels that are under this category. - - .. versionadded:: 1.7 - """ - ret = [c for c in self.guild.channels if c.category_id == self.id and isinstance(c, StageChannel)] - ret.sort(key=lambda c: (c.position, c.id)) - return ret - - async def create_text_channel(self, name: str, **options: Any) -> TextChannel: - """|coro| - - A shortcut method to :meth:`Guild.create_text_channel` to create a :class:`TextChannel` in the category. - - Returns - ------- - :class:`TextChannel` - The channel that was just created. - """ - return await self.guild.create_text_channel(name, category=self, **options) - - async def create_voice_channel(self, name: str, **options: Any) -> VoiceChannel: - """|coro| - - A shortcut method to :meth:`Guild.create_voice_channel` to create a :class:`VoiceChannel` in the category. - - Returns - ------- - :class:`VoiceChannel` - The channel that was just created. - """ - return await self.guild.create_voice_channel(name, category=self, **options) - - async def create_stage_channel(self, name: str, **options: Any) -> StageChannel: - """|coro| - - A shortcut method to :meth:`Guild.create_stage_channel` to create a :class:`StageChannel` in the category. - - .. versionadded:: 1.7 - - Returns - ------- - :class:`StageChannel` - The channel that was just created. - """ - return await self.guild.create_stage_channel(name, category=self, **options) - - async def create_forum(self, name: str, **options: Any) -> ForumChannel: - """|coro| - - A shortcut method to :meth:`Guild.create_forum` to create a :class:`ForumChannel` in the category. - - .. versionadded:: 2.0 - - Returns - -------- - :class:`ForumChannel` - The channel that was just created. - """ - return await self.guild.create_forum(name, category=self, **options) - - -class ForumChannel(discord.abc.GuildChannel, Hashable): - """Represents a Discord guild forum channel. - - .. versionadded:: 2.0 - - .. container:: operations - - .. describe:: x == y - - Checks if two forums are equal. - - .. describe:: x != y - - Checks if two forums are not equal. - - .. describe:: hash(x) - - Returns the forum's hash. - - .. describe:: str(x) - - Returns the forum's name. - - Attributes - ----------- - name: :class:`str` - The forum name. - guild: :class:`Guild` - The guild the forum belongs to. - id: :class:`int` - The forum ID. - category_id: Optional[:class:`int`] - The category channel ID this forum belongs to, if applicable. - topic: Optional[:class:`str`] - The forum's topic. ``None`` if it doesn't exist. - position: :class:`int` - The position in the channel list. This is a number that starts at 0. e.g. the - top channel is position 0. - last_message_id: Optional[:class:`int`] - The last thread ID that was created on this forum. This technically also - coincides with the message ID that started the thread that was created. - It may *not* point to an existing or valid thread or message. - slowmode_delay: :class:`int` - The number of seconds a member must wait between creating threads - in this forum. A value of `0` denotes that it is disabled. - Bots and users with :attr:`~Permissions.manage_channels` or - :attr:`~Permissions.manage_messages` bypass slowmode. - nsfw: :class:`bool` - If the forum is marked as "not safe for work" or "age restricted". - default_auto_archive_duration: :class:`int` - The default auto archive duration in minutes for threads created in this forum. - """ - - __slots__ = ( - 'name', - 'id', - 'guild', - 'topic', - '_state', - '_flags', - 'nsfw', - 'category_id', - 'position', - 'slowmode_delay', - '_overwrites', - 'last_message_id', - 'default_auto_archive_duration', - ) - - def __init__(self, *, state: ConnectionState, guild: Guild, data: ForumChannelPayload): - self._state: ConnectionState = state - self.id: int = int(data['id']) - self._update(guild, data) - - def __repr__(self) -> str: - attrs = [ - ('id', self.id), - ('name', self.name), - ('position', self.position), - ('nsfw', self.nsfw), - ('category_id', self.category_id), - ] - joined = ' '.join('%s=%r' % t for t in attrs) - return f'<{self.__class__.__name__} {joined}>' - - def _update(self, guild: Guild, data: ForumChannelPayload) -> None: - self.guild: Guild = guild - self.name: str = data['name'] - self.category_id: Optional[int] = utils._get_as_snowflake(data, 'parent_id') - self.topic: Optional[str] = data.get('topic') - self.position: int = data['position'] - self.nsfw: bool = data.get('nsfw', False) - self.slowmode_delay: int = data.get('rate_limit_per_user', 0) - self.default_auto_archive_duration: ThreadArchiveDuration = data.get('default_auto_archive_duration', 1440) - self.last_message_id: Optional[int] = utils._get_as_snowflake(data, 'last_message_id') - self._fill_overwrites(data) - - @property - def type(self) -> Literal[ChannelType.forum]: - """:class:`ChannelType`: The channel's Discord type.""" - return ChannelType.forum - - @property - def _sorting_bucket(self) -> int: - return ChannelType.text.value - - @property - def _scheduled_event_entity_type(self) -> Optional[EntityType]: - return None - - @utils.copy_doc(discord.abc.GuildChannel.permissions_for) - def permissions_for(self, obj: Union[Member, Role], /) -> Permissions: - base = super().permissions_for(obj) - - # text channels do not have voice related permissions - denied = Permissions.voice() - base.value &= ~denied.value - return base - - @property - def threads(self) -> List[Thread]: - """List[:class:`Thread`]: Returns all the threads that you can see.""" - return [thread for thread in self.guild._threads.values() if thread.parent_id == self.id] - - def is_nsfw(self) -> bool: - """:class:`bool`: Checks if the forum is NSFW.""" - return self.nsfw - - @utils.copy_doc(discord.abc.GuildChannel.clone) - async def clone(self, *, name: Optional[str] = None, reason: Optional[str] = None) -> ForumChannel: - return await self._clone_impl( - {'topic': self.topic, 'nsfw': self.nsfw, 'rate_limit_per_user': self.slowmode_delay}, name=name, reason=reason - ) - - @overload - async def edit(self) -> None: - ... - - @overload - async def edit(self, *, position: int, reason: Optional[str] = ...) -> None: - ... - - @overload - async def edit( - self, - *, - reason: Optional[str] = ..., - name: str = ..., - topic: str = ..., - position: int = ..., - nsfw: bool = ..., - sync_permissions: bool = ..., - category: Optional[CategoryChannel] = ..., - slowmode_delay: int = ..., - default_auto_archive_duration: ThreadArchiveDuration = ..., - type: ChannelType = ..., - overwrites: Mapping[OverwriteKeyT, PermissionOverwrite] = ..., - ) -> ForumChannel: - ... - - async def edit(self, *, reason: Optional[str] = None, **options: Any) -> Optional[ForumChannel]: - """|coro| - - Edits the forum. - - You must have the :attr:`~Permissions.manage_channels` permission to - use this. - - Parameters - ---------- - name: :class:`str` - The new forum name. - topic: :class:`str` - The new forum's topic. - position: :class:`int` - The new forum's position. - nsfw: :class:`bool` - To mark the forum as NSFW or not. - sync_permissions: :class:`bool` - Whether to sync permissions with the forum's new or pre-existing - category. Defaults to ``False``. - category: Optional[:class:`CategoryChannel`] - The new category for this forum. Can be ``None`` to remove the - category. - slowmode_delay: :class:`int` - Specifies the slowmode rate limit for user in this forum, in seconds. - A value of `0` disables slowmode. The maximum value possible is `21600`. - type: :class:`ChannelType` - Change the type of this text forum. Currently, only conversion between - :attr:`ChannelType.text` and :attr:`ChannelType.news` is supported. This - is only available to guilds that contain ``NEWS`` in :attr:`Guild.features`. - reason: Optional[:class:`str`] - The reason for editing this forum. Shows up on the audit log. - overwrites: :class:`Mapping` - A :class:`Mapping` of target (either a role or a member) to - :class:`PermissionOverwrite` to apply to the forum. - default_auto_archive_duration: :class:`int` - The new default auto archive duration in minutes for threads created in this channel. - Must be one of ``60``, ``1440``, ``4320``, or ``10080``. - - Raises - ------ - ValueError - The new ``position`` is less than 0 or greater than the number of channels. - TypeError - The permission overwrite information is not in proper form. - Forbidden - You do not have permissions to edit the forum. - HTTPException - Editing the forum failed. - - Returns - -------- - Optional[:class:`.ForumChannel`] - The newly edited forum channel. If the edit was only positional - then ``None`` is returned instead. - """ - - payload = await self._edit(options, reason=reason) - if payload is not None: - # the payload will always be the proper channel payload - return self.__class__(state=self._state, guild=self.guild, data=payload) # type: ignore - - async def create_thread( - self, - *, - name: str, - auto_archive_duration: ThreadArchiveDuration = MISSING, - slowmode_delay: Optional[int] = None, - content: Optional[str] = None, - tts: bool = False, - embed: Embed = MISSING, - embeds: Sequence[Embed] = MISSING, - file: File = MISSING, - files: Sequence[File] = MISSING, - stickers: Sequence[Union[GuildSticker, StickerItem]] = MISSING, - allowed_mentions: AllowedMentions = MISSING, - mention_author: bool = MISSING, - view: View = MISSING, - suppress_embeds: bool = False, - reason: Optional[str] = None, - ) -> ThreadWithMessage: - """|coro| - - Creates a thread in this forum. - - This thread is a public thread with the initial message given. Currently in order - to start a thread in this forum, the user needs :attr:`~discord.Permissions.send_messages`. - - Parameters - ----------- - name: :class:`str` - The name of the thread. - auto_archive_duration: :class:`int` - The duration in minutes before a thread is automatically archived for inactivity. - If not provided, the channel's default auto archive duration is used. - slowmode_delay: Optional[:class:`int`] - Specifies the slowmode rate limit for user in this channel, in seconds. - The maximum value possible is `21600`. By default no slowmode rate limit - if this is ``None``. - content: Optional[:class:`str`] - The content of the message to send with the thread. - tts: :class:`bool` - Indicates if the message should be sent using text-to-speech. - embed: :class:`~discord.Embed` - The rich embed for the content. - embeds: List[:class:`~discord.Embed`] - A list of embeds to upload. Must be a maximum of 10. - file: :class:`~discord.File` - The file to upload. - files: List[:class:`~discord.File`] - A list of files to upload. Must be a maximum of 10. - allowed_mentions: :class:`~discord.AllowedMentions` - Controls the mentions being processed in this message. If this is - passed, then the object is merged with :attr:`~discord.Client.allowed_mentions`. - The merging behaviour only overrides attributes that have been explicitly passed - to the object, otherwise it uses the attributes set in :attr:`~discord.Client.allowed_mentions`. - If no object is passed at all then the defaults given by :attr:`~discord.Client.allowed_mentions` - are used instead. - mention_author: :class:`bool` - If set, overrides the :attr:`~discord.AllowedMentions.replied_user` attribute of ``allowed_mentions``. - view: :class:`discord.ui.View` - A Discord UI View to add to the message. - stickers: Sequence[Union[:class:`~discord.GuildSticker`, :class:`~discord.StickerItem`]] - A list of stickers to upload. Must be a maximum of 3. - suppress_embeds: :class:`bool` - Whether to suppress embeds for the message. This sends the message without any embeds if set to ``True``. - reason: :class:`str` - The reason for creating a new thread. Shows up on the audit log. - - Raises - ------- - Forbidden - You do not have permissions to create a thread. - HTTPException - Starting the thread failed. - ValueError - The ``files`` or ``embeds`` list is not of the appropriate size. - TypeError - You specified both ``file`` and ``files``, - or you specified both ``embed`` and ``embeds``. - - Returns - -------- - Tuple[:class:`Thread`, :class:`Message`] - The created thread with the created message. - This is also accessible as a namedtuple with ``thread`` and ``message`` fields. - """ - - state = self._state - previous_allowed_mention = state.allowed_mentions - if stickers is MISSING: - sticker_ids = MISSING - else: - sticker_ids: SnowflakeList = [s.id for s in stickers] - - if view and not hasattr(view, '__discord_ui_view__'): - raise TypeError(f'view parameter must be View not {view.__class__!r}') - - if suppress_embeds: - from .message import MessageFlags # circular import - - flags = MessageFlags._from_value(4) - else: - flags = MISSING - - content = str(content) if content else MISSING - - channel_payload = { - 'name': name, - 'auto_archive_duration': auto_archive_duration or self.default_auto_archive_duration, - 'rate_limit_per_user': slowmode_delay, - 'type': 11, # Private threads don't seem to be allowed - } - - with handle_message_parameters( - content=content, - tts=tts, - file=file, - files=files, - embed=embed, - embeds=embeds, - allowed_mentions=allowed_mentions, - previous_allowed_mentions=previous_allowed_mention, - mention_author=None if mention_author is MISSING else mention_author, - stickers=sticker_ids, - view=view, - flags=flags, - channel_payload=channel_payload, - ) as params: - # Circular import - from .message import Message - - data = await state.http.start_thread_in_forum(self.id, params=params, reason=reason) - thread = Thread(guild=self.guild, state=self._state, data=data) - message = Message(state=self._state, channel=thread, data=data['message']) - if view: - self._state.store_view(view, message.id) - - return ThreadWithMessage(thread=thread, message=message) - - async def webhooks(self) -> List[Webhook]: - """|coro| - - Gets the list of webhooks from this channel. - - Requires :attr:`~.Permissions.manage_webhooks` permissions. - - Raises - ------- - Forbidden - You don't have permissions to get the webhooks. - - Returns - -------- - List[:class:`Webhook`] - The webhooks for this channel. - """ - - from .webhook import Webhook - - data = await self._state.http.channel_webhooks(self.id) - return [Webhook.from_state(d, state=self._state) for d in data] - - async def create_webhook(self, *, name: str, avatar: Optional[bytes] = None, reason: Optional[str] = None) -> Webhook: - """|coro| - - Creates a webhook for this channel. - - Requires :attr:`~.Permissions.manage_webhooks` permissions. - - Parameters - ------------- - name: :class:`str` - The webhook's name. - avatar: Optional[:class:`bytes`] - A :term:`py:bytes-like object` representing the webhook's default avatar. - This operates similarly to :meth:`~ClientUser.edit`. - reason: Optional[:class:`str`] - The reason for creating this webhook. Shows up in the audit logs. - - Raises - ------- - HTTPException - Creating the webhook failed. - Forbidden - You do not have permissions to create a webhook. - - Returns - -------- - :class:`Webhook` - The created webhook. - """ - - from .webhook import Webhook - - if avatar is not None: - avatar = utils._bytes_to_base64_data(avatar) # type: ignore # Silence reassignment error - - data = await self._state.http.create_webhook(self.id, name=str(name), avatar=avatar, reason=reason) - return Webhook.from_state(data, state=self._state) - - -class DMChannel(discord.abc.Messageable, discord.abc.PrivateChannel, Hashable): - """Represents a Discord direct message channel. - - .. container:: operations - - .. describe:: x == y - - Checks if two channels are equal. - - .. describe:: x != y - - Checks if two channels are not equal. - - .. describe:: hash(x) - - Returns the channel's hash. - - .. describe:: str(x) - - Returns a string representation of the channel - - Attributes - ---------- - recipient: Optional[:class:`User`] - The user you are participating with in the direct message channel. - If this channel is received through the gateway, the recipient information - may not be always available. - me: :class:`ClientUser` - The user presenting yourself. - id: :class:`int` - The direct message channel ID. - """ - - __slots__ = ('id', 'recipient', 'me', '_state') - - def __init__(self, *, me: ClientUser, state: ConnectionState, data: DMChannelPayload): - self._state: ConnectionState = state - self.recipient: Optional[User] = state.store_user(data['recipients'][0]) - self.me: ClientUser = me - self.id: int = int(data['id']) - - async def _get_channel(self) -> Self: - return self - - def __str__(self) -> str: - if self.recipient: - return f'Direct Message with {self.recipient}' - return 'Direct Message with Unknown User' - - def __repr__(self) -> str: - return f'' - - @classmethod - def _from_message(cls, state: ConnectionState, channel_id: int) -> Self: - self = cls.__new__(cls) - self._state = state - self.id = channel_id - self.recipient = None - # state.user won't be None here - self.me = state.user # type: ignore - return self - - @property - def type(self) -> Literal[ChannelType.private]: - """:class:`ChannelType`: The channel's Discord type.""" - return ChannelType.private - - @property - def guild(self) -> Optional[Guild]: - """Optional[:class:`Guild`]: The guild this DM channel belongs to. Always ``None``. - - This is mainly provided for compatibility purposes in duck typing. - - .. versionadded:: 2.0 - """ - return None - - @property - def jump_url(self) -> str: - """:class:`str`: Returns a URL that allows the client to jump to the channel. - - .. versionadded:: 2.0 - """ - return f'https://discord.com/channels/@me/{self.id}' - - @property - def created_at(self) -> datetime.datetime: - """:class:`datetime.datetime`: Returns the direct message channel's creation time in UTC.""" - return utils.snowflake_time(self.id) - - def permissions_for(self, obj: Any = None, /) -> Permissions: - """Handles permission resolution for a :class:`User`. - - This function is there for compatibility with other channel types. - - Actual direct messages do not really have the concept of permissions. - - This returns all the Text related permissions set to ``True`` except: - - - :attr:`~Permissions.send_tts_messages`: You cannot send TTS messages in a DM. - - :attr:`~Permissions.manage_messages`: You cannot delete others messages in a DM. - - .. versionchanged:: 2.0 - - ``obj`` parameter is now positional-only. - - Parameters - ----------- - obj: :class:`User` - The user to check permissions for. This parameter is ignored - but kept for compatibility with other ``permissions_for`` methods. - - Returns - -------- - :class:`Permissions` - The resolved permissions. - """ - return Permissions._dm_permissions() - - def get_partial_message(self, message_id: int, /) -> PartialMessage: - """Creates a :class:`PartialMessage` from the message ID. - - This is useful if you want to work with a message and only have its ID without - doing an unnecessary API call. - - .. versionadded:: 1.6 - - .. versionchanged:: 2.0 - - ``message_id`` parameter is now positional-only. - - Parameters - ------------ - message_id: :class:`int` - The message ID to create a partial message for. - - Returns - --------- - :class:`PartialMessage` - The partial message. - """ - - from .message import PartialMessage - - return PartialMessage(channel=self, id=message_id) - - -class GroupChannel(discord.abc.Messageable, discord.abc.PrivateChannel, Hashable): - """Represents a Discord group channel. - - .. container:: operations - - .. describe:: x == y - - Checks if two channels are equal. - - .. describe:: x != y - - Checks if two channels are not equal. - - .. describe:: hash(x) - - Returns the channel's hash. - - .. describe:: str(x) - - Returns a string representation of the channel - - Attributes - ---------- - recipients: List[:class:`User`] - The users you are participating with in the group channel. - me: :class:`ClientUser` - The user presenting yourself. - id: :class:`int` - The group channel ID. - owner: Optional[:class:`User`] - The user that owns the group channel. - owner_id: :class:`int` - The owner ID that owns the group channel. - - .. versionadded:: 2.0 - name: Optional[:class:`str`] - The group channel's name if provided. - """ - - __slots__ = ('id', 'recipients', 'owner_id', 'owner', '_icon', 'name', 'me', '_state') - - def __init__(self, *, me: ClientUser, state: ConnectionState, data: GroupChannelPayload): - self._state: ConnectionState = state - self.id: int = int(data['id']) - self.me: ClientUser = me - self._update_group(data) - - def _update_group(self, data: GroupChannelPayload) -> None: - self.owner_id: Optional[int] = utils._get_as_snowflake(data, 'owner_id') - self._icon: Optional[str] = data.get('icon') - self.name: Optional[str] = data.get('name') - self.recipients: List[User] = [self._state.store_user(u) for u in data.get('recipients', [])] - - self.owner: Optional[BaseUser] - if self.owner_id == self.me.id: - self.owner = self.me - else: - self.owner = utils.find(lambda u: u.id == self.owner_id, self.recipients) - - async def _get_channel(self) -> Self: - return self - - def __str__(self) -> str: - if self.name: - return self.name - - if len(self.recipients) == 0: - return 'Unnamed' - - return ', '.join(map(lambda x: x.name, self.recipients)) - - def __repr__(self) -> str: - return f'' - - @property - def type(self) -> Literal[ChannelType.group]: - """:class:`ChannelType`: The channel's Discord type.""" - return ChannelType.group - - @property - def guild(self) -> Optional[Guild]: - """Optional[:class:`Guild`]: The guild this group channel belongs to. Always ``None``. - - This is mainly provided for compatibility purposes in duck typing. - - .. versionadded:: 2.0 - """ - return None - - @property - def icon(self) -> Optional[Asset]: - """Optional[:class:`Asset`]: Returns the channel's icon asset if available.""" - if self._icon is None: - return None - return Asset._from_icon(self._state, self.id, self._icon, path='channel') - - @property - def created_at(self) -> datetime.datetime: - """:class:`datetime.datetime`: Returns the channel's creation time in UTC.""" - return utils.snowflake_time(self.id) - - @property - def jump_url(self) -> str: - """:class:`str`: Returns a URL that allows the client to jump to the channel. - - .. versionadded:: 2.0 - """ - return f'https://discord.com/channels/@me/{self.id}' - - def permissions_for(self, obj: Snowflake, /) -> Permissions: - """Handles permission resolution for a :class:`User`. - - This function is there for compatibility with other channel types. - - Actual direct messages do not really have the concept of permissions. - - This returns all the Text related permissions set to ``True`` except: - - - :attr:`~Permissions.send_tts_messages`: You cannot send TTS messages in a DM. - - :attr:`~Permissions.manage_messages`: You cannot delete others messages in a DM. - - This also checks the kick_members permission if the user is the owner. - - .. versionchanged:: 2.0 - - ``obj`` parameter is now positional-only. - - Parameters - ----------- - obj: :class:`~discord.abc.Snowflake` - The user to check permissions for. - - Returns - -------- - :class:`Permissions` - The resolved permissions for the user. - """ - - base = Permissions._dm_permissions() - base.mention_everyone = True - - if obj.id == self.owner_id: - base.kick_members = True - - return base - - async def leave(self) -> None: - """|coro| - - Leave the group. - - If you are the only one in the group, this deletes it as well. - - Raises - ------- - HTTPException - Leaving the group failed. - """ - - await self._state.http.leave_group(self.id) - - -class PartialMessageable(discord.abc.Messageable, Hashable): - """Represents a partial messageable to aid with working messageable channels when - only a channel ID is present. - - The only way to construct this class is through :meth:`Client.get_partial_messageable`. - - Note that this class is trimmed down and has no rich attributes. - - .. versionadded:: 2.0 - - .. container:: operations - - .. describe:: x == y - - Checks if two partial messageables are equal. - - .. describe:: x != y - - Checks if two partial messageables are not equal. - - .. describe:: hash(x) - - Returns the partial messageable's hash. - - Attributes - ----------- - id: :class:`int` - The channel ID associated with this partial messageable. - guild_id: Optional[:class:`int`] - The guild ID associated with this partial messageable. - type: Optional[:class:`ChannelType`] - The channel type associated with this partial messageable, if given. - """ - - def __init__(self, state: ConnectionState, id: int, guild_id: Optional[int] = None, type: Optional[ChannelType] = None): - self._state: ConnectionState = state - self.id: int = id - self.guild_id: Optional[int] = guild_id - self.type: Optional[ChannelType] = type - - def __repr__(self) -> str: - return f'<{self.__class__.__name__} id={self.id} type={self.type!r}>' - - async def _get_channel(self) -> PartialMessageable: - return self - - @property - def guild(self) -> Optional[Guild]: - """Optional[:class:`Guild`]: The guild this partial messageable is in.""" - return self._state._get_guild(self.guild_id) - - @property - def jump_url(self) -> str: - """:class:`str`: Returns a URL that allows the client to jump to the channel.""" - if self.guild_id is None: - return f'https://discord.com/channels/@me/{self.id}' - return f'https://discord.com/channels/{self.guild_id}/{self.id}' - - @property - def created_at(self) -> datetime.datetime: - """:class:`datetime.datetime`: Returns the channel's creation time in UTC.""" - return utils.snowflake_time(self.id) - - def permissions_for(self, obj: Any = None, /) -> Permissions: - """Handles permission resolution for a :class:`User`. - - This function is there for compatibility with other channel types. - - Since partial messageables cannot reasonably have the concept of - permissions, this will always return :meth:`Permissions.none`. - - Parameters - ----------- - obj: :class:`User` - The user to check permissions for. This parameter is ignored - but kept for compatibility with other ``permissions_for`` methods. - - Returns - -------- - :class:`Permissions` - The resolved permissions. - """ - - return Permissions.none() - - def get_partial_message(self, message_id: int, /) -> PartialMessage: - """Creates a :class:`PartialMessage` from the message ID. - - This is useful if you want to work with a message and only have its ID without - doing an unnecessary API call. - - Parameters - ------------ - message_id: :class:`int` - The message ID to create a partial message for. - - Returns - --------- - :class:`PartialMessage` - The partial message. - """ - - from .message import PartialMessage - - return PartialMessage(channel=self, id=message_id) - - -def _guild_channel_factory(channel_type: int): - value = try_enum(ChannelType, channel_type) - if value is ChannelType.text: - return TextChannel, value - elif value is ChannelType.voice: - return VoiceChannel, value - elif value is ChannelType.category: - return CategoryChannel, value - elif value is ChannelType.news: - return TextChannel, value - elif value is ChannelType.stage_voice: - return StageChannel, value - elif value is ChannelType.forum: - return ForumChannel, value - else: - return None, value - - -def _channel_factory(channel_type: int): - cls, value = _guild_channel_factory(channel_type) - if value is ChannelType.private: - return DMChannel, value - elif value is ChannelType.group: - return GroupChannel, value - else: - return cls, value - - -def _threaded_channel_factory(channel_type: int): - cls, value = _channel_factory(channel_type) - if value in (ChannelType.private_thread, ChannelType.public_thread, ChannelType.news_thread): - return Thread, value - return cls, value - - -def _threaded_guild_channel_factory(channel_type: int): - cls, value = _guild_channel_factory(channel_type) - if value in (ChannelType.private_thread, ChannelType.public_thread, ChannelType.news_thread): - return Thread, value - return cls, value diff --git a/.venv/Lib/site-packages/discord/client.py b/.venv/Lib/site-packages/discord/client.py deleted file mode 100644 index 6415d35..0000000 --- a/.venv/Lib/site-packages/discord/client.py +++ /dev/null @@ -1,1980 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations - -import asyncio -import datetime -import logging -from typing import ( - Any, - AsyncIterator, - Callable, - Coroutine, - Dict, - Generator, - List, - Optional, - Sequence, - TYPE_CHECKING, - Tuple, - Type, - TypeVar, - Union, -) - -import aiohttp - -from .user import User, ClientUser -from .invite import Invite -from .template import Template -from .widget import Widget -from .guild import Guild -from .emoji import Emoji -from .channel import _threaded_channel_factory, PartialMessageable -from .enums import ChannelType -from .mentions import AllowedMentions -from .errors import * -from .enums import Status -from .flags import ApplicationFlags, Intents -from .gateway import * -from .activity import ActivityTypes, BaseActivity, create_activity -from .voice_client import VoiceClient -from .http import HTTPClient -from .state import ConnectionState -from . import utils -from .utils import MISSING, time_snowflake -from .object import Object -from .backoff import ExponentialBackoff -from .webhook import Webhook -from .appinfo import AppInfo -from .ui.view import View -from .stage_instance import StageInstance -from .threads import Thread -from .sticker import GuildSticker, StandardSticker, StickerPack, _sticker_factory - -if TYPE_CHECKING: - from typing_extensions import Self - from types import TracebackType - from .types.guild import Guild as GuildPayload - from .abc import SnowflakeTime, Snowflake, PrivateChannel - from .guild import GuildChannel - from .channel import DMChannel - from .message import Message - from .member import Member - from .voice_client import VoiceProtocol - -# fmt: off -__all__ = ( - 'Client', -) -# fmt: on - -Coro = TypeVar('Coro', bound=Callable[..., Coroutine[Any, Any, Any]]) - -_log = logging.getLogger(__name__) - - -class _LoopSentinel: - __slots__ = () - - def __getattr__(self, attr: str) -> None: - msg = ( - 'loop attribute cannot be accessed in non-async contexts. ' - 'Consider using either an asynchronous main function and passing it to asyncio.run or ' - 'using asynchronous initialisation hooks such as Client.setup_hook' - ) - raise AttributeError(msg) - - -_loop: Any = _LoopSentinel() - - -class Client: - r"""Represents a client connection that connects to Discord. - This class is used to interact with the Discord WebSocket and API. - - .. container:: operations - - .. describe:: async with x - - Asynchronously initialises the client and automatically cleans up. - - .. versionadded:: 2.0 - - A number of options can be passed to the :class:`Client`. - - Parameters - ----------- - max_messages: Optional[:class:`int`] - The maximum number of messages to store in the internal message cache. - This defaults to ``1000``. Passing in ``None`` disables the message cache. - - .. versionchanged:: 1.3 - Allow disabling the message cache and change the default size to ``1000``. - proxy: Optional[:class:`str`] - Proxy URL. - proxy_auth: Optional[:class:`aiohttp.BasicAuth`] - An object that represents proxy HTTP Basic Authorization. - shard_id: Optional[:class:`int`] - Integer starting at ``0`` and less than :attr:`.shard_count`. - shard_count: Optional[:class:`int`] - The total number of shards. - application_id: :class:`int` - The client's application ID. - intents: :class:`Intents` - The intents that you want to enable for the session. This is a way of - disabling and enabling certain gateway events from triggering and being sent. - - .. versionadded:: 1.5 - - .. versionchanged:: 2.0 - Parameter is now required. - member_cache_flags: :class:`MemberCacheFlags` - Allows for finer control over how the library caches members. - If not given, defaults to cache as much as possible with the - currently selected intents. - - .. versionadded:: 1.5 - chunk_guilds_at_startup: :class:`bool` - Indicates if :func:`.on_ready` should be delayed to chunk all guilds - at start-up if necessary. This operation is incredibly slow for large - amounts of guilds. The default is ``True`` if :attr:`Intents.members` - is ``True``. - - .. versionadded:: 1.5 - status: Optional[:class:`.Status`] - A status to start your presence with upon logging on to Discord. - activity: Optional[:class:`.BaseActivity`] - An activity to start your presence with upon logging on to Discord. - allowed_mentions: Optional[:class:`AllowedMentions`] - Control how the client handles mentions by default on every message sent. - - .. versionadded:: 1.4 - heartbeat_timeout: :class:`float` - The maximum numbers of seconds before timing out and restarting the - WebSocket in the case of not receiving a HEARTBEAT_ACK. Useful if - processing the initial packets take too long to the point of disconnecting - you. The default timeout is 60 seconds. - guild_ready_timeout: :class:`float` - The maximum number of seconds to wait for the GUILD_CREATE stream to end before - preparing the member cache and firing READY. The default timeout is 2 seconds. - - .. versionadded:: 1.4 - assume_unsync_clock: :class:`bool` - Whether to assume the system clock is unsynced. This applies to the ratelimit handling - code. If this is set to ``True``, the default, then the library uses the time to reset - a rate limit bucket given by Discord. If this is ``False`` then your system clock is - used to calculate how long to sleep for. If this is set to ``False`` it is recommended to - sync your system clock to Google's NTP server. - - .. versionadded:: 1.3 - enable_debug_events: :class:`bool` - Whether to enable events that are useful only for debugging gateway related information. - - Right now this involves :func:`on_socket_raw_receive` and :func:`on_socket_raw_send`. If - this is ``False`` then those events will not be dispatched (due to performance considerations). - To enable these events, this must be set to ``True``. Defaults to ``False``. - - .. versionadded:: 2.0 - http_trace: :class:`aiohttp.TraceConfig` - The trace configuration to use for tracking HTTP requests the library does using ``aiohttp``. - This allows you to check requests the library is using. For more information, check the - `aiohttp documentation `_. - - .. versionadded:: 2.0 - max_ratelimit_timeout: Optional[:class:`float`] - The maximum number of seconds to wait when a non-global rate limit is encountered. - If a request requires sleeping for more than the seconds passed in, then - :exc:`~discord.RateLimited` will be raised. By default, there is no timeout limit. - In order to prevent misuse and unnecessary bans, the minimum value this can be - set to is ``30.0`` seconds. - - .. versionadded:: 2.0 - - Attributes - ----------- - ws - The websocket gateway the client is currently connected to. Could be ``None``. - """ - - def __init__(self, *, intents: Intents, **options: Any) -> None: - self.loop: asyncio.AbstractEventLoop = _loop - # self.ws is set in the connect method - self.ws: DiscordWebSocket = None # type: ignore - self._listeners: Dict[str, List[Tuple[asyncio.Future, Callable[..., bool]]]] = {} - self.shard_id: Optional[int] = options.get('shard_id') - self.shard_count: Optional[int] = options.get('shard_count') - - proxy: Optional[str] = options.pop('proxy', None) - proxy_auth: Optional[aiohttp.BasicAuth] = options.pop('proxy_auth', None) - unsync_clock: bool = options.pop('assume_unsync_clock', True) - http_trace: Optional[aiohttp.TraceConfig] = options.pop('http_trace', None) - max_ratelimit_timeout: Optional[float] = options.pop('max_ratelimit_timeout', None) - self.http: HTTPClient = HTTPClient( - self.loop, - proxy=proxy, - proxy_auth=proxy_auth, - unsync_clock=unsync_clock, - http_trace=http_trace, - max_ratelimit_timeout=max_ratelimit_timeout, - ) - - self._handlers: Dict[str, Callable[..., None]] = { - 'ready': self._handle_ready, - } - - self._hooks: Dict[str, Callable[..., Coroutine[Any, Any, Any]]] = { - 'before_identify': self._call_before_identify_hook, - } - - self._enable_debug_events: bool = options.pop('enable_debug_events', False) - self._connection: ConnectionState = self._get_state(intents=intents, **options) - self._connection.shard_count = self.shard_count - self._closed: bool = False - self._ready: asyncio.Event = MISSING - self._application: Optional[AppInfo] = None - self._connection._get_websocket = self._get_websocket - self._connection._get_client = lambda: self - - if VoiceClient.warn_nacl: - VoiceClient.warn_nacl = False - _log.warning("PyNaCl is not installed, voice will NOT be supported") - - async def __aenter__(self) -> Self: - await self._async_setup_hook() - return self - - async def __aexit__( - self, - exc_type: Optional[Type[BaseException]], - exc_value: Optional[BaseException], - traceback: Optional[TracebackType], - ) -> None: - if not self.is_closed(): - await self.close() - - # internals - - def _get_websocket(self, guild_id: Optional[int] = None, *, shard_id: Optional[int] = None) -> DiscordWebSocket: - return self.ws - - def _get_state(self, **options: Any) -> ConnectionState: - return ConnectionState(dispatch=self.dispatch, handlers=self._handlers, hooks=self._hooks, http=self.http, **options) - - def _handle_ready(self) -> None: - self._ready.set() - - @property - def latency(self) -> float: - """:class:`float`: Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds. - - This could be referred to as the Discord WebSocket protocol latency. - """ - ws = self.ws - return float('nan') if not ws else ws.latency - - def is_ws_ratelimited(self) -> bool: - """:class:`bool`: Whether the websocket is currently rate limited. - - This can be useful to know when deciding whether you should query members - using HTTP or via the gateway. - - .. versionadded:: 1.6 - """ - if self.ws: - return self.ws.is_ratelimited() - return False - - @property - def user(self) -> Optional[ClientUser]: - """Optional[:class:`.ClientUser`]: Represents the connected client. ``None`` if not logged in.""" - return self._connection.user - - @property - def guilds(self) -> Sequence[Guild]: - """Sequence[:class:`.Guild`]: The guilds that the connected client is a member of.""" - return self._connection.guilds - - @property - def emojis(self) -> Sequence[Emoji]: - """Sequence[:class:`.Emoji`]: The emojis that the connected client has.""" - return self._connection.emojis - - @property - def stickers(self) -> Sequence[GuildSticker]: - """Sequence[:class:`.GuildSticker`]: The stickers that the connected client has. - - .. versionadded:: 2.0 - """ - return self._connection.stickers - - @property - def cached_messages(self) -> Sequence[Message]: - """Sequence[:class:`.Message`]: Read-only list of messages the connected client has cached. - - .. versionadded:: 1.1 - """ - return utils.SequenceProxy(self._connection._messages or []) - - @property - def private_channels(self) -> Sequence[PrivateChannel]: - """Sequence[:class:`.abc.PrivateChannel`]: The private channels that the connected client is participating on. - - .. note:: - - This returns only up to 128 most recent private channels due to an internal working - on how Discord deals with private channels. - """ - return self._connection.private_channels - - @property - def voice_clients(self) -> List[VoiceProtocol]: - """List[:class:`.VoiceProtocol`]: Represents a list of voice connections. - - These are usually :class:`.VoiceClient` instances. - """ - return self._connection.voice_clients - - @property - def application_id(self) -> Optional[int]: - """Optional[:class:`int`]: The client's application ID. - - If this is not passed via ``__init__`` then this is retrieved - through the gateway when an event contains the data or after a call - to :meth:`~discord.Client.login`. Usually after :func:`~discord.on_connect` - is called. - - .. versionadded:: 2.0 - """ - return self._connection.application_id - - @property - def application_flags(self) -> ApplicationFlags: - """:class:`~discord.ApplicationFlags`: The client's application flags. - - .. versionadded:: 2.0 - """ - return self._connection.application_flags - - @property - def application(self) -> Optional[AppInfo]: - """Optional[:class:`~discord.AppInfo`]: The client's application info. - - This is retrieved on :meth:`~discord.Client.login` and is not updated - afterwards. This allows populating the application_id without requiring a - gateway connection. - - This is ``None`` if accessed before :meth:`~discord.Client.login` is called. - - .. seealso:: The :meth:`~discord.Client.application_info` API call - - .. versionadded:: 2.0 - """ - return self._application - - def is_ready(self) -> bool: - """:class:`bool`: Specifies if the client's internal cache is ready for use.""" - return self._ready is not MISSING and self._ready.is_set() - - async def _run_event( - self, - coro: Callable[..., Coroutine[Any, Any, Any]], - event_name: str, - *args: Any, - **kwargs: Any, - ) -> None: - try: - await coro(*args, **kwargs) - except asyncio.CancelledError: - pass - except Exception: - try: - await self.on_error(event_name, *args, **kwargs) - except asyncio.CancelledError: - pass - - def _schedule_event( - self, - coro: Callable[..., Coroutine[Any, Any, Any]], - event_name: str, - *args: Any, - **kwargs: Any, - ) -> asyncio.Task: - wrapped = self._run_event(coro, event_name, *args, **kwargs) - # Schedules the task - return self.loop.create_task(wrapped, name=f'discord.py: {event_name}') - - def dispatch(self, event: str, /, *args: Any, **kwargs: Any) -> None: - _log.debug('Dispatching event %s', event) - method = 'on_' + event - - listeners = self._listeners.get(event) - if listeners: - removed = [] - for i, (future, condition) in enumerate(listeners): - if future.cancelled(): - removed.append(i) - continue - - try: - result = condition(*args) - except Exception as exc: - future.set_exception(exc) - removed.append(i) - else: - if result: - if len(args) == 0: - future.set_result(None) - elif len(args) == 1: - future.set_result(args[0]) - else: - future.set_result(args) - removed.append(i) - - if len(removed) == len(listeners): - self._listeners.pop(event) - else: - for idx in reversed(removed): - del listeners[idx] - - try: - coro = getattr(self, method) - except AttributeError: - pass - else: - self._schedule_event(coro, method, *args, **kwargs) - - async def on_error(self, event_method: str, /, *args: Any, **kwargs: Any) -> None: - """|coro| - - The default error handler provided by the client. - - By default this logs to the library logger however it could be - overridden to have a different implementation. - Check :func:`~discord.on_error` for more details. - - .. versionchanged:: 2.0 - - ``event_method`` parameter is now positional-only - and instead of writing to ``sys.stderr`` it logs instead. - """ - _log.exception('Ignoring exception in %s', event_method) - - # hooks - - async def _call_before_identify_hook(self, shard_id: Optional[int], *, initial: bool = False) -> None: - # This hook is an internal hook that actually calls the public one. - # It allows the library to have its own hook without stepping on the - # toes of those who need to override their own hook. - await self.before_identify_hook(shard_id, initial=initial) - - async def before_identify_hook(self, shard_id: Optional[int], *, initial: bool = False) -> None: - """|coro| - - A hook that is called before IDENTIFYing a session. This is useful - if you wish to have more control over the synchronization of multiple - IDENTIFYing clients. - - The default implementation sleeps for 5 seconds. - - .. versionadded:: 1.4 - - Parameters - ------------ - shard_id: :class:`int` - The shard ID that requested being IDENTIFY'd - initial: :class:`bool` - Whether this IDENTIFY is the first initial IDENTIFY. - """ - - if not initial: - await asyncio.sleep(5.0) - - async def _async_setup_hook(self) -> None: - # Called whenever the client needs to initialise asyncio objects with a running loop - loop = asyncio.get_running_loop() - self.loop = loop - self.http.loop = loop - self._connection.loop = loop - - self._ready = asyncio.Event() - - async def setup_hook(self) -> None: - """|coro| - - A coroutine to be called to setup the bot, by default this is blank. - - To perform asynchronous setup after the bot is logged in but before - it has connected to the Websocket, overwrite this coroutine. - - This is only called once, in :meth:`login`, and will be called before - any events are dispatched, making it a better solution than doing such - setup in the :func:`~discord.on_ready` event. - - .. warning:: - - Since this is called *before* the websocket connection is made therefore - anything that waits for the websocket will deadlock, this includes things - like :meth:`wait_for` and :meth:`wait_until_ready`. - - .. versionadded:: 2.0 - """ - pass - - # login state management - - async def login(self, token: str) -> None: - """|coro| - - Logs in the client with the specified credentials and - calls the :meth:`setup_hook`. - - - Parameters - ----------- - token: :class:`str` - The authentication token. Do not prefix this token with - anything as the library will do it for you. - - Raises - ------ - LoginFailure - The wrong credentials are passed. - HTTPException - An unknown HTTP related error occurred, - usually when it isn't 200 or the known incorrect credentials - passing status code. - """ - - _log.info('logging in using static token') - - if self.loop is _loop: - await self._async_setup_hook() - - if not isinstance(token, str): - raise TypeError(f'expected token to be a str, received {token.__class__!r} instead') - token = token.strip() - - data = await self.http.static_login(token) - self._connection.user = ClientUser(state=self._connection, data=data) - self._application = await self.application_info() - if self._connection.application_id is None: - self._connection.application_id = self._application.id - - if not self._connection.application_flags: - self._connection.application_flags = self._application.flags - - await self.setup_hook() - - async def connect(self, *, reconnect: bool = True) -> None: - """|coro| - - Creates a websocket connection and lets the websocket listen - to messages from Discord. This is a loop that runs the entire - event system and miscellaneous aspects of the library. Control - is not resumed until the WebSocket connection is terminated. - - Parameters - ----------- - reconnect: :class:`bool` - If we should attempt reconnecting, either due to internet - failure or a specific failure on Discord's part. Certain - disconnects that lead to bad state will not be handled (such as - invalid sharding payloads or bad tokens). - - Raises - ------- - GatewayNotFound - If the gateway to connect to Discord is not found. Usually if this - is thrown then there is a Discord API outage. - ConnectionClosed - The websocket connection has been terminated. - """ - - backoff = ExponentialBackoff() - ws_params = { - 'initial': True, - 'shard_id': self.shard_id, - } - while not self.is_closed(): - try: - coro = DiscordWebSocket.from_client(self, **ws_params) - self.ws = await asyncio.wait_for(coro, timeout=60.0) - ws_params['initial'] = False - while True: - await self.ws.poll_event() - except ReconnectWebSocket as e: - _log.debug('Got a request to %s the websocket.', e.op) - self.dispatch('disconnect') - ws_params.update(sequence=self.ws.sequence, resume=e.resume, session=self.ws.session_id) - if e.resume: - ws_params['gateway'] = self.ws.gateway - continue - except ( - OSError, - HTTPException, - GatewayNotFound, - ConnectionClosed, - aiohttp.ClientError, - asyncio.TimeoutError, - ) as exc: - - self.dispatch('disconnect') - if not reconnect: - await self.close() - if isinstance(exc, ConnectionClosed) and exc.code == 1000: - # clean close, don't re-raise this - return - raise - - if self.is_closed(): - return - - # If we get connection reset by peer then try to RESUME - if isinstance(exc, OSError) and exc.errno in (54, 10054): - ws_params.update( - sequence=self.ws.sequence, - gateway=self.ws.gateway, - initial=False, - resume=True, - session=self.ws.session_id, - ) - continue - - # We should only get this when an unhandled close code happens, - # such as a clean disconnect (1000) or a bad state (bad token, no sharding, etc) - # sometimes, discord sends us 1000 for unknown reasons so we should reconnect - # regardless and rely on is_closed instead - if isinstance(exc, ConnectionClosed): - if exc.code == 4014: - raise PrivilegedIntentsRequired(exc.shard_id) from None - if exc.code != 1000: - await self.close() - raise - - retry = backoff.delay() - _log.exception("Attempting a reconnect in %.2fs", retry) - await asyncio.sleep(retry) - # Always try to RESUME the connection - # If the connection is not RESUME-able then the gateway will invalidate the session. - # This is apparently what the official Discord client does. - ws_params.update( - sequence=self.ws.sequence, - gateway=self.ws.gateway, - resume=True, - session=self.ws.session_id, - ) - - async def close(self) -> None: - """|coro| - - Closes the connection to Discord. - """ - if self._closed: - return - - self._closed = True - - await self._connection.close() - - if self.ws is not None and self.ws.open: - await self.ws.close(code=1000) - - await self.http.close() - - if self._ready is not MISSING: - self._ready.clear() - - self.loop = MISSING - - def clear(self) -> None: - """Clears the internal state of the bot. - - After this, the bot can be considered "re-opened", i.e. :meth:`is_closed` - and :meth:`is_ready` both return ``False`` along with the bot's internal - cache cleared. - """ - self._closed = False - self._ready.clear() - self._connection.clear() - self.http.clear() - - async def start(self, token: str, *, reconnect: bool = True) -> None: - """|coro| - - A shorthand coroutine for :meth:`login` + :meth:`connect`. - - Parameters - ----------- - token: :class:`str` - The authentication token. Do not prefix this token with - anything as the library will do it for you. - reconnect: :class:`bool` - If we should attempt reconnecting, either due to internet - failure or a specific failure on Discord's part. Certain - disconnects that lead to bad state will not be handled (such as - invalid sharding payloads or bad tokens). - - Raises - ------- - TypeError - An unexpected keyword argument was received. - """ - await self.login(token) - await self.connect(reconnect=reconnect) - - def run( - self, - token: str, - *, - reconnect: bool = True, - log_handler: Optional[logging.Handler] = MISSING, - log_formatter: logging.Formatter = MISSING, - log_level: int = MISSING, - root_logger: bool = False, - ) -> None: - """A blocking call that abstracts away the event loop - initialisation from you. - - If you want more control over the event loop then this - function should not be used. Use :meth:`start` coroutine - or :meth:`connect` + :meth:`login`. - - This function also sets up the logging library to make it easier - for beginners to know what is going on with the library. For more - advanced users, this can be disabled by passing ``None`` to - the ``log_handler`` parameter. - - .. warning:: - - This function must be the last function to call due to the fact that it - is blocking. That means that registration of events or anything being - called after this function call will not execute until it returns. - - Parameters - ----------- - token: :class:`str` - The authentication token. Do not prefix this token with - anything as the library will do it for you. - reconnect: :class:`bool` - If we should attempt reconnecting, either due to internet - failure or a specific failure on Discord's part. Certain - disconnects that lead to bad state will not be handled (such as - invalid sharding payloads or bad tokens). - log_handler: Optional[:class:`logging.Handler`] - The log handler to use for the library's logger. If this is ``None`` - then the library will not set up anything logging related. Logging - will still work if ``None`` is passed, though it is your responsibility - to set it up. - - The default log handler if not provided is :class:`logging.StreamHandler`. - - .. versionadded:: 2.0 - log_formatter: :class:`logging.Formatter` - The formatter to use with the given log handler. If not provided then it - defaults to a colour based logging formatter (if available). - - .. versionadded:: 2.0 - log_level: :class:`int` - The default log level for the library's logger. This is only applied if the - ``log_handler`` parameter is not ``None``. Defaults to ``logging.INFO``. - - .. versionadded:: 2.0 - root_logger: :class:`bool` - Whether to set up the root logger rather than the library logger. - By default, only the library logger (``'discord'``) is set up. If this - is set to ``True`` then the root logger is set up as well. - - Defaults to ``False``. - - .. versionadded:: 2.0 - """ - - async def runner(): - async with self: - await self.start(token, reconnect=reconnect) - - if log_handler is not None: - utils.setup_logging( - handler=log_handler, - formatter=log_formatter, - level=log_level, - root=root_logger, - ) - - try: - asyncio.run(runner()) - except KeyboardInterrupt: - # nothing to do here - # `asyncio.run` handles the loop cleanup - # and `self.start` closes all sockets and the HTTPClient instance. - return - - # properties - - def is_closed(self) -> bool: - """:class:`bool`: Indicates if the websocket connection is closed.""" - return self._closed - - @property - def activity(self) -> Optional[ActivityTypes]: - """Optional[:class:`.BaseActivity`]: The activity being used upon - logging in. - """ - return create_activity(self._connection._activity, self._connection) - - @activity.setter - def activity(self, value: Optional[ActivityTypes]) -> None: - if value is None: - self._connection._activity = None - elif isinstance(value, BaseActivity): - # ConnectionState._activity is typehinted as ActivityPayload, we're passing Dict[str, Any] - self._connection._activity = value.to_dict() # type: ignore - else: - raise TypeError('activity must derive from BaseActivity.') - - @property - def status(self) -> Status: - """:class:`.Status`: - The status being used upon logging on to Discord. - - .. versionadded: 2.0 - """ - if self._connection._status in set(state.value for state in Status): - return Status(self._connection._status) - return Status.online - - @status.setter - def status(self, value: Status) -> None: - if value is Status.offline: - self._connection._status = 'invisible' - elif isinstance(value, Status): - self._connection._status = str(value) - else: - raise TypeError('status must derive from Status.') - - @property - def allowed_mentions(self) -> Optional[AllowedMentions]: - """Optional[:class:`~discord.AllowedMentions`]: The allowed mention configuration. - - .. versionadded:: 1.4 - """ - return self._connection.allowed_mentions - - @allowed_mentions.setter - def allowed_mentions(self, value: Optional[AllowedMentions]) -> None: - if value is None or isinstance(value, AllowedMentions): - self._connection.allowed_mentions = value - else: - raise TypeError(f'allowed_mentions must be AllowedMentions not {value.__class__!r}') - - @property - def intents(self) -> Intents: - """:class:`~discord.Intents`: The intents configured for this connection. - - .. versionadded:: 1.5 - """ - return self._connection.intents - - # helpers/getters - - @property - def users(self) -> List[User]: - """List[:class:`~discord.User`]: Returns a list of all the users the bot can see.""" - return list(self._connection._users.values()) - - def get_channel(self, id: int, /) -> Optional[Union[GuildChannel, Thread, PrivateChannel]]: - """Returns a channel or thread with the given ID. - - .. versionchanged:: 2.0 - - ``id`` parameter is now positional-only. - - Parameters - ----------- - id: :class:`int` - The ID to search for. - - Returns - -------- - Optional[Union[:class:`.abc.GuildChannel`, :class:`.Thread`, :class:`.abc.PrivateChannel`]] - The returned channel or ``None`` if not found. - """ - return self._connection.get_channel(id) # type: ignore # The cache contains all channel types - - def get_partial_messageable( - self, id: int, *, guild_id: Optional[int] = None, type: Optional[ChannelType] = None - ) -> PartialMessageable: - """Returns a partial messageable with the given channel ID. - - This is useful if you have a channel_id but don't want to do an API call - to send messages to it. - - .. versionadded:: 2.0 - - Parameters - ----------- - id: :class:`int` - The channel ID to create a partial messageable for. - guild_id: Optional[:class:`int`] - The optional guild ID to create a partial messageable for. - - This is not required to actually send messages, but it does allow the - :meth:`~discord.PartialMessageable.jump_url` and - :attr:`~discord.PartialMessageable.guild` properties to function properly. - type: Optional[:class:`.ChannelType`] - The underlying channel type for the partial messageable. - - Returns - -------- - :class:`.PartialMessageable` - The partial messageable - """ - return PartialMessageable(state=self._connection, id=id, guild_id=guild_id, type=type) - - def get_stage_instance(self, id: int, /) -> Optional[StageInstance]: - """Returns a stage instance with the given stage channel ID. - - .. versionadded:: 2.0 - - Parameters - ----------- - id: :class:`int` - The ID to search for. - - Returns - -------- - Optional[:class:`.StageInstance`] - The stage instance or ``None`` if not found. - """ - from .channel import StageChannel - - channel = self._connection.get_channel(id) - - if isinstance(channel, StageChannel): - return channel.instance - - def get_guild(self, id: int, /) -> Optional[Guild]: - """Returns a guild with the given ID. - - .. versionchanged:: 2.0 - - ``id`` parameter is now positional-only. - - Parameters - ----------- - id: :class:`int` - The ID to search for. - - Returns - -------- - Optional[:class:`.Guild`] - The guild or ``None`` if not found. - """ - return self._connection._get_guild(id) - - def get_user(self, id: int, /) -> Optional[User]: - """Returns a user with the given ID. - - .. versionchanged:: 2.0 - - ``id`` parameter is now positional-only. - - Parameters - ----------- - id: :class:`int` - The ID to search for. - - Returns - -------- - Optional[:class:`~discord.User`] - The user or ``None`` if not found. - """ - return self._connection.get_user(id) - - def get_emoji(self, id: int, /) -> Optional[Emoji]: - """Returns an emoji with the given ID. - - .. versionchanged:: 2.0 - - ``id`` parameter is now positional-only. - - Parameters - ----------- - id: :class:`int` - The ID to search for. - - Returns - -------- - Optional[:class:`.Emoji`] - The custom emoji or ``None`` if not found. - """ - return self._connection.get_emoji(id) - - def get_sticker(self, id: int, /) -> Optional[GuildSticker]: - """Returns a guild sticker with the given ID. - - .. versionadded:: 2.0 - - .. note:: - - To retrieve standard stickers, use :meth:`.fetch_sticker`. - or :meth:`.fetch_premium_sticker_packs`. - - Returns - -------- - Optional[:class:`.GuildSticker`] - The sticker or ``None`` if not found. - """ - return self._connection.get_sticker(id) - - def get_all_channels(self) -> Generator[GuildChannel, None, None]: - """A generator that retrieves every :class:`.abc.GuildChannel` the client can 'access'. - - This is equivalent to: :: - - for guild in client.guilds: - for channel in guild.channels: - yield channel - - .. note:: - - Just because you receive a :class:`.abc.GuildChannel` does not mean that - you can communicate in said channel. :meth:`.abc.GuildChannel.permissions_for` should - be used for that. - - Yields - ------ - :class:`.abc.GuildChannel` - A channel the client can 'access'. - """ - - for guild in self.guilds: - yield from guild.channels - - def get_all_members(self) -> Generator[Member, None, None]: - """Returns a generator with every :class:`.Member` the client can see. - - This is equivalent to: :: - - for guild in client.guilds: - for member in guild.members: - yield member - - Yields - ------ - :class:`.Member` - A member the client can see. - """ - for guild in self.guilds: - yield from guild.members - - # listeners/waiters - - async def wait_until_ready(self) -> None: - """|coro| - - Waits until the client's internal cache is all ready. - - .. warning:: - - Calling this inside :meth:`setup_hook` can lead to a deadlock. - """ - if self._ready is not MISSING: - await self._ready.wait() - else: - raise RuntimeError( - 'Client has not been properly initialised. ' - 'Please use the login method or asynchronous context manager before calling this method' - ) - - def wait_for( - self, - event: str, - /, - *, - check: Optional[Callable[..., bool]] = None, - timeout: Optional[float] = None, - ) -> Any: - """|coro| - - Waits for a WebSocket event to be dispatched. - - This could be used to wait for a user to reply to a message, - or to react to a message, or to edit a message in a self-contained - way. - - The ``timeout`` parameter is passed onto :func:`asyncio.wait_for`. By default, - it does not timeout. Note that this does propagate the - :exc:`asyncio.TimeoutError` for you in case of timeout and is provided for - ease of use. - - In case the event returns multiple arguments, a :class:`tuple` containing those - arguments is returned instead. Please check the - :ref:`documentation ` for a list of events and their - parameters. - - This function returns the **first event that meets the requirements**. - - Examples - --------- - - Waiting for a user reply: :: - - @client.event - async def on_message(message): - if message.content.startswith('$greet'): - channel = message.channel - await channel.send('Say hello!') - - def check(m): - return m.content == 'hello' and m.channel == channel - - msg = await client.wait_for('message', check=check) - await channel.send(f'Hello {msg.author}!') - - Waiting for a thumbs up reaction from the message author: :: - - @client.event - async def on_message(message): - if message.content.startswith('$thumb'): - channel = message.channel - await channel.send('Send me that \N{THUMBS UP SIGN} reaction, mate') - - def check(reaction, user): - return user == message.author and str(reaction.emoji) == '\N{THUMBS UP SIGN}' - - try: - reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check) - except asyncio.TimeoutError: - await channel.send('\N{THUMBS DOWN SIGN}') - else: - await channel.send('\N{THUMBS UP SIGN}') - - .. versionchanged:: 2.0 - - ``event`` parameter is now positional-only. - - - Parameters - ------------ - event: :class:`str` - The event name, similar to the :ref:`event reference `, - but without the ``on_`` prefix, to wait for. - check: Optional[Callable[..., :class:`bool`]] - A predicate to check what to wait for. The arguments must meet the - parameters of the event being waited for. - timeout: Optional[:class:`float`] - The number of seconds to wait before timing out and raising - :exc:`asyncio.TimeoutError`. - - Raises - ------- - asyncio.TimeoutError - If a timeout is provided and it was reached. - - Returns - -------- - Any - Returns no arguments, a single argument, or a :class:`tuple` of multiple - arguments that mirrors the parameters passed in the - :ref:`event reference `. - """ - - future = self.loop.create_future() - if check is None: - - def _check(*args): - return True - - check = _check - - ev = event.lower() - try: - listeners = self._listeners[ev] - except KeyError: - listeners = [] - self._listeners[ev] = listeners - - listeners.append((future, check)) - return asyncio.wait_for(future, timeout) - - # event registration - - def event(self, coro: Coro, /) -> Coro: - """A decorator that registers an event to listen to. - - You can find more info about the events on the :ref:`documentation below `. - - The events must be a :ref:`coroutine `, if not, :exc:`TypeError` is raised. - - Example - --------- - - .. code-block:: python3 - - @client.event - async def on_ready(): - print('Ready!') - - .. versionchanged:: 2.0 - - ``coro`` parameter is now positional-only. - - Raises - -------- - TypeError - The coroutine passed is not actually a coroutine. - """ - - if not asyncio.iscoroutinefunction(coro): - raise TypeError('event registered must be a coroutine function') - - setattr(self, coro.__name__, coro) - _log.debug('%s has successfully been registered as an event', coro.__name__) - return coro - - async def change_presence( - self, - *, - activity: Optional[BaseActivity] = None, - status: Optional[Status] = None, - ) -> None: - """|coro| - - Changes the client's presence. - - Example - --------- - - .. code-block:: python3 - - game = discord.Game("with the API") - await client.change_presence(status=discord.Status.idle, activity=game) - - .. versionchanged:: 2.0 - Removed the ``afk`` keyword-only parameter. - - .. versionchanged:: 2.0 - This function will now raise :exc:`TypeError` instead of - ``InvalidArgument``. - - Parameters - ---------- - activity: Optional[:class:`.BaseActivity`] - The activity being done. ``None`` if no currently active activity is done. - status: Optional[:class:`.Status`] - Indicates what status to change to. If ``None``, then - :attr:`.Status.online` is used. - - Raises - ------ - TypeError - If the ``activity`` parameter is not the proper type. - """ - - if status is None: - status_str = 'online' - status = Status.online - elif status is Status.offline: - status_str = 'invisible' - status = Status.offline - else: - status_str = str(status) - - await self.ws.change_presence(activity=activity, status=status_str) - - for guild in self._connection.guilds: - me = guild.me - if me is None: - continue - - if activity is not None: - me.activities = (activity,) # type: ignore # Type checker does not understand the downcast here - else: - me.activities = () - - me.status = status - - # Guild stuff - - async def fetch_guilds( - self, - *, - limit: Optional[int] = 200, - before: Optional[SnowflakeTime] = None, - after: Optional[SnowflakeTime] = None, - ) -> AsyncIterator[Guild]: - """Retrieves an :term:`asynchronous iterator` that enables receiving your guilds. - - .. note:: - - Using this, you will only receive :attr:`.Guild.owner`, :attr:`.Guild.icon`, - :attr:`.Guild.id`, and :attr:`.Guild.name` per :class:`.Guild`. - - .. note:: - - This method is an API call. For general usage, consider :attr:`guilds` instead. - - Examples - --------- - - Usage :: - - async for guild in client.fetch_guilds(limit=150): - print(guild.name) - - Flattening into a list :: - - guilds = [guild async for guild in client.fetch_guilds(limit=150)] - # guilds is now a list of Guild... - - All parameters are optional. - - Parameters - ----------- - limit: Optional[:class:`int`] - The number of guilds to retrieve. - If ``None``, it retrieves every guild you have access to. Note, however, - that this would make it a slow operation. - Defaults to ``200``. - - .. versionchanged:: 2.0 - - The default has been changed to 200. - - before: Union[:class:`.abc.Snowflake`, :class:`datetime.datetime`] - Retrieves guilds before this date or object. - If a datetime is provided, it is recommended to use a UTC aware datetime. - If the datetime is naive, it is assumed to be local time. - after: Union[:class:`.abc.Snowflake`, :class:`datetime.datetime`] - Retrieve guilds after this date or object. - If a datetime is provided, it is recommended to use a UTC aware datetime. - If the datetime is naive, it is assumed to be local time. - - Raises - ------ - HTTPException - Getting the guilds failed. - - Yields - -------- - :class:`.Guild` - The guild with the guild data parsed. - """ - - async def _before_strategy(retrieve: int, before: Optional[Snowflake], limit: Optional[int]): - before_id = before.id if before else None - data = await self.http.get_guilds(retrieve, before=before_id) - - if data: - if limit is not None: - limit -= len(data) - - before = Object(id=int(data[0]['id'])) - - return data, before, limit - - async def _after_strategy(retrieve: int, after: Optional[Snowflake], limit: Optional[int]): - after_id = after.id if after else None - data = await self.http.get_guilds(retrieve, after=after_id) - - if data: - if limit is not None: - limit -= len(data) - - after = Object(id=int(data[-1]['id'])) - - return data, after, limit - - if isinstance(before, datetime.datetime): - before = Object(id=time_snowflake(before, high=False)) - if isinstance(after, datetime.datetime): - after = Object(id=time_snowflake(after, high=True)) - - predicate: Optional[Callable[[GuildPayload], bool]] = None - strategy, state = _after_strategy, after - - if before: - strategy, state = _before_strategy, before - - if before and after: - predicate = lambda m: int(m['id']) > after.id - - while True: - retrieve = min(200 if limit is None else limit, 200) - if retrieve < 1: - return - - data, state, limit = await strategy(retrieve, state, limit) - - # Terminate loop on next iteration; there's no data left after this - if len(data) < 200: - limit = 0 - - if predicate: - data = filter(predicate, data) - - for raw_guild in data: - yield Guild(state=self._connection, data=raw_guild) - - async def fetch_template(self, code: Union[Template, str]) -> Template: - """|coro| - - Gets a :class:`.Template` from a discord.new URL or code. - - Parameters - ----------- - code: Union[:class:`.Template`, :class:`str`] - The Discord Template Code or URL (must be a discord.new URL). - - Raises - ------- - NotFound - The template is invalid. - HTTPException - Getting the template failed. - - Returns - -------- - :class:`.Template` - The template from the URL/code. - """ - code = utils.resolve_template(code) - data = await self.http.get_template(code) - return Template(data=data, state=self._connection) - - async def fetch_guild(self, guild_id: int, /, *, with_counts: bool = True) -> Guild: - """|coro| - - Retrieves a :class:`.Guild` from an ID. - - .. note:: - - Using this, you will **not** receive :attr:`.Guild.channels`, :attr:`.Guild.members`, - :attr:`.Member.activity` and :attr:`.Member.voice` per :class:`.Member`. - - .. note:: - - This method is an API call. For general usage, consider :meth:`get_guild` instead. - - .. versionchanged:: 2.0 - - ``guild_id`` parameter is now positional-only. - - - Parameters - ----------- - guild_id: :class:`int` - The guild's ID to fetch from. - with_counts: :class:`bool` - Whether to include count information in the guild. This fills the - :attr:`.Guild.approximate_member_count` and :attr:`.Guild.approximate_presence_count` - attributes without needing any privileged intents. Defaults to ``True``. - - .. versionadded:: 2.0 - - Raises - ------ - Forbidden - You do not have access to the guild. - HTTPException - Getting the guild failed. - - Returns - -------- - :class:`.Guild` - The guild from the ID. - """ - data = await self.http.get_guild(guild_id, with_counts=with_counts) - return Guild(data=data, state=self._connection) - - async def create_guild( - self, - *, - name: str, - icon: bytes = MISSING, - code: str = MISSING, - ) -> Guild: - """|coro| - - Creates a :class:`.Guild`. - - Bot accounts in more than 10 guilds are not allowed to create guilds. - - .. versionchanged:: 2.0 - ``name`` and ``icon`` parameters are now keyword-only. The ``region`` parameter has been removed. - - .. versionchanged:: 2.0 - This function will now raise :exc:`ValueError` instead of - ``InvalidArgument``. - - Parameters - ---------- - name: :class:`str` - The name of the guild. - icon: Optional[:class:`bytes`] - The :term:`py:bytes-like object` representing the icon. See :meth:`.ClientUser.edit` - for more details on what is expected. - code: :class:`str` - The code for a template to create the guild with. - - .. versionadded:: 1.4 - - Raises - ------ - HTTPException - Guild creation failed. - ValueError - Invalid icon image format given. Must be PNG or JPG. - - Returns - ------- - :class:`.Guild` - The guild created. This is not the same guild that is - added to cache. - """ - if icon is not MISSING: - icon_base64 = utils._bytes_to_base64_data(icon) - else: - icon_base64 = None - - if code: - data = await self.http.create_from_template(code, name, icon_base64) - else: - data = await self.http.create_guild(name, icon_base64) - return Guild(data=data, state=self._connection) - - async def fetch_stage_instance(self, channel_id: int, /) -> StageInstance: - """|coro| - - Gets a :class:`.StageInstance` for a stage channel id. - - .. versionadded:: 2.0 - - Parameters - ----------- - channel_id: :class:`int` - The stage channel ID. - - Raises - ------- - NotFound - The stage instance or channel could not be found. - HTTPException - Getting the stage instance failed. - - Returns - -------- - :class:`.StageInstance` - The stage instance from the stage channel ID. - """ - data = await self.http.get_stage_instance(channel_id) - guild = self.get_guild(int(data['guild_id'])) - # Guild can technically be None here but this is being explicitly silenced right now. - return StageInstance(guild=guild, state=self._connection, data=data) # type: ignore - - # Invite management - - async def fetch_invite( - self, - url: Union[Invite, str], - *, - with_counts: bool = True, - with_expiration: bool = True, - scheduled_event_id: Optional[int] = None, - ) -> Invite: - """|coro| - - Gets an :class:`.Invite` from a discord.gg URL or ID. - - .. note:: - - If the invite is for a guild you have not joined, the guild and channel - attributes of the returned :class:`.Invite` will be :class:`.PartialInviteGuild` and - :class:`.PartialInviteChannel` respectively. - - Parameters - ----------- - url: Union[:class:`.Invite`, :class:`str`] - The Discord invite ID or URL (must be a discord.gg URL). - with_counts: :class:`bool` - Whether to include count information in the invite. This fills the - :attr:`.Invite.approximate_member_count` and :attr:`.Invite.approximate_presence_count` - fields. - with_expiration: :class:`bool` - Whether to include the expiration date of the invite. This fills the - :attr:`.Invite.expires_at` field. - - .. versionadded:: 2.0 - scheduled_event_id: Optional[:class:`int`] - The ID of the scheduled event this invite is for. - - .. note:: - - It is not possible to provide a url that contains an ``event_id`` parameter - when using this parameter. - - .. versionadded:: 2.0 - - Raises - ------- - ValueError - The url contains an ``event_id``, but ``scheduled_event_id`` has also been provided. - NotFound - The invite has expired or is invalid. - HTTPException - Getting the invite failed. - - Returns - -------- - :class:`.Invite` - The invite from the URL/ID. - """ - - resolved = utils.resolve_invite(url) - - if scheduled_event_id and resolved.event: - raise ValueError('Cannot specify scheduled_event_id and contain an event_id in the url.') - - scheduled_event_id = scheduled_event_id or resolved.event - - data = await self.http.get_invite( - resolved.code, - with_counts=with_counts, - with_expiration=with_expiration, - guild_scheduled_event_id=scheduled_event_id, - ) - return Invite.from_incomplete(state=self._connection, data=data) - - async def delete_invite(self, invite: Union[Invite, str], /) -> None: - """|coro| - - Revokes an :class:`.Invite`, URL, or ID to an invite. - - You must have the :attr:`~.Permissions.manage_channels` permission in - the associated guild to do this. - - .. versionchanged:: 2.0 - - ``invite`` parameter is now positional-only. - - Parameters - ---------- - invite: Union[:class:`.Invite`, :class:`str`] - The invite to revoke. - - Raises - ------- - Forbidden - You do not have permissions to revoke invites. - NotFound - The invite is invalid or expired. - HTTPException - Revoking the invite failed. - """ - - resolved = utils.resolve_invite(invite) - await self.http.delete_invite(resolved.code) - - # Miscellaneous stuff - - async def fetch_widget(self, guild_id: int, /) -> Widget: - """|coro| - - Gets a :class:`.Widget` from a guild ID. - - .. note:: - - The guild must have the widget enabled to get this information. - - .. versionchanged:: 2.0 - - ``guild_id`` parameter is now positional-only. - - Parameters - ----------- - guild_id: :class:`int` - The ID of the guild. - - Raises - ------- - Forbidden - The widget for this guild is disabled. - HTTPException - Retrieving the widget failed. - - Returns - -------- - :class:`.Widget` - The guild's widget. - """ - data = await self.http.get_widget(guild_id) - - return Widget(state=self._connection, data=data) - - async def application_info(self) -> AppInfo: - """|coro| - - Retrieves the bot's application information. - - Raises - ------- - HTTPException - Retrieving the information failed somehow. - - Returns - -------- - :class:`.AppInfo` - The bot's application information. - """ - data = await self.http.application_info() - if 'rpc_origins' not in data: - data['rpc_origins'] = None - return AppInfo(self._connection, data) - - async def fetch_user(self, user_id: int, /) -> User: - """|coro| - - Retrieves a :class:`~discord.User` based on their ID. - You do not have to share any guilds with the user to get this information, - however many operations do require that you do. - - .. note:: - - This method is an API call. If you have :attr:`discord.Intents.members` and member cache enabled, consider :meth:`get_user` instead. - - .. versionchanged:: 2.0 - - ``user_id`` parameter is now positional-only. - - Parameters - ----------- - user_id: :class:`int` - The user's ID to fetch from. - - Raises - ------- - NotFound - A user with this ID does not exist. - HTTPException - Fetching the user failed. - - Returns - -------- - :class:`~discord.User` - The user you requested. - """ - data = await self.http.get_user(user_id) - return User(state=self._connection, data=data) - - async def fetch_channel(self, channel_id: int, /) -> Union[GuildChannel, PrivateChannel, Thread]: - """|coro| - - Retrieves a :class:`.abc.GuildChannel`, :class:`.abc.PrivateChannel`, or :class:`.Thread` with the specified ID. - - .. note:: - - This method is an API call. For general usage, consider :meth:`get_channel` instead. - - .. versionadded:: 1.2 - - .. versionchanged:: 2.0 - - ``channel_id`` parameter is now positional-only. - - Raises - ------- - InvalidData - An unknown channel type was received from Discord. - HTTPException - Retrieving the channel failed. - NotFound - Invalid Channel ID. - Forbidden - You do not have permission to fetch this channel. - - Returns - -------- - Union[:class:`.abc.GuildChannel`, :class:`.abc.PrivateChannel`, :class:`.Thread`] - The channel from the ID. - """ - data = await self.http.get_channel(channel_id) - - factory, ch_type = _threaded_channel_factory(data['type']) - if factory is None: - raise InvalidData('Unknown channel type {type} for channel ID {id}.'.format_map(data)) - - if ch_type in (ChannelType.group, ChannelType.private): - # the factory will be a DMChannel or GroupChannel here - channel = factory(me=self.user, data=data, state=self._connection) # type: ignore - else: - # the factory can't be a DMChannel or GroupChannel here - guild_id = int(data['guild_id']) # type: ignore - guild = self._connection._get_or_create_unavailable_guild(guild_id) - # the factory should be a GuildChannel or Thread - channel = factory(guild=guild, state=self._connection, data=data) # type: ignore - - return channel - - async def fetch_webhook(self, webhook_id: int, /) -> Webhook: - """|coro| - - Retrieves a :class:`.Webhook` with the specified ID. - - .. versionchanged:: 2.0 - - ``webhook_id`` parameter is now positional-only. - - Raises - -------- - HTTPException - Retrieving the webhook failed. - NotFound - Invalid webhook ID. - Forbidden - You do not have permission to fetch this webhook. - - Returns - --------- - :class:`.Webhook` - The webhook you requested. - """ - data = await self.http.get_webhook(webhook_id) - return Webhook.from_state(data, state=self._connection) - - async def fetch_sticker(self, sticker_id: int, /) -> Union[StandardSticker, GuildSticker]: - """|coro| - - Retrieves a :class:`.Sticker` with the specified ID. - - .. versionadded:: 2.0 - - Raises - -------- - HTTPException - Retrieving the sticker failed. - NotFound - Invalid sticker ID. - - Returns - -------- - Union[:class:`.StandardSticker`, :class:`.GuildSticker`] - The sticker you requested. - """ - data = await self.http.get_sticker(sticker_id) - cls, _ = _sticker_factory(data['type']) - # The type checker is not smart enough to figure out the constructor is correct - return cls(state=self._connection, data=data) # type: ignore - - async def fetch_premium_sticker_packs(self) -> List[StickerPack]: - """|coro| - - Retrieves all available premium sticker packs. - - .. versionadded:: 2.0 - - Raises - ------- - HTTPException - Retrieving the sticker packs failed. - - Returns - --------- - List[:class:`.StickerPack`] - All available premium sticker packs. - """ - data = await self.http.list_premium_sticker_packs() - return [StickerPack(state=self._connection, data=pack) for pack in data['sticker_packs']] - - async def create_dm(self, user: Snowflake) -> DMChannel: - """|coro| - - Creates a :class:`.DMChannel` with this user. - - This should be rarely called, as this is done transparently for most - people. - - .. versionadded:: 2.0 - - Parameters - ----------- - user: :class:`~discord.abc.Snowflake` - The user to create a DM with. - - Returns - ------- - :class:`.DMChannel` - The channel that was created. - """ - state = self._connection - found = state._get_private_channel_by_user(user.id) - if found: - return found - - data = await state.http.start_private_message(user.id) - return state.add_dm_channel(data) - - def add_view(self, view: View, *, message_id: Optional[int] = None) -> None: - """Registers a :class:`~discord.ui.View` for persistent listening. - - This method should be used for when a view is comprised of components - that last longer than the lifecycle of the program. - - .. versionadded:: 2.0 - - Parameters - ------------ - view: :class:`discord.ui.View` - The view to register for dispatching. - message_id: Optional[:class:`int`] - The message ID that the view is attached to. This is currently used to - refresh the view's state during message update events. If not given - then message update events are not propagated for the view. - - Raises - ------- - TypeError - A view was not passed. - ValueError - The view is not persistent. A persistent view has no timeout - and all their components have an explicitly provided custom_id. - """ - - if not isinstance(view, View): - raise TypeError(f'expected an instance of View not {view.__class__!r}') - - if not view.is_persistent(): - raise ValueError('View is not persistent. Items need to have a custom_id set and View must have no timeout') - - self._connection.store_view(view, message_id) - - @property - def persistent_views(self) -> Sequence[View]: - """Sequence[:class:`.View`]: A sequence of persistent views added to the client. - - .. versionadded:: 2.0 - """ - return self._connection.persistent_views diff --git a/.venv/Lib/site-packages/discord/colour.py b/.venv/Lib/site-packages/discord/colour.py deleted file mode 100644 index f6d88f8..0000000 --- a/.venv/Lib/site-packages/discord/colour.py +++ /dev/null @@ -1,401 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" -from __future__ import annotations - -import colorsys -import random -import re - -from typing import TYPE_CHECKING, Optional, Tuple, Union - -if TYPE_CHECKING: - from typing_extensions import Self - -__all__ = ( - 'Colour', - 'Color', -) - -RGB_REGEX = re.compile(r'rgb\s*\((?P[0-9.]+%?)\s*,\s*(?P[0-9.]+%?)\s*,\s*(?P[0-9.]+%?)\s*\)') - - -def parse_hex_number(argument: str) -> Colour: - arg = ''.join(i * 2 for i in argument) if len(argument) == 3 else argument - try: - value = int(arg, base=16) - if not (0 <= value <= 0xFFFFFF): - raise ValueError('hex number out of range for 24-bit colour') - except ValueError: - raise ValueError('invalid hex digit given') from None - else: - return Color(value=value) - - -def parse_rgb_number(number: str) -> int: - if number[-1] == '%': - value = float(number[:-1]) - if not (0 <= value <= 100): - raise ValueError('rgb percentage can only be between 0 to 100') - return round(255 * (value / 100)) - - value = int(number) - if not (0 <= value <= 255): - raise ValueError('rgb number can only be between 0 to 255') - return value - - -def parse_rgb(argument: str, *, regex: re.Pattern[str] = RGB_REGEX) -> Colour: - match = regex.match(argument) - if match is None: - raise ValueError('invalid rgb syntax found') - - red = parse_rgb_number(match.group('r')) - green = parse_rgb_number(match.group('g')) - blue = parse_rgb_number(match.group('b')) - return Color.from_rgb(red, green, blue) - - -class Colour: - """Represents a Discord role colour. This class is similar - to a (red, green, blue) :class:`tuple`. - - There is an alias for this called Color. - - .. container:: operations - - .. describe:: x == y - - Checks if two colours are equal. - - .. describe:: x != y - - Checks if two colours are not equal. - - .. describe:: hash(x) - - Return the colour's hash. - - .. describe:: str(x) - - Returns the hex format for the colour. - - .. describe:: int(x) - - Returns the raw colour value. - - Attributes - ------------ - value: :class:`int` - The raw integer colour value. - """ - - __slots__ = ('value',) - - def __init__(self, value: int): - if not isinstance(value, int): - raise TypeError(f'Expected int parameter, received {value.__class__.__name__} instead.') - - self.value: int = value - - def _get_byte(self, byte: int) -> int: - return (self.value >> (8 * byte)) & 0xFF - - def __eq__(self, other: object) -> bool: - return isinstance(other, Colour) and self.value == other.value - - def __ne__(self, other: object) -> bool: - return not self.__eq__(other) - - def __str__(self) -> str: - return f'#{self.value:0>6x}' - - def __int__(self) -> int: - return self.value - - def __repr__(self) -> str: - return f'' - - def __hash__(self) -> int: - return hash(self.value) - - @property - def r(self) -> int: - """:class:`int`: Returns the red component of the colour.""" - return self._get_byte(2) - - @property - def g(self) -> int: - """:class:`int`: Returns the green component of the colour.""" - return self._get_byte(1) - - @property - def b(self) -> int: - """:class:`int`: Returns the blue component of the colour.""" - return self._get_byte(0) - - def to_rgb(self) -> Tuple[int, int, int]: - """Tuple[:class:`int`, :class:`int`, :class:`int`]: Returns an (r, g, b) tuple representing the colour.""" - return (self.r, self.g, self.b) - - @classmethod - def from_rgb(cls, r: int, g: int, b: int) -> Self: - """Constructs a :class:`Colour` from an RGB tuple.""" - return cls((r << 16) + (g << 8) + b) - - @classmethod - def from_hsv(cls, h: float, s: float, v: float) -> Self: - """Constructs a :class:`Colour` from an HSV tuple.""" - rgb = colorsys.hsv_to_rgb(h, s, v) - return cls.from_rgb(*(int(x * 255) for x in rgb)) - - @classmethod - def from_str(cls, value: str) -> Self: - """Constructs a :class:`Colour` from a string. - - The following formats are accepted: - - - ``0x`` - - ``#`` - - ``0x#`` - - ``rgb(, , )`` - - Like CSS, ```` can be either 0-255 or 0-100% and ```` can be - either a 6 digit hex number or a 3 digit hex shortcut (e.g. #fff). - - .. versionadded:: 2.0 - - Raises - ------- - ValueError - The string could not be converted into a colour. - """ - - if value[0] == '#': - return parse_hex_number(value[1:]) - - if value[0:2] == '0x': - rest = value[2:] - # Legacy backwards compatible syntax - if rest.startswith('#'): - return parse_hex_number(rest[1:]) - return parse_hex_number(rest) - - arg = value.lower() - if arg[0:3] == 'rgb': - return parse_rgb(arg) - - raise ValueError('unknown colour format given') - - @classmethod - def default(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0``.""" - return cls(0) - - @classmethod - def random(cls, *, seed: Optional[Union[int, str, float, bytes, bytearray]] = None) -> Self: - """A factory method that returns a :class:`Colour` with a random hue. - - .. note:: - - The random algorithm works by choosing a colour with a random hue but - with maxed out saturation and value. - - .. versionadded:: 1.6 - - Parameters - ------------ - seed: Optional[Union[:class:`int`, :class:`str`, :class:`float`, :class:`bytes`, :class:`bytearray`]] - The seed to initialize the RNG with. If ``None`` is passed the default RNG is used. - - .. versionadded:: 1.7 - """ - rand = random if seed is None else random.Random(seed) - return cls.from_hsv(rand.random(), 1, 1) - - @classmethod - def teal(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0x1abc9c``.""" - return cls(0x1ABC9C) - - @classmethod - def dark_teal(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0x11806a``.""" - return cls(0x11806A) - - @classmethod - def brand_green(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0x57F287``. - - .. versionadded:: 2.0 - """ - return cls(0x57F287) - - @classmethod - def green(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0x2ecc71``.""" - return cls(0x2ECC71) - - @classmethod - def dark_green(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0x1f8b4c``.""" - return cls(0x1F8B4C) - - @classmethod - def blue(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0x3498db``.""" - return cls(0x3498DB) - - @classmethod - def dark_blue(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0x206694``.""" - return cls(0x206694) - - @classmethod - def purple(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0x9b59b6``.""" - return cls(0x9B59B6) - - @classmethod - def dark_purple(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0x71368a``.""" - return cls(0x71368A) - - @classmethod - def magenta(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0xe91e63``.""" - return cls(0xE91E63) - - @classmethod - def dark_magenta(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0xad1457``.""" - return cls(0xAD1457) - - @classmethod - def gold(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0xf1c40f``.""" - return cls(0xF1C40F) - - @classmethod - def dark_gold(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0xc27c0e``.""" - return cls(0xC27C0E) - - @classmethod - def orange(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0xe67e22``.""" - return cls(0xE67E22) - - @classmethod - def dark_orange(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0xa84300``.""" - return cls(0xA84300) - - @classmethod - def brand_red(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0xED4245``. - - .. versionadded:: 2.0 - """ - return cls(0xED4245) - - @classmethod - def red(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0xe74c3c``.""" - return cls(0xE74C3C) - - @classmethod - def dark_red(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0x992d22``.""" - return cls(0x992D22) - - @classmethod - def lighter_grey(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0x95a5a6``.""" - return cls(0x95A5A6) - - lighter_gray = lighter_grey - - @classmethod - def dark_grey(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0x607d8b``.""" - return cls(0x607D8B) - - dark_gray = dark_grey - - @classmethod - def light_grey(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0x979c9f``.""" - return cls(0x979C9F) - - light_gray = light_grey - - @classmethod - def darker_grey(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0x546e7a``.""" - return cls(0x546E7A) - - darker_gray = darker_grey - - @classmethod - def og_blurple(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0x7289da``.""" - return cls(0x7289DA) - - @classmethod - def blurple(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0x5865F2``.""" - return cls(0x5865F2) - - @classmethod - def greyple(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0x99aab5``.""" - return cls(0x99AAB5) - - @classmethod - def dark_theme(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0x36393F``. - This will appear transparent on Discord's dark theme. - - .. versionadded:: 1.5 - """ - return cls(0x36393F) - - @classmethod - def fuchsia(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0xEB459E``. - - .. versionadded:: 2.0 - """ - return cls(0xEB459E) - - @classmethod - def yellow(cls) -> Self: - """A factory method that returns a :class:`Colour` with a value of ``0xFEE75C``. - - .. versionadded:: 2.0 - """ - return cls(0xFEE75C) - - -Color = Colour diff --git a/.venv/Lib/site-packages/discord/components.py b/.venv/Lib/site-packages/discord/components.py deleted file mode 100644 index 3f7dd11..0000000 --- a/.venv/Lib/site-packages/discord/components.py +++ /dev/null @@ -1,528 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations - -from typing import ClassVar, List, Literal, Optional, TYPE_CHECKING, Tuple, Union, overload -from .enums import try_enum, ComponentType, ButtonStyle, TextStyle -from .utils import get_slots, MISSING -from .partial_emoji import PartialEmoji, _EmojiTag - -if TYPE_CHECKING: - from typing_extensions import Self - - from .types.components import ( - Component as ComponentPayload, - ButtonComponent as ButtonComponentPayload, - SelectMenu as SelectMenuPayload, - SelectOption as SelectOptionPayload, - ActionRow as ActionRowPayload, - TextInput as TextInputPayload, - ActionRowChildComponent as ActionRowChildComponentPayload, - ) - from .emoji import Emoji - - ActionRowChildComponentType = Union['Button', 'SelectMenu', 'TextInput'] - - -__all__ = ( - 'Component', - 'ActionRow', - 'Button', - 'SelectMenu', - 'SelectOption', - 'TextInput', -) - - -class Component: - """Represents a Discord Bot UI Kit Component. - - Currently, the only components supported by Discord are: - - - :class:`ActionRow` - - :class:`Button` - - :class:`SelectMenu` - - :class:`TextInput` - - This class is abstract and cannot be instantiated. - - .. versionadded:: 2.0 - """ - - __slots__: Tuple[str, ...] = () - - __repr_info__: ClassVar[Tuple[str, ...]] - - def __repr__(self) -> str: - attrs = ' '.join(f'{key}={getattr(self, key)!r}' for key in self.__repr_info__) - return f'<{self.__class__.__name__} {attrs}>' - - @property - def type(self) -> ComponentType: - """:class:`ComponentType`: The type of component.""" - raise NotImplementedError - - @classmethod - def _raw_construct(cls, **kwargs) -> Self: - self = cls.__new__(cls) - for slot in get_slots(cls): - try: - value = kwargs[slot] - except KeyError: - pass - else: - setattr(self, slot, value) - return self - - def to_dict(self) -> ComponentPayload: - raise NotImplementedError - - -class ActionRow(Component): - """Represents a Discord Bot UI Kit Action Row. - - This is a component that holds up to 5 children components in a row. - - This inherits from :class:`Component`. - - .. versionadded:: 2.0 - - Attributes - ------------ - children: List[Union[:class:`Button`, :class:`SelectMenu`, :class:`TextInput`]] - The children components that this holds, if any. - """ - - __slots__: Tuple[str, ...] = ('children',) - - __repr_info__: ClassVar[Tuple[str, ...]] = __slots__ - - def __init__(self, data: ActionRowPayload, /) -> None: - self.children: List[ActionRowChildComponentType] = [] - - for component_data in data.get('components', []): - component = _component_factory(component_data) - - if component is not None: - self.children.append(component) - - @property - def type(self) -> Literal[ComponentType.action_row]: - """:class:`ComponentType`: The type of component.""" - return ComponentType.action_row - - def to_dict(self) -> ActionRowPayload: - return { - 'type': self.type.value, - 'components': [child.to_dict() for child in self.children], - } - - -class Button(Component): - """Represents a button from the Discord Bot UI Kit. - - This inherits from :class:`Component`. - - .. note:: - - The user constructible and usable type to create a button is :class:`discord.ui.Button` - not this one. - - .. versionadded:: 2.0 - - Attributes - ----------- - style: :class:`.ButtonStyle` - The style of the button. - custom_id: Optional[:class:`str`] - The ID of the button that gets received during an interaction. - If this button is for a URL, it does not have a custom ID. - url: Optional[:class:`str`] - The URL this button sends you to. - disabled: :class:`bool` - Whether the button is disabled or not. - label: Optional[:class:`str`] - The label of the button, if any. - emoji: Optional[:class:`PartialEmoji`] - The emoji of the button, if available. - """ - - __slots__: Tuple[str, ...] = ( - 'style', - 'custom_id', - 'url', - 'disabled', - 'label', - 'emoji', - ) - - __repr_info__: ClassVar[Tuple[str, ...]] = __slots__ - - def __init__(self, data: ButtonComponentPayload, /) -> None: - self.style: ButtonStyle = try_enum(ButtonStyle, data['style']) - self.custom_id: Optional[str] = data.get('custom_id') - self.url: Optional[str] = data.get('url') - self.disabled: bool = data.get('disabled', False) - self.label: Optional[str] = data.get('label') - self.emoji: Optional[PartialEmoji] - try: - self.emoji = PartialEmoji.from_dict(data['emoji']) - except KeyError: - self.emoji = None - - @property - def type(self) -> Literal[ComponentType.button]: - """:class:`ComponentType`: The type of component.""" - return ComponentType.button - - def to_dict(self) -> ButtonComponentPayload: - payload: ButtonComponentPayload = { - 'type': 2, - 'style': self.style.value, - 'disabled': self.disabled, - } - - if self.label: - payload['label'] = self.label - - if self.custom_id: - payload['custom_id'] = self.custom_id - - if self.url: - payload['url'] = self.url - - if self.emoji: - payload['emoji'] = self.emoji.to_dict() - - return payload - - -class SelectMenu(Component): - """Represents a select menu from the Discord Bot UI Kit. - - A select menu is functionally the same as a dropdown, however - on mobile it renders a bit differently. - - .. note:: - - The user constructible and usable type to create a select menu is - :class:`discord.ui.Select` not this one. - - .. versionadded:: 2.0 - - Attributes - ------------ - custom_id: Optional[:class:`str`] - The ID of the select menu that gets received during an interaction. - placeholder: Optional[:class:`str`] - The placeholder text that is shown if nothing is selected, if any. - min_values: :class:`int` - The minimum number of items that must be chosen for this select menu. - Defaults to 1 and must be between 0 and 25. - max_values: :class:`int` - The maximum number of items that must be chosen for this select menu. - Defaults to 1 and must be between 1 and 25. - options: List[:class:`SelectOption`] - A list of options that can be selected in this menu. - disabled: :class:`bool` - Whether the select is disabled or not. - """ - - __slots__: Tuple[str, ...] = ( - 'custom_id', - 'placeholder', - 'min_values', - 'max_values', - 'options', - 'disabled', - ) - - __repr_info__: ClassVar[Tuple[str, ...]] = __slots__ - - def __init__(self, data: SelectMenuPayload, /) -> None: - self.custom_id: str = data['custom_id'] - self.placeholder: Optional[str] = data.get('placeholder') - self.min_values: int = data.get('min_values', 1) - self.max_values: int = data.get('max_values', 1) - self.options: List[SelectOption] = [SelectOption.from_dict(option) for option in data.get('options', [])] - self.disabled: bool = data.get('disabled', False) - - @property - def type(self) -> Literal[ComponentType.select]: - """:class:`ComponentType`: The type of component.""" - return ComponentType.select - - def to_dict(self) -> SelectMenuPayload: - payload: SelectMenuPayload = { - 'type': self.type.value, - 'custom_id': self.custom_id, - 'min_values': self.min_values, - 'max_values': self.max_values, - 'options': [op.to_dict() for op in self.options], - 'disabled': self.disabled, - } - - if self.placeholder: - payload['placeholder'] = self.placeholder - - return payload - - -class SelectOption: - """Represents a select menu's option. - - These can be created by users. - - .. versionadded:: 2.0 - - Parameters - ----------- - label: :class:`str` - The label of the option. This is displayed to users. - Can only be up to 100 characters. - value: :class:`str` - The value of the option. This is not displayed to users. - If not provided when constructed then it defaults to the - label. Can only be up to 100 characters. - description: Optional[:class:`str`] - An additional description of the option, if any. - Can only be up to 100 characters. - emoji: Optional[Union[:class:`str`, :class:`Emoji`, :class:`PartialEmoji`]] - The emoji of the option, if available. - default: :class:`bool` - Whether this option is selected by default. - - Attributes - ----------- - label: :class:`str` - The label of the option. This is displayed to users. - Can only be up to 100 characters. - value: :class:`str` - The value of the option. This is not displayed to users. - If not provided when constructed then it defaults to the - label. Can only be up to 100 characters. - description: Optional[:class:`str`] - An additional description of the option, if any. - Can only be up to 100 characters. - default: :class:`bool` - Whether this option is selected by default. - """ - - __slots__: Tuple[str, ...] = ( - 'label', - 'value', - 'description', - '_emoji', - 'default', - ) - - def __init__( - self, - *, - label: str, - value: str = MISSING, - description: Optional[str] = None, - emoji: Optional[Union[str, Emoji, PartialEmoji]] = None, - default: bool = False, - ) -> None: - self.label: str = label - self.value: str = label if value is MISSING else value - self.description: Optional[str] = description - - self.emoji = emoji - self.default: bool = default - - def __repr__(self) -> str: - return ( - f'' - ) - - def __str__(self) -> str: - if self.emoji: - base = f'{self.emoji} {self.label}' - else: - base = self.label - - if self.description: - return f'{base}\n{self.description}' - return base - - @property - def emoji(self) -> Optional[PartialEmoji]: - """Optional[:class:`.PartialEmoji`]: The emoji of the option, if available.""" - return self._emoji - - @emoji.setter - def emoji(self, value: Optional[Union[str, Emoji, PartialEmoji]]) -> None: - if value is not None: - if isinstance(value, str): - self._emoji = PartialEmoji.from_str(value) - elif isinstance(value, _EmojiTag): - self._emoji = value._to_partial() - else: - raise TypeError(f'expected str, Emoji, or PartialEmoji, received {value.__class__} instead') - else: - self._emoji = None - - @classmethod - def from_dict(cls, data: SelectOptionPayload) -> SelectOption: - try: - emoji = PartialEmoji.from_dict(data['emoji']) - except KeyError: - emoji = None - - return cls( - label=data['label'], - value=data['value'], - description=data.get('description'), - emoji=emoji, - default=data.get('default', False), - ) - - def to_dict(self) -> SelectOptionPayload: - payload: SelectOptionPayload = { - 'label': self.label, - 'value': self.value, - 'default': self.default, - } - - if self.emoji: - payload['emoji'] = self.emoji.to_dict() - - if self.description: - payload['description'] = self.description - - return payload - - -class TextInput(Component): - """Represents a text input from the Discord Bot UI Kit. - - .. note:: - The user constructible and usable type to create a text input is - :class:`discord.ui.TextInput` not this one. - - .. versionadded:: 2.0 - - Attributes - ------------ - custom_id: Optional[:class:`str`] - The ID of the text input that gets received during an interaction. - label: :class:`str` - The label to display above the text input. - style: :class:`TextStyle` - The style of the text input. - placeholder: Optional[:class:`str`] - The placeholder text to display when the text input is empty. - value: Optional[:class:`str`] - The default value of the text input. - required: :class:`bool` - Whether the text input is required. - min_length: Optional[:class:`int`] - The minimum length of the text input. - max_length: Optional[:class:`int`] - The maximum length of the text input. - """ - - __slots__: Tuple[str, ...] = ( - 'style', - 'label', - 'custom_id', - 'placeholder', - 'value', - 'required', - 'min_length', - 'max_length', - ) - - __repr_info__: ClassVar[Tuple[str, ...]] = __slots__ - - def __init__(self, data: TextInputPayload, /) -> None: - self.style: TextStyle = try_enum(TextStyle, data['style']) - self.label: str = data['label'] - self.custom_id: str = data['custom_id'] - self.placeholder: Optional[str] = data.get('placeholder') - self.value: Optional[str] = data.get('value') - self.required: bool = data.get('required', True) - self.min_length: Optional[int] = data.get('min_length') - self.max_length: Optional[int] = data.get('max_length') - - @property - def type(self) -> Literal[ComponentType.text_input]: - """:class:`ComponentType`: The type of component.""" - return ComponentType.text_input - - def to_dict(self) -> TextInputPayload: - payload: TextInputPayload = { - 'type': self.type.value, - 'style': self.style.value, - 'label': self.label, - 'custom_id': self.custom_id, - 'required': self.required, - } - - if self.placeholder: - payload['placeholder'] = self.placeholder - - if self.value: - payload['value'] = self.value - - if self.min_length: - payload['min_length'] = self.min_length - - if self.max_length: - payload['max_length'] = self.max_length - - return payload - - @property - def default(self) -> Optional[str]: - """Optional[:class:`str`]: The default value of the text input. - - This is an alias to :attr:`value`. - """ - return self.value - - -@overload -def _component_factory(data: ActionRowChildComponentPayload) -> Optional[ActionRowChildComponentType]: - ... - - -@overload -def _component_factory(data: ComponentPayload) -> Optional[Union[ActionRow, ActionRowChildComponentType]]: - ... - - -def _component_factory(data: ComponentPayload) -> Optional[Union[ActionRow, ActionRowChildComponentType]]: - if data['type'] == 1: - return ActionRow(data) - elif data['type'] == 2: - return Button(data) - elif data['type'] == 3: - return SelectMenu(data) - elif data['type'] == 4: - return TextInput(data) diff --git a/.venv/Lib/site-packages/discord/context_managers.py b/.venv/Lib/site-packages/discord/context_managers.py deleted file mode 100644 index 09803c9..0000000 --- a/.venv/Lib/site-packages/discord/context_managers.py +++ /dev/null @@ -1,92 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations - -import asyncio -from typing import TYPE_CHECKING, Generator, Optional, Type, TypeVar - -if TYPE_CHECKING: - from .abc import Messageable, MessageableChannel - - from types import TracebackType - - BE = TypeVar('BE', bound=BaseException) - -# fmt: off -__all__ = ( - 'Typing', -) -# fmt: on - - -def _typing_done_callback(fut: asyncio.Future) -> None: - # just retrieve any exception and call it a day - try: - fut.exception() - except (asyncio.CancelledError, Exception): - pass - - -class Typing: - def __init__(self, messageable: Messageable) -> None: - self.loop: asyncio.AbstractEventLoop = messageable._state.loop - self.messageable: Messageable = messageable - self.channel: Optional[MessageableChannel] = None - - async def _get_channel(self) -> MessageableChannel: - if self.channel: - return self.channel - - self.channel = channel = await self.messageable._get_channel() - return channel - - async def wrapped_typer(self) -> None: - channel = await self._get_channel() - await channel._state.http.send_typing(channel.id) - - def __await__(self) -> Generator[None, None, None]: - return self.wrapped_typer().__await__() - - async def do_typing(self) -> None: - channel = await self._get_channel() - typing = channel._state.http.send_typing - - while True: - await asyncio.sleep(5) - await typing(channel.id) - - async def __aenter__(self) -> None: - channel = await self._get_channel() - await channel._state.http.send_typing(channel.id) - self.task: asyncio.Task[None] = self.loop.create_task(self.do_typing()) - self.task.add_done_callback(_typing_done_callback) - - async def __aexit__( - self, - exc_type: Optional[Type[BE]], - exc: Optional[BE], - traceback: Optional[TracebackType], - ) -> None: - self.task.cancel() diff --git a/.venv/Lib/site-packages/discord/embeds.py b/.venv/Lib/site-packages/discord/embeds.py deleted file mode 100644 index 6a79fef..0000000 --- a/.venv/Lib/site-packages/discord/embeds.py +++ /dev/null @@ -1,757 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations - -import datetime -from typing import Any, Dict, List, Mapping, Optional, Protocol, TYPE_CHECKING, TypeVar, Union - -from . import utils -from .colour import Colour - -# fmt: off -__all__ = ( - 'Embed', -) -# fmt: on - - -class EmbedProxy: - def __init__(self, layer: Dict[str, Any]): - self.__dict__.update(layer) - - def __len__(self) -> int: - return len(self.__dict__) - - def __repr__(self) -> str: - inner = ', '.join((f'{k}={v!r}' for k, v in self.__dict__.items() if not k.startswith('_'))) - return f'EmbedProxy({inner})' - - def __getattr__(self, attr: str) -> None: - return None - - def __eq__(self, other: object) -> bool: - return isinstance(other, EmbedProxy) and self.__dict__ == other.__dict__ - - -if TYPE_CHECKING: - from typing_extensions import Self - - from .types.embed import Embed as EmbedData, EmbedType - - T = TypeVar('T') - - class _EmbedFooterProxy(Protocol): - text: Optional[str] - icon_url: Optional[str] - - class _EmbedFieldProxy(Protocol): - name: Optional[str] - value: Optional[str] - inline: bool - - class _EmbedMediaProxy(Protocol): - url: Optional[str] - proxy_url: Optional[str] - height: Optional[int] - width: Optional[int] - - class _EmbedVideoProxy(Protocol): - url: Optional[str] - height: Optional[int] - width: Optional[int] - - class _EmbedProviderProxy(Protocol): - name: Optional[str] - url: Optional[str] - - class _EmbedAuthorProxy(Protocol): - name: Optional[str] - url: Optional[str] - icon_url: Optional[str] - proxy_icon_url: Optional[str] - - -class Embed: - """Represents a Discord embed. - - .. container:: operations - - .. describe:: len(x) - - Returns the total size of the embed. - Useful for checking if it's within the 6000 character limit. - - .. describe:: bool(b) - - Returns whether the embed has any data set. - - .. versionadded:: 2.0 - - .. describe:: x == y - - Checks if two embeds are equal. - - .. versionadded:: 2.0 - - For ease of use, all parameters that expect a :class:`str` are implicitly - casted to :class:`str` for you. - - .. versionchanged:: 2.0 - ``Embed.Empty`` has been removed in favour of ``None``. - - Attributes - ----------- - title: Optional[:class:`str`] - The title of the embed. - This can be set during initialisation. - Can only be up to 256 characters. - type: :class:`str` - The type of embed. Usually "rich". - This can be set during initialisation. - Possible strings for embed types can be found on discord's - :ddocs:`api docs ` - description: Optional[:class:`str`] - The description of the embed. - This can be set during initialisation. - Can only be up to 4096 characters. - url: Optional[:class:`str`] - The URL of the embed. - This can be set during initialisation. - timestamp: Optional[:class:`datetime.datetime`] - The timestamp of the embed content. This is an aware datetime. - If a naive datetime is passed, it is converted to an aware - datetime with the local timezone. - colour: Optional[Union[:class:`Colour`, :class:`int`]] - The colour code of the embed. Aliased to ``color`` as well. - This can be set during initialisation. - """ - - __slots__ = ( - 'title', - 'url', - 'type', - '_timestamp', - '_colour', - '_footer', - '_image', - '_thumbnail', - '_video', - '_provider', - '_author', - '_fields', - 'description', - ) - - def __init__( - self, - *, - colour: Optional[Union[int, Colour]] = None, - color: Optional[Union[int, Colour]] = None, - title: Optional[Any] = None, - type: EmbedType = 'rich', - url: Optional[Any] = None, - description: Optional[Any] = None, - timestamp: Optional[datetime.datetime] = None, - ): - - self.colour = colour if colour is not None else color - self.title: Optional[str] = title - self.type: EmbedType = type - self.url: Optional[str] = url - self.description: Optional[str] = description - - if self.title is not None: - self.title = str(self.title) - - if self.description is not None: - self.description = str(self.description) - - if self.url is not None: - self.url = str(self.url) - - if timestamp is not None: - self.timestamp = timestamp - - @classmethod - def from_dict(cls, data: Mapping[str, Any]) -> Self: - """Converts a :class:`dict` to a :class:`Embed` provided it is in the - format that Discord expects it to be in. - - You can find out about this format in the :ddocs:`official Discord documentation `. - - Parameters - ----------- - data: :class:`dict` - The dictionary to convert into an embed. - """ - # we are bypassing __init__ here since it doesn't apply here - self = cls.__new__(cls) - - # fill in the basic fields - - self.title = data.get('title', None) - self.type = data.get('type', None) - self.description = data.get('description', None) - self.url = data.get('url', None) - - if self.title is not None: - self.title = str(self.title) - - if self.description is not None: - self.description = str(self.description) - - if self.url is not None: - self.url = str(self.url) - - # try to fill in the more rich fields - - try: - self._colour = Colour(value=data['color']) - except KeyError: - pass - - try: - self._timestamp = utils.parse_time(data['timestamp']) - except KeyError: - pass - - for attr in ('thumbnail', 'video', 'provider', 'author', 'fields', 'image', 'footer'): - try: - value = data[attr] - except KeyError: - continue - else: - setattr(self, '_' + attr, value) - - return self - - def copy(self) -> Self: - """Returns a shallow copy of the embed.""" - return self.__class__.from_dict(self.to_dict()) - - def __len__(self) -> int: - total = len(self.title or '') + len(self.description or '') - for field in getattr(self, '_fields', []): - total += len(field['name']) + len(field['value']) - - try: - footer_text = self._footer['text'] - except (AttributeError, KeyError): - pass - else: - total += len(footer_text) - - try: - author = self._author - except AttributeError: - pass - else: - total += len(author['name']) - - return total - - def __bool__(self) -> bool: - return any( - ( - self.title, - self.url, - self.description, - self.colour, - self.fields, - self.timestamp, - self.author, - self.thumbnail, - self.footer, - self.image, - self.provider, - self.video, - ) - ) - - def __eq__(self, other: Embed) -> bool: - return isinstance(other, Embed) and ( - self.type == other.type - and self.title == other.title - and self.url == other.url - and self.description == other.description - and self.colour == other.colour - and self.fields == other.fields - and self.timestamp == other.timestamp - and self.author == other.author - and self.thumbnail == other.thumbnail - and self.footer == other.footer - and self.image == other.image - and self.provider == other.provider - and self.video == other.video - ) - - @property - def colour(self) -> Optional[Colour]: - return getattr(self, '_colour', None) - - @colour.setter - def colour(self, value: Optional[Union[int, Colour]]) -> None: - if value is None: - self._colour = None - elif isinstance(value, Colour): - self._colour = value - elif isinstance(value, int): - self._colour = Colour(value=value) - else: - raise TypeError(f'Expected discord.Colour, int, or None but received {value.__class__.__name__} instead.') - - color = colour - - @property - def timestamp(self) -> Optional[datetime.datetime]: - return getattr(self, '_timestamp', None) - - @timestamp.setter - def timestamp(self, value: Optional[datetime.datetime]) -> None: - if isinstance(value, datetime.datetime): - if value.tzinfo is None: - value = value.astimezone() - self._timestamp = value - elif value is None: - self._timestamp = None - else: - raise TypeError(f"Expected datetime.datetime or None received {value.__class__.__name__} instead") - - @property - def footer(self) -> _EmbedFooterProxy: - """Returns an ``EmbedProxy`` denoting the footer contents. - - See :meth:`set_footer` for possible values you can access. - - If the attribute has no value then ``None`` is returned. - """ - # Lying to the type checker for better developer UX. - return EmbedProxy(getattr(self, '_footer', {})) # type: ignore - - def set_footer(self, *, text: Optional[Any] = None, icon_url: Optional[Any] = None) -> Self: - """Sets the footer for the embed content. - - This function returns the class instance to allow for fluent-style - chaining. - - Parameters - ----------- - text: :class:`str` - The footer text. Can only be up to 2048 characters. - icon_url: :class:`str` - The URL of the footer icon. Only HTTP(S) is supported. - Inline attachment URLs are also supported, see :ref:`local_image`. - """ - - self._footer = {} - if text is not None: - self._footer['text'] = str(text) - - if icon_url is not None: - self._footer['icon_url'] = str(icon_url) - - return self - - def remove_footer(self) -> Self: - """Clears embed's footer information. - - This function returns the class instance to allow for fluent-style - chaining. - - .. versionadded:: 2.0 - """ - try: - del self._footer - except AttributeError: - pass - - return self - - @property - def image(self) -> _EmbedMediaProxy: - """Returns an ``EmbedProxy`` denoting the image contents. - - Possible attributes you can access are: - - - ``url`` - - ``proxy_url`` - - ``width`` - - ``height`` - - If the attribute has no value then ``None`` is returned. - """ - # Lying to the type checker for better developer UX. - return EmbedProxy(getattr(self, '_image', {})) # type: ignore - - def set_image(self, *, url: Optional[Any]) -> Self: - """Sets the image for the embed content. - - This function returns the class instance to allow for fluent-style - chaining. - - Parameters - ----------- - url: :class:`str` - The source URL for the image. Only HTTP(S) is supported. - Inline attachment URLs are also supported, see :ref:`local_image`. - """ - - if url is None: - try: - del self._image - except AttributeError: - pass - else: - self._image = { - 'url': str(url), - } - - return self - - @property - def thumbnail(self) -> _EmbedMediaProxy: - """Returns an ``EmbedProxy`` denoting the thumbnail contents. - - Possible attributes you can access are: - - - ``url`` - - ``proxy_url`` - - ``width`` - - ``height`` - - If the attribute has no value then ``None`` is returned. - """ - # Lying to the type checker for better developer UX. - return EmbedProxy(getattr(self, '_thumbnail', {})) # type: ignore - - def set_thumbnail(self, *, url: Optional[Any]) -> Self: - """Sets the thumbnail for the embed content. - - This function returns the class instance to allow for fluent-style - chaining. - - .. versionchanged:: 1.4 - Passing ``None`` removes the thumbnail. - - Parameters - ----------- - url: :class:`str` - The source URL for the thumbnail. Only HTTP(S) is supported. - Inline attachment URLs are also supported, see :ref:`local_image`. - """ - - if url is None: - try: - del self._thumbnail - except AttributeError: - pass - else: - self._thumbnail = { - 'url': str(url), - } - - return self - - @property - def video(self) -> _EmbedVideoProxy: - """Returns an ``EmbedProxy`` denoting the video contents. - - Possible attributes include: - - - ``url`` for the video URL. - - ``height`` for the video height. - - ``width`` for the video width. - - If the attribute has no value then ``None`` is returned. - """ - # Lying to the type checker for better developer UX. - return EmbedProxy(getattr(self, '_video', {})) # type: ignore - - @property - def provider(self) -> _EmbedProviderProxy: - """Returns an ``EmbedProxy`` denoting the provider contents. - - The only attributes that might be accessed are ``name`` and ``url``. - - If the attribute has no value then ``None`` is returned. - """ - # Lying to the type checker for better developer UX. - return EmbedProxy(getattr(self, '_provider', {})) # type: ignore - - @property - def author(self) -> _EmbedAuthorProxy: - """Returns an ``EmbedProxy`` denoting the author contents. - - See :meth:`set_author` for possible values you can access. - - If the attribute has no value then ``None`` is returned. - """ - # Lying to the type checker for better developer UX. - return EmbedProxy(getattr(self, '_author', {})) # type: ignore - - def set_author(self, *, name: Any, url: Optional[Any] = None, icon_url: Optional[Any] = None) -> Self: - """Sets the author for the embed content. - - This function returns the class instance to allow for fluent-style - chaining. - - Parameters - ----------- - name: :class:`str` - The name of the author. Can only be up to 256 characters. - url: :class:`str` - The URL for the author. - icon_url: :class:`str` - The URL of the author icon. Only HTTP(S) is supported. - Inline attachment URLs are also supported, see :ref:`local_image`. - """ - - self._author = { - 'name': str(name), - } - - if url is not None: - self._author['url'] = str(url) - - if icon_url is not None: - self._author['icon_url'] = str(icon_url) - - return self - - def remove_author(self) -> Self: - """Clears embed's author information. - - This function returns the class instance to allow for fluent-style - chaining. - - .. versionadded:: 1.4 - """ - try: - del self._author - except AttributeError: - pass - - return self - - @property - def fields(self) -> List[_EmbedFieldProxy]: - """List[``EmbedProxy``]: Returns a :class:`list` of ``EmbedProxy`` denoting the field contents. - - See :meth:`add_field` for possible values you can access. - - If the attribute has no value then ``None`` is returned. - """ - # Lying to the type checker for better developer UX. - return [EmbedProxy(d) for d in getattr(self, '_fields', [])] # type: ignore - - def add_field(self, *, name: Any, value: Any, inline: bool = True) -> Self: - """Adds a field to the embed object. - - This function returns the class instance to allow for fluent-style - chaining. Can only be up to 25 fields. - - Parameters - ----------- - name: :class:`str` - The name of the field. Can only be up to 256 characters. - value: :class:`str` - The value of the field. Can only be up to 1024 characters. - inline: :class:`bool` - Whether the field should be displayed inline. - """ - - field = { - 'inline': inline, - 'name': str(name), - 'value': str(value), - } - - try: - self._fields.append(field) - except AttributeError: - self._fields = [field] - - return self - - def insert_field_at(self, index: int, *, name: Any, value: Any, inline: bool = True) -> Self: - """Inserts a field before a specified index to the embed. - - This function returns the class instance to allow for fluent-style - chaining. Can only be up to 25 fields. - - .. versionadded:: 1.2 - - Parameters - ----------- - index: :class:`int` - The index of where to insert the field. - name: :class:`str` - The name of the field. Can only be up to 256 characters. - value: :class:`str` - The value of the field. Can only be up to 1024 characters. - inline: :class:`bool` - Whether the field should be displayed inline. - """ - - field = { - 'inline': inline, - 'name': str(name), - 'value': str(value), - } - - try: - self._fields.insert(index, field) - except AttributeError: - self._fields = [field] - - return self - - def clear_fields(self) -> Self: - """Removes all fields from this embed. - - This function returns the class instance to allow for fluent-style - chaining. - - .. versionchanged:: 2.0 - This function now returns the class instance. - """ - try: - self._fields.clear() - except AttributeError: - self._fields = [] - - return self - - def remove_field(self, index: int) -> Self: - """Removes a field at a specified index. - - If the index is invalid or out of bounds then the error is - silently swallowed. - - This function returns the class instance to allow for fluent-style - chaining. - - .. note:: - - When deleting a field by index, the index of the other fields - shift to fill the gap just like a regular list. - - .. versionchanged:: 2.0 - This function now returns the class instance. - - Parameters - ----------- - index: :class:`int` - The index of the field to remove. - """ - try: - del self._fields[index] - except (AttributeError, IndexError): - pass - - return self - - def set_field_at(self, index: int, *, name: Any, value: Any, inline: bool = True) -> Self: - """Modifies a field to the embed object. - - The index must point to a valid pre-existing field. Can only be up to 25 fields. - - This function returns the class instance to allow for fluent-style - chaining. - - Parameters - ----------- - index: :class:`int` - The index of the field to modify. - name: :class:`str` - The name of the field. Can only be up to 256 characters. - value: :class:`str` - The value of the field. Can only be up to 1024 characters. - inline: :class:`bool` - Whether the field should be displayed inline. - - Raises - ------- - IndexError - An invalid index was provided. - """ - - try: - field = self._fields[index] - except (TypeError, IndexError, AttributeError): - raise IndexError('field index out of range') - - field['name'] = str(name) - field['value'] = str(value) - field['inline'] = inline - return self - - def to_dict(self) -> EmbedData: - """Converts this embed object into a dict.""" - - # add in the raw data into the dict - # fmt: off - result = { - key[1:]: getattr(self, key) - for key in self.__slots__ - if key[0] == '_' and hasattr(self, key) - } - # fmt: on - - # deal with basic convenience wrappers - - try: - colour = result.pop('colour') - except KeyError: - pass - else: - if colour: - result['color'] = colour.value - - try: - timestamp = result.pop('timestamp') - except KeyError: - pass - else: - if timestamp: - if timestamp.tzinfo: - result['timestamp'] = timestamp.astimezone(tz=datetime.timezone.utc).isoformat() - else: - result['timestamp'] = timestamp.replace(tzinfo=datetime.timezone.utc).isoformat() - - # add in the non raw attribute ones - if self.type: - result['type'] = self.type - - if self.description: - result['description'] = self.description - - if self.url: - result['url'] = self.url - - if self.title: - result['title'] = self.title - - return result # type: ignore # This payload is equivalent to the EmbedData type diff --git a/.venv/Lib/site-packages/discord/emoji.py b/.venv/Lib/site-packages/discord/emoji.py deleted file mode 100644 index 35875fa..0000000 --- a/.venv/Lib/site-packages/discord/emoji.py +++ /dev/null @@ -1,259 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations -from typing import Any, Collection, Iterator, List, Optional, TYPE_CHECKING, Tuple - -from .asset import Asset, AssetMixin -from .utils import SnowflakeList, snowflake_time, MISSING -from .partial_emoji import _EmojiTag, PartialEmoji -from .user import User - -# fmt: off -__all__ = ( - 'Emoji', -) -# fmt: on - -if TYPE_CHECKING: - from .types.emoji import Emoji as EmojiPayload - from .guild import Guild - from .state import ConnectionState - from .abc import Snowflake - from .role import Role - from datetime import datetime - - -class Emoji(_EmojiTag, AssetMixin): - """Represents a custom emoji. - - Depending on the way this object was created, some of the attributes can - have a value of ``None``. - - .. container:: operations - - .. describe:: x == y - - Checks if two emoji are the same. - - .. describe:: x != y - - Checks if two emoji are not the same. - - .. describe:: hash(x) - - Return the emoji's hash. - - .. describe:: iter(x) - - Returns an iterator of ``(field, value)`` pairs. This allows this class - to be used as an iterable in list/dict/etc constructions. - - .. describe:: str(x) - - Returns the emoji rendered for discord. - - Attributes - ----------- - name: :class:`str` - The name of the emoji. - id: :class:`int` - The emoji's ID. - require_colons: :class:`bool` - If colons are required to use this emoji in the client (:PJSalt: vs PJSalt). - animated: :class:`bool` - Whether an emoji is animated or not. - managed: :class:`bool` - If this emoji is managed by a Twitch integration. - guild_id: :class:`int` - The guild ID the emoji belongs to. - available: :class:`bool` - Whether the emoji is available for use. - user: Optional[:class:`User`] - The user that created the emoji. This can only be retrieved using :meth:`Guild.fetch_emoji` and - having the :attr:`~Permissions.manage_emojis` permission. - """ - - __slots__: Tuple[str, ...] = ( - 'require_colons', - 'animated', - 'managed', - 'id', - 'name', - '_roles', - 'guild_id', - '_state', - 'user', - 'available', - ) - - def __init__(self, *, guild: Guild, state: ConnectionState, data: EmojiPayload) -> None: - self.guild_id: int = guild.id - self._state: ConnectionState = state - self._from_data(data) - - def _from_data(self, emoji: EmojiPayload) -> None: - self.require_colons: bool = emoji.get('require_colons', False) - self.managed: bool = emoji.get('managed', False) - self.id: int = int(emoji['id']) # type: ignore # This won't be None for full emoji objects. - self.name: str = emoji['name'] # type: ignore # This won't be None for full emoji objects. - self.animated: bool = emoji.get('animated', False) - self.available: bool = emoji.get('available', True) - self._roles: SnowflakeList = SnowflakeList(map(int, emoji.get('roles', []))) - user = emoji.get('user') - self.user: Optional[User] = User(state=self._state, data=user) if user else None - - def _to_partial(self) -> PartialEmoji: - return PartialEmoji(name=self.name, animated=self.animated, id=self.id) - - def __iter__(self) -> Iterator[Tuple[str, Any]]: - for attr in self.__slots__: - if attr[0] != '_': - value = getattr(self, attr, None) - if value is not None: - yield (attr, value) - - def __str__(self) -> str: - if self.animated: - return f'' - return f'<:{self.name}:{self.id}>' - - def __repr__(self) -> str: - return f'' - - def __eq__(self, other: object) -> bool: - return isinstance(other, _EmojiTag) and self.id == other.id - - def __ne__(self, other: object) -> bool: - return not self.__eq__(other) - - def __hash__(self) -> int: - return self.id >> 22 - - @property - def created_at(self) -> datetime: - """:class:`datetime.datetime`: Returns the emoji's creation time in UTC.""" - return snowflake_time(self.id) - - @property - def url(self) -> str: - """:class:`str`: Returns the URL of the emoji.""" - fmt = 'gif' if self.animated else 'png' - return f'{Asset.BASE}/emojis/{self.id}.{fmt}' - - @property - def roles(self) -> List[Role]: - """List[:class:`Role`]: A :class:`list` of roles that is allowed to use this emoji. - - If roles is empty, the emoji is unrestricted. - """ - guild = self.guild - if guild is None: - return [] - - return [role for role in guild.roles if self._roles.has(role.id)] - - @property - def guild(self) -> Optional[Guild]: - """:class:`Guild`: The guild this emoji belongs to.""" - return self._state._get_guild(self.guild_id) - - def is_usable(self) -> bool: - """:class:`bool`: Whether the bot can use this emoji. - - .. versionadded:: 1.3 - """ - if not self.available or not self.guild or self.guild.unavailable: - return False - if not self._roles: - return True - emoji_roles, my_roles = self._roles, self.guild.me._roles - return any(my_roles.has(role_id) for role_id in emoji_roles) - - async def delete(self, *, reason: Optional[str] = None) -> None: - """|coro| - - Deletes the custom emoji. - - You must have :attr:`~Permissions.manage_emojis` permission to - do this. - - Parameters - ----------- - reason: Optional[:class:`str`] - The reason for deleting this emoji. Shows up on the audit log. - - Raises - ------- - Forbidden - You are not allowed to delete emojis. - HTTPException - An error occurred deleting the emoji. - """ - - await self._state.http.delete_custom_emoji(self.guild_id, self.id, reason=reason) - - async def edit( - self, *, name: str = MISSING, roles: Collection[Snowflake] = MISSING, reason: Optional[str] = None - ) -> Emoji: - r"""|coro| - - Edits the custom emoji. - - You must have :attr:`~Permissions.manage_emojis` permission to - do this. - - .. versionchanged:: 2.0 - The newly updated emoji is returned. - - Parameters - ----------- - name: :class:`str` - The new emoji name. - roles: List[:class:`~discord.abc.Snowflake`] - A list of roles that can use this emoji. An empty list can be passed to make it available to everyone. - reason: Optional[:class:`str`] - The reason for editing this emoji. Shows up on the audit log. - - Raises - ------- - Forbidden - You are not allowed to edit emojis. - HTTPException - An error occurred editing the emoji. - - Returns - -------- - :class:`Emoji` - The newly updated emoji. - """ - - payload = {} - if name is not MISSING: - payload['name'] = name - if roles is not MISSING: - payload['roles'] = [role.id for role in roles] - - data = await self._state.http.edit_custom_emoji(self.guild_id, self.id, payload=payload, reason=reason) - return Emoji(guild=self.guild, data=data, state=self._state) # type: ignore # if guild is None, the http request would have failed diff --git a/.venv/Lib/site-packages/discord/enums.py b/.venv/Lib/site-packages/discord/enums.py deleted file mode 100644 index 0368e96..0000000 --- a/.venv/Lib/site-packages/discord/enums.py +++ /dev/null @@ -1,741 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" -from __future__ import annotations - -import types -from collections import namedtuple -from typing import Any, ClassVar, Dict, List, Optional, TYPE_CHECKING, Tuple, Type, TypeVar, Iterator, Mapping - -__all__ = ( - 'Enum', - 'ChannelType', - 'MessageType', - 'SpeakingState', - 'VerificationLevel', - 'ContentFilter', - 'Status', - 'DefaultAvatar', - 'AuditLogAction', - 'AuditLogActionCategory', - 'UserFlags', - 'ActivityType', - 'NotificationLevel', - 'TeamMembershipState', - 'WebhookType', - 'ExpireBehaviour', - 'ExpireBehavior', - 'StickerType', - 'StickerFormatType', - 'InviteTarget', - 'VideoQualityMode', - 'ComponentType', - 'ButtonStyle', - 'TextStyle', - 'PrivacyLevel', - 'InteractionType', - 'InteractionResponseType', - 'NSFWLevel', - 'MFALevel', - 'Locale', - 'EntityType', - 'EventStatus', - 'AppCommandType', - 'AppCommandOptionType', - 'AppCommandPermissionType', - 'AutoModRuleTriggerType', - 'AutoModRuleEventType', - 'AutoModRuleActionType', -) - -if TYPE_CHECKING: - from typing_extensions import Self - - -def _create_value_cls(name: str, comparable: bool): - # All the type ignores here are due to the type checker being unable to recognise - # Runtime type creation without exploding. - cls = namedtuple('_EnumValue_' + name, 'name value') - cls.__repr__ = lambda self: f'<{name}.{self.name}: {self.value!r}>' # type: ignore - cls.__str__ = lambda self: f'{name}.{self.name}' # type: ignore - if comparable: - cls.__le__ = lambda self, other: isinstance(other, self.__class__) and self.value <= other.value # type: ignore - cls.__ge__ = lambda self, other: isinstance(other, self.__class__) and self.value >= other.value # type: ignore - cls.__lt__ = lambda self, other: isinstance(other, self.__class__) and self.value < other.value # type: ignore - cls.__gt__ = lambda self, other: isinstance(other, self.__class__) and self.value > other.value # type: ignore - return cls - - -def _is_descriptor(obj): - return hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj, '__delete__') - - -class EnumMeta(type): - if TYPE_CHECKING: - __name__: ClassVar[str] - _enum_member_names_: ClassVar[List[str]] - _enum_member_map_: ClassVar[Dict[str, Any]] - _enum_value_map_: ClassVar[Dict[Any, Any]] - - def __new__(cls, name: str, bases: Tuple[type, ...], attrs: Dict[str, Any], *, comparable: bool = False) -> Self: - value_mapping = {} - member_mapping = {} - member_names = [] - - value_cls = _create_value_cls(name, comparable) - for key, value in list(attrs.items()): - is_descriptor = _is_descriptor(value) - if key[0] == '_' and not is_descriptor: - continue - - # Special case classmethod to just pass through - if isinstance(value, classmethod): - continue - - if is_descriptor: - setattr(value_cls, key, value) - del attrs[key] - continue - - try: - new_value = value_mapping[value] - except KeyError: - new_value = value_cls(name=key, value=value) - value_mapping[value] = new_value - member_names.append(key) - - member_mapping[key] = new_value - attrs[key] = new_value - - attrs['_enum_value_map_'] = value_mapping - attrs['_enum_member_map_'] = member_mapping - attrs['_enum_member_names_'] = member_names - attrs['_enum_value_cls_'] = value_cls - actual_cls = super().__new__(cls, name, bases, attrs) - value_cls._actual_enum_cls_ = actual_cls # type: ignore # Runtime attribute isn't understood - return actual_cls - - def __iter__(cls) -> Iterator[Any]: - return (cls._enum_member_map_[name] for name in cls._enum_member_names_) - - def __reversed__(cls) -> Iterator[Any]: - return (cls._enum_member_map_[name] for name in reversed(cls._enum_member_names_)) - - def __len__(cls) -> int: - return len(cls._enum_member_names_) - - def __repr__(cls) -> str: - return f'' - - @property - def __members__(cls) -> Mapping[str, Any]: - return types.MappingProxyType(cls._enum_member_map_) - - def __call__(cls, value: str) -> Any: - try: - return cls._enum_value_map_[value] - except (KeyError, TypeError): - raise ValueError(f"{value!r} is not a valid {cls.__name__}") - - def __getitem__(cls, key: str) -> Any: - return cls._enum_member_map_[key] - - def __setattr__(cls, name: str, value: Any) -> None: - raise TypeError('Enums are immutable.') - - def __delattr__(cls, attr: str) -> None: - raise TypeError('Enums are immutable') - - def __instancecheck__(self, instance: Any) -> bool: - # isinstance(x, Y) - # -> __instancecheck__(Y, x) - try: - return instance._actual_enum_cls_ is self - except AttributeError: - return False - - -if TYPE_CHECKING: - from enum import Enum -else: - - class Enum(metaclass=EnumMeta): - @classmethod - def try_value(cls, value): - try: - return cls._enum_value_map_[value] - except (KeyError, TypeError): - return value - - -class ChannelType(Enum): - text = 0 - private = 1 - voice = 2 - group = 3 - category = 4 - news = 5 - news_thread = 10 - public_thread = 11 - private_thread = 12 - stage_voice = 13 - forum = 15 - - def __str__(self) -> str: - return self.name - - -class MessageType(Enum): - default = 0 - recipient_add = 1 - recipient_remove = 2 - call = 3 - channel_name_change = 4 - channel_icon_change = 5 - pins_add = 6 - new_member = 7 - premium_guild_subscription = 8 - premium_guild_tier_1 = 9 - premium_guild_tier_2 = 10 - premium_guild_tier_3 = 11 - channel_follow_add = 12 - guild_stream = 13 - guild_discovery_disqualified = 14 - guild_discovery_requalified = 15 - guild_discovery_grace_period_initial_warning = 16 - guild_discovery_grace_period_final_warning = 17 - thread_created = 18 - reply = 19 - chat_input_command = 20 - thread_starter_message = 21 - guild_invite_reminder = 22 - context_menu_command = 23 - auto_moderation_action = 24 - - -class SpeakingState(Enum): - none = 0 - voice = 1 - soundshare = 2 - priority = 4 - - def __str__(self) -> str: - return self.name - - def __int__(self) -> int: - return self.value - - -class VerificationLevel(Enum, comparable=True): - none = 0 - low = 1 - medium = 2 - high = 3 - highest = 4 - - def __str__(self) -> str: - return self.name - - -class ContentFilter(Enum, comparable=True): - disabled = 0 - no_role = 1 - all_members = 2 - - def __str__(self) -> str: - return self.name - - -class Status(Enum): - online = 'online' - offline = 'offline' - idle = 'idle' - dnd = 'dnd' - do_not_disturb = 'dnd' - invisible = 'invisible' - - def __str__(self) -> str: - return self.value - - -class DefaultAvatar(Enum): - blurple = 0 - grey = 1 - gray = 1 - green = 2 - orange = 3 - red = 4 - - def __str__(self) -> str: - return self.name - - -class NotificationLevel(Enum, comparable=True): - all_messages = 0 - only_mentions = 1 - - -class AuditLogActionCategory(Enum): - create = 1 - delete = 2 - update = 3 - - -class AuditLogAction(Enum): - # fmt: off - guild_update = 1 - channel_create = 10 - channel_update = 11 - channel_delete = 12 - overwrite_create = 13 - overwrite_update = 14 - overwrite_delete = 15 - kick = 20 - member_prune = 21 - ban = 22 - unban = 23 - member_update = 24 - member_role_update = 25 - member_move = 26 - member_disconnect = 27 - bot_add = 28 - role_create = 30 - role_update = 31 - role_delete = 32 - invite_create = 40 - invite_update = 41 - invite_delete = 42 - webhook_create = 50 - webhook_update = 51 - webhook_delete = 52 - emoji_create = 60 - emoji_update = 61 - emoji_delete = 62 - message_delete = 72 - message_bulk_delete = 73 - message_pin = 74 - message_unpin = 75 - integration_create = 80 - integration_update = 81 - integration_delete = 82 - stage_instance_create = 83 - stage_instance_update = 84 - stage_instance_delete = 85 - sticker_create = 90 - sticker_update = 91 - sticker_delete = 92 - scheduled_event_create = 100 - scheduled_event_update = 101 - scheduled_event_delete = 102 - thread_create = 110 - thread_update = 111 - thread_delete = 112 - app_command_permission_update = 121 - automod_rule_create = 140 - automod_rule_update = 141 - automod_rule_delete = 142 - automod_block_message = 143 - # fmt: on - - @property - def category(self) -> Optional[AuditLogActionCategory]: - # fmt: off - lookup: Dict[AuditLogAction, Optional[AuditLogActionCategory]] = { - AuditLogAction.guild_update: AuditLogActionCategory.update, - AuditLogAction.channel_create: AuditLogActionCategory.create, - AuditLogAction.channel_update: AuditLogActionCategory.update, - AuditLogAction.channel_delete: AuditLogActionCategory.delete, - AuditLogAction.overwrite_create: AuditLogActionCategory.create, - AuditLogAction.overwrite_update: AuditLogActionCategory.update, - AuditLogAction.overwrite_delete: AuditLogActionCategory.delete, - AuditLogAction.kick: None, - AuditLogAction.member_prune: None, - AuditLogAction.ban: None, - AuditLogAction.unban: None, - AuditLogAction.member_update: AuditLogActionCategory.update, - AuditLogAction.member_role_update: AuditLogActionCategory.update, - AuditLogAction.member_move: None, - AuditLogAction.member_disconnect: None, - AuditLogAction.bot_add: None, - AuditLogAction.role_create: AuditLogActionCategory.create, - AuditLogAction.role_update: AuditLogActionCategory.update, - AuditLogAction.role_delete: AuditLogActionCategory.delete, - AuditLogAction.invite_create: AuditLogActionCategory.create, - AuditLogAction.invite_update: AuditLogActionCategory.update, - AuditLogAction.invite_delete: AuditLogActionCategory.delete, - AuditLogAction.webhook_create: AuditLogActionCategory.create, - AuditLogAction.webhook_update: AuditLogActionCategory.update, - AuditLogAction.webhook_delete: AuditLogActionCategory.delete, - AuditLogAction.emoji_create: AuditLogActionCategory.create, - AuditLogAction.emoji_update: AuditLogActionCategory.update, - AuditLogAction.emoji_delete: AuditLogActionCategory.delete, - AuditLogAction.message_delete: AuditLogActionCategory.delete, - AuditLogAction.message_bulk_delete: AuditLogActionCategory.delete, - AuditLogAction.message_pin: None, - AuditLogAction.message_unpin: None, - AuditLogAction.integration_create: AuditLogActionCategory.create, - AuditLogAction.integration_update: AuditLogActionCategory.update, - AuditLogAction.integration_delete: AuditLogActionCategory.delete, - AuditLogAction.stage_instance_create: AuditLogActionCategory.create, - AuditLogAction.stage_instance_update: AuditLogActionCategory.update, - AuditLogAction.stage_instance_delete: AuditLogActionCategory.delete, - AuditLogAction.sticker_create: AuditLogActionCategory.create, - AuditLogAction.sticker_update: AuditLogActionCategory.update, - AuditLogAction.sticker_delete: AuditLogActionCategory.delete, - AuditLogAction.scheduled_event_create: AuditLogActionCategory.create, - AuditLogAction.scheduled_event_update: AuditLogActionCategory.update, - AuditLogAction.scheduled_event_delete: AuditLogActionCategory.delete, - AuditLogAction.thread_create: AuditLogActionCategory.create, - AuditLogAction.thread_delete: AuditLogActionCategory.delete, - AuditLogAction.thread_update: AuditLogActionCategory.update, - AuditLogAction.app_command_permission_update: AuditLogActionCategory.update, - AuditLogAction.automod_rule_create: AuditLogActionCategory.create, - AuditLogAction.automod_rule_update: AuditLogActionCategory.update, - AuditLogAction.automod_rule_delete: AuditLogActionCategory.delete, - AuditLogAction.automod_block_message: None, - } - # fmt: on - return lookup[self] - - @property - def target_type(self) -> Optional[str]: - v = self.value - if v == -1: - return 'all' - elif v < 10: - return 'guild' - elif v < 20: - return 'channel' - elif v < 30: - return 'user' - elif v < 40: - return 'role' - elif v < 50: - return 'invite' - elif v < 60: - return 'webhook' - elif v < 70: - return 'emoji' - elif v == 73: - return 'channel' - elif v < 80: - return 'message' - elif v < 83: - return 'integration' - elif v < 90: - return 'stage_instance' - elif v < 93: - return 'sticker' - elif v < 103: - return 'guild_scheduled_event' - elif v < 113: - return 'thread' - elif v < 122: - return 'integration_or_app_command' - elif v < 143: - return 'auto_moderation' - elif v == 143: - return 'user' - - -class UserFlags(Enum): - staff = 1 - partner = 2 - hypesquad = 4 - bug_hunter = 8 - mfa_sms = 16 - premium_promo_dismissed = 32 - hypesquad_bravery = 64 - hypesquad_brilliance = 128 - hypesquad_balance = 256 - early_supporter = 512 - team_user = 1024 - system = 4096 - has_unread_urgent_messages = 8192 - bug_hunter_level_2 = 16384 - verified_bot = 65536 - verified_bot_developer = 131072 - discord_certified_moderator = 262144 - bot_http_interactions = 524288 - spammer = 1048576 - - -class ActivityType(Enum): - unknown = -1 - playing = 0 - streaming = 1 - listening = 2 - watching = 3 - custom = 4 - competing = 5 - - def __int__(self) -> int: - return self.value - - -class TeamMembershipState(Enum): - invited = 1 - accepted = 2 - - -class WebhookType(Enum): - incoming = 1 - channel_follower = 2 - application = 3 - - -class ExpireBehaviour(Enum): - remove_role = 0 - kick = 1 - - -ExpireBehavior = ExpireBehaviour - - -class StickerType(Enum): - standard = 1 - guild = 2 - - -class StickerFormatType(Enum): - png = 1 - apng = 2 - lottie = 3 - - @property - def file_extension(self) -> str: - # fmt: off - lookup: Dict[StickerFormatType, str] = { - StickerFormatType.png: 'png', - StickerFormatType.apng: 'png', - StickerFormatType.lottie: 'json', - } - # fmt: on - return lookup[self] - - -class InviteTarget(Enum): - unknown = 0 - stream = 1 - embedded_application = 2 - - -class InteractionType(Enum): - ping = 1 - application_command = 2 - component = 3 - autocomplete = 4 - modal_submit = 5 - - -class InteractionResponseType(Enum): - pong = 1 - # ack = 2 (deprecated) - # channel_message = 3 (deprecated) - channel_message = 4 # (with source) - deferred_channel_message = 5 # (with source) - deferred_message_update = 6 # for components - message_update = 7 # for components - autocomplete_result = 8 - modal = 9 # for modals - - -class VideoQualityMode(Enum): - auto = 1 - full = 2 - - def __int__(self) -> int: - return self.value - - -class ComponentType(Enum): - action_row = 1 - button = 2 - select = 3 - text_input = 4 - - def __int__(self) -> int: - return self.value - - -class ButtonStyle(Enum): - primary = 1 - secondary = 2 - success = 3 - danger = 4 - link = 5 - - # Aliases - blurple = 1 - grey = 2 - gray = 2 - green = 3 - red = 4 - url = 5 - - def __int__(self) -> int: - return self.value - - -class TextStyle(Enum): - short = 1 - paragraph = 2 - - # Aliases - long = 2 - - def __int__(self) -> int: - return self.value - - -class PrivacyLevel(Enum): - guild_only = 2 - - -class NSFWLevel(Enum, comparable=True): - default = 0 - explicit = 1 - safe = 2 - age_restricted = 3 - - -class MFALevel(Enum, comparable=True): - disabled = 0 - require_2fa = 1 - - -class Locale(Enum): - american_english = 'en-US' - british_english = 'en-GB' - bulgarian = 'bg' - chinese = 'zh-CN' - taiwan_chinese = 'zh-TW' - croatian = 'hr' - czech = 'cs' - danish = 'da' - dutch = 'nl' - finnish = 'fi' - french = 'fr' - german = 'de' - greek = 'el' - hindi = 'hi' - hungarian = 'hu' - italian = 'it' - japanese = 'ja' - korean = 'ko' - lithuanian = 'lt' - norwegian = 'no' - polish = 'pl' - brazil_portuguese = 'pt-BR' - romanian = 'ro' - russian = 'ru' - spain_spanish = 'es-ES' - swedish = 'sv-SE' - thai = 'th' - turkish = 'tr' - ukrainian = 'uk' - vietnamese = 'vi' - - def __str__(self) -> str: - return self.value - - -E = TypeVar('E', bound='Enum') - - -class EntityType(Enum): - stage_instance = 1 - voice = 2 - external = 3 - - -class EventStatus(Enum): - scheduled = 1 - active = 2 - completed = 3 - canceled = 4 - - ended = 3 - cancelled = 4 - - -class AppCommandOptionType(Enum): - subcommand = 1 - subcommand_group = 2 - string = 3 - integer = 4 - boolean = 5 - user = 6 - channel = 7 - role = 8 - mentionable = 9 - number = 10 - attachment = 11 - - -class AppCommandType(Enum): - chat_input = 1 - user = 2 - message = 3 - - -class AppCommandPermissionType(Enum): - role = 1 - user = 2 - channel = 3 - - -class AutoModRuleTriggerType(Enum): - keyword = 1 - harmful_link = 2 - spam = 3 - keyword_preset = 4 - mention_spam = 5 - - -class AutoModRuleEventType(Enum): - message_send = 1 - - -class AutoModRuleActionType(Enum): - block_message = 1 - send_alert_message = 2 - timeout = 3 - - -def create_unknown_value(cls: Type[E], val: Any) -> E: - value_cls = cls._enum_value_cls_ # type: ignore # This is narrowed below - name = f'unknown_{val}' - return value_cls(name=name, value=val) - - -def try_enum(cls: Type[E], val: Any) -> E: - """A function that tries to turn the value into enum ``cls``. - - If it fails it returns a proxy invalid value instead. - """ - - try: - return cls._enum_value_map_[val] # type: ignore # All errors are caught below - except (KeyError, TypeError, AttributeError): - return create_unknown_value(cls, val) diff --git a/.venv/Lib/site-packages/discord/errors.py b/.venv/Lib/site-packages/discord/errors.py deleted file mode 100644 index 6035ace..0000000 --- a/.venv/Lib/site-packages/discord/errors.py +++ /dev/null @@ -1,280 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations -from typing import Dict, List, Optional, TYPE_CHECKING, Any, Tuple, Union - -if TYPE_CHECKING: - from aiohttp import ClientResponse, ClientWebSocketResponse - from requests import Response - - _ResponseType = Union[ClientResponse, Response] - - from .interactions import Interaction - -__all__ = ( - 'DiscordException', - 'ClientException', - 'GatewayNotFound', - 'HTTPException', - 'RateLimited', - 'Forbidden', - 'NotFound', - 'DiscordServerError', - 'InvalidData', - 'LoginFailure', - 'ConnectionClosed', - 'PrivilegedIntentsRequired', - 'InteractionResponded', -) - - -class DiscordException(Exception): - """Base exception class for discord.py - - Ideally speaking, this could be caught to handle any exceptions raised from this library. - """ - - pass - - -class ClientException(DiscordException): - """Exception that's raised when an operation in the :class:`Client` fails. - - These are usually for exceptions that happened due to user input. - """ - - pass - - -class GatewayNotFound(DiscordException): - """An exception that is raised when the gateway for Discord could not be found""" - - def __init__(self): - message = 'The gateway to connect to discord was not found.' - super().__init__(message) - - -def _flatten_error_dict(d: Dict[str, Any], key: str = '') -> Dict[str, str]: - items: List[Tuple[str, str]] = [] - for k, v in d.items(): - new_key = key + '.' + k if key else k - - if isinstance(v, dict): - try: - _errors: List[Dict[str, Any]] = v['_errors'] - except KeyError: - items.extend(_flatten_error_dict(v, new_key).items()) - else: - items.append((new_key, ' '.join(x.get('message', '') for x in _errors))) - else: - items.append((new_key, v)) - - return dict(items) - - -class HTTPException(DiscordException): - """Exception that's raised when an HTTP request operation fails. - - Attributes - ------------ - response: :class:`aiohttp.ClientResponse` - The response of the failed HTTP request. This is an - instance of :class:`aiohttp.ClientResponse`. In some cases - this could also be a :class:`requests.Response`. - - text: :class:`str` - The text of the error. Could be an empty string. - status: :class:`int` - The status code of the HTTP request. - code: :class:`int` - The Discord specific error code for the failure. - """ - - def __init__(self, response: _ResponseType, message: Optional[Union[str, Dict[str, Any]]]): - self.response: _ResponseType = response - self.status: int = response.status # type: ignore # This attribute is filled by the library even if using requests - self.code: int - self.text: str - if isinstance(message, dict): - self.code = message.get('code', 0) - base = message.get('message', '') - errors = message.get('errors') - self._errors: Optional[Dict[str, Any]] = errors - if errors: - errors = _flatten_error_dict(errors) - helpful = '\n'.join('In %s: %s' % t for t in errors.items()) - self.text = base + '\n' + helpful - else: - self.text = base - else: - self.text = message or '' - self.code = 0 - - fmt = '{0.status} {0.reason} (error code: {1})' - if len(self.text): - fmt += ': {2}' - - super().__init__(fmt.format(self.response, self.code, self.text)) - - -class RateLimited(DiscordException): - """Exception that's raised for when status code 429 occurs - and the timeout is greater than the configured maximum using - the ``max_ratelimit_timeout`` parameter in :class:`Client`. - - This is not raised during global ratelimits. - - Since sometimes requests are halted pre-emptively before they're - even made, this **does not** subclass :exc:`HTTPException`. - - .. versionadded:: 2.0 - - Attributes - ------------ - retry_after: :class:`float` - The amount of seconds that the client should wait before retrying - the request. - """ - - def __init__(self, retry_after: float): - self.retry_after = retry_after - super().__init__(f'Too many requests. Retry in {retry_after:.2f} seconds.') - - -class Forbidden(HTTPException): - """Exception that's raised for when status code 403 occurs. - - Subclass of :exc:`HTTPException` - """ - - pass - - -class NotFound(HTTPException): - """Exception that's raised for when status code 404 occurs. - - Subclass of :exc:`HTTPException` - """ - - pass - - -class DiscordServerError(HTTPException): - """Exception that's raised for when a 500 range status code occurs. - - Subclass of :exc:`HTTPException`. - - .. versionadded:: 1.5 - """ - - pass - - -class InvalidData(ClientException): - """Exception that's raised when the library encounters unknown - or invalid data from Discord. - """ - - pass - - -class LoginFailure(ClientException): - """Exception that's raised when the :meth:`Client.login` function - fails to log you in from improper credentials or some other misc. - failure. - """ - - pass - - -class ConnectionClosed(ClientException): - """Exception that's raised when the gateway connection is - closed for reasons that could not be handled internally. - - Attributes - ----------- - code: :class:`int` - The close code of the websocket. - reason: :class:`str` - The reason provided for the closure. - shard_id: Optional[:class:`int`] - The shard ID that got closed if applicable. - """ - - def __init__(self, socket: ClientWebSocketResponse, *, shard_id: Optional[int], code: Optional[int] = None): - # This exception is just the same exception except - # reconfigured to subclass ClientException for users - self.code: int = code or socket.close_code or -1 - # aiohttp doesn't seem to consistently provide close reason - self.reason: str = '' - self.shard_id: Optional[int] = shard_id - super().__init__(f'Shard ID {self.shard_id} WebSocket closed with {self.code}') - - -class PrivilegedIntentsRequired(ClientException): - """Exception that's raised when the gateway is requesting privileged intents - but they're not ticked in the developer page yet. - - Go to https://discord.com/developers/applications/ and enable the intents - that are required. Currently these are as follows: - - - :attr:`Intents.members` - - :attr:`Intents.presences` - - :attr:`Intents.message_content` - - Attributes - ----------- - shard_id: Optional[:class:`int`] - The shard ID that got closed if applicable. - """ - - def __init__(self, shard_id: Optional[int]): - self.shard_id: Optional[int] = shard_id - msg = ( - 'Shard ID %s is requesting privileged intents that have not been explicitly enabled in the ' - 'developer portal. It is recommended to go to https://discord.com/developers/applications/ ' - 'and explicitly enable the privileged intents within your application\'s page. If this is not ' - 'possible, then consider disabling the privileged intents instead.' - ) - super().__init__(msg % shard_id) - - -class InteractionResponded(ClientException): - """Exception that's raised when sending another interaction response using - :class:`InteractionResponse` when one has already been done before. - - An interaction can only respond once. - - .. versionadded:: 2.0 - - Attributes - ----------- - interaction: :class:`Interaction` - The interaction that's already been responded to. - """ - - def __init__(self, interaction: Interaction): - self.interaction: Interaction = interaction - super().__init__('This interaction has already been responded to before') diff --git a/.venv/Lib/site-packages/discord/ext/commands/__init__.py b/.venv/Lib/site-packages/discord/ext/commands/__init__.py deleted file mode 100644 index 08dab54..0000000 --- a/.venv/Lib/site-packages/discord/ext/commands/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -""" -discord.ext.commands -~~~~~~~~~~~~~~~~~~~~~ - -An extension module to facilitate creation of bot commands. - -:copyright: (c) 2015-present Rapptz -:license: MIT, see LICENSE for more details. -""" - -from .bot import * -from .cog import * -from .context import * -from .converter import * -from .cooldowns import * -from .core import * -from .errors import * -from .flags import * -from .help import * -from .parameters import * -from .hybrid import * diff --git a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/__init__.cpython-38.pyc b/.venv/Lib/site-packages/discord/ext/commands/__pycache__/__init__.cpython-38.pyc deleted file mode 100644 index 9f3eb8d..0000000 Binary files a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/__init__.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/_types.cpython-38.pyc b/.venv/Lib/site-packages/discord/ext/commands/__pycache__/_types.cpython-38.pyc deleted file mode 100644 index 300005e..0000000 Binary files a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/_types.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/bot.cpython-38.pyc b/.venv/Lib/site-packages/discord/ext/commands/__pycache__/bot.cpython-38.pyc deleted file mode 100644 index f07f208..0000000 Binary files a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/bot.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/cog.cpython-38.pyc b/.venv/Lib/site-packages/discord/ext/commands/__pycache__/cog.cpython-38.pyc deleted file mode 100644 index 774c279..0000000 Binary files a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/cog.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/context.cpython-38.pyc b/.venv/Lib/site-packages/discord/ext/commands/__pycache__/context.cpython-38.pyc deleted file mode 100644 index 77cd9b2..0000000 Binary files a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/context.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/converter.cpython-38.pyc b/.venv/Lib/site-packages/discord/ext/commands/__pycache__/converter.cpython-38.pyc deleted file mode 100644 index e089834..0000000 Binary files a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/converter.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/cooldowns.cpython-38.pyc b/.venv/Lib/site-packages/discord/ext/commands/__pycache__/cooldowns.cpython-38.pyc deleted file mode 100644 index 2681bf4..0000000 Binary files a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/cooldowns.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/core.cpython-38.pyc b/.venv/Lib/site-packages/discord/ext/commands/__pycache__/core.cpython-38.pyc deleted file mode 100644 index b43d3c5..0000000 Binary files a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/core.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/errors.cpython-38.pyc b/.venv/Lib/site-packages/discord/ext/commands/__pycache__/errors.cpython-38.pyc deleted file mode 100644 index ed5ac39..0000000 Binary files a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/errors.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/flags.cpython-38.pyc b/.venv/Lib/site-packages/discord/ext/commands/__pycache__/flags.cpython-38.pyc deleted file mode 100644 index cc7b938..0000000 Binary files a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/flags.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/help.cpython-38.pyc b/.venv/Lib/site-packages/discord/ext/commands/__pycache__/help.cpython-38.pyc deleted file mode 100644 index ddfef82..0000000 Binary files a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/help.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/hybrid.cpython-38.pyc b/.venv/Lib/site-packages/discord/ext/commands/__pycache__/hybrid.cpython-38.pyc deleted file mode 100644 index e3aeaba..0000000 Binary files a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/hybrid.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/parameters.cpython-38.pyc b/.venv/Lib/site-packages/discord/ext/commands/__pycache__/parameters.cpython-38.pyc deleted file mode 100644 index 1bfd999..0000000 Binary files a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/parameters.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/view.cpython-38.pyc b/.venv/Lib/site-packages/discord/ext/commands/__pycache__/view.cpython-38.pyc deleted file mode 100644 index 3055617..0000000 Binary files a/.venv/Lib/site-packages/discord/ext/commands/__pycache__/view.cpython-38.pyc and /dev/null differ diff --git a/.venv/Lib/site-packages/discord/ext/commands/_types.py b/.venv/Lib/site-packages/discord/ext/commands/_types.py deleted file mode 100644 index 1331c9f..0000000 --- a/.venv/Lib/site-packages/discord/ext/commands/_types.py +++ /dev/null @@ -1,73 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - - -from typing import Any, Awaitable, Callable, Coroutine, TYPE_CHECKING, Protocol, TypeVar, Union, Tuple, Optional - - -T = TypeVar('T') - -if TYPE_CHECKING: - from typing_extensions import ParamSpec - - from .bot import Bot, AutoShardedBot - from .context import Context - from .cog import Cog - from .errors import CommandError - - P = ParamSpec('P') - MaybeAwaitableFunc = Callable[P, 'MaybeAwaitable[T]'] -else: - P = TypeVar('P') - MaybeAwaitableFunc = Tuple[P, T] - -_Bot = Union['Bot', 'AutoShardedBot'] -Coro = Coroutine[Any, Any, T] -CoroFunc = Callable[..., Coro[Any]] -MaybeCoro = Union[T, Coro[T]] -MaybeAwaitable = Union[T, Awaitable[T]] - -CogT = TypeVar('CogT', bound='Optional[Cog]') -UserCheck = Callable[["ContextT"], MaybeCoro[bool]] -Hook = Union[Callable[["CogT", "ContextT"], Coro[Any]], Callable[["ContextT"], Coro[Any]]] -Error = Union[Callable[["CogT", "ContextT", "CommandError"], Coro[Any]], Callable[["ContextT", "CommandError"], Coro[Any]]] - -ContextT = TypeVar('ContextT', bound='Context[Any]') -BotT = TypeVar('BotT', bound=_Bot, covariant=True) - -ContextT_co = TypeVar('ContextT_co', bound='Context[Any]', covariant=True) - - -class Check(Protocol[ContextT_co]): # type: ignore # TypeVar is expected to be invariant - - predicate: Callable[[ContextT_co], Coroutine[Any, Any, bool]] - - def __call__(self, coro_or_commands: T) -> T: - ... - - -# This is merely a tag type to avoid circular import issues. -# Yes, this is a terrible solution but ultimately it is the only solution. -class _BaseCommand: - __slots__ = () diff --git a/.venv/Lib/site-packages/discord/ext/commands/bot.py b/.venv/Lib/site-packages/discord/ext/commands/bot.py deleted file mode 100644 index 050e2c4..0000000 --- a/.venv/Lib/site-packages/discord/ext/commands/bot.py +++ /dev/null @@ -1,1497 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations - - -import asyncio -import collections -import collections.abc -import inspect -import importlib.util -import sys -import logging -import types -from typing import ( - Any, - Callable, - Mapping, - List, - Dict, - TYPE_CHECKING, - Optional, - TypeVar, - Type, - Union, - Iterable, - Collection, - overload, -) - -import discord -from discord import app_commands -from discord.app_commands.tree import _retrieve_guild_ids -from discord.utils import MISSING, _is_submodule - -from .core import GroupMixin -from .view import StringView -from .context import Context -from . import errors -from .help import HelpCommand, DefaultHelpCommand -from .cog import Cog -from .hybrid import hybrid_command, hybrid_group, HybridCommand, HybridGroup - -if TYPE_CHECKING: - from typing_extensions import Self - - import importlib.machinery - - from discord.message import Message - from discord.interactions import Interaction - from discord.abc import User, Snowflake - from ._types import ( - _Bot, - BotT, - UserCheck, - CoroFunc, - ContextT, - MaybeAwaitableFunc, - ) - from .core import Command - from .hybrid import CommandCallback, ContextT, P - - _Prefix = Union[Iterable[str], str] - _PrefixCallable = MaybeAwaitableFunc[[BotT, Message], _Prefix] - PrefixType = Union[_Prefix, _PrefixCallable[BotT]] - -__all__ = ( - 'when_mentioned', - 'when_mentioned_or', - 'Bot', - 'AutoShardedBot', -) - -T = TypeVar('T') -CFT = TypeVar('CFT', bound='CoroFunc') - -_log = logging.getLogger(__name__) - - -def when_mentioned(bot: _Bot, msg: Message, /) -> List[str]: - """A callable that implements a command prefix equivalent to being mentioned. - - These are meant to be passed into the :attr:`.Bot.command_prefix` attribute. - - .. versionchanged:: 2.0 - - ``bot`` and ``msg`` parameters are now positional-only. - """ - # bot.user will never be None when this is called - return [f'<@{bot.user.id}> ', f'<@!{bot.user.id}> '] # type: ignore - - -def when_mentioned_or(*prefixes: str) -> Callable[[_Bot, Message], List[str]]: - """A callable that implements when mentioned or other prefixes provided. - - These are meant to be passed into the :attr:`.Bot.command_prefix` attribute. - - Example - -------- - - .. code-block:: python3 - - bot = commands.Bot(command_prefix=commands.when_mentioned_or('!')) - - - .. note:: - - This callable returns another callable, so if this is done inside a custom - callable, you must call the returned callable, for example: - - .. code-block:: python3 - - async def get_prefix(bot, message): - extras = await prefixes_for(message.guild) # returns a list - return commands.when_mentioned_or(*extras)(bot, message) - - - See Also - ---------- - :func:`.when_mentioned` - """ - - def inner(bot, msg): - r = list(prefixes) - r = when_mentioned(bot, msg) + r - return r - - return inner - - -class _DefaultRepr: - def __repr__(self): - return '' - - -_default: Any = _DefaultRepr() - - -class BotBase(GroupMixin[None]): - def __init__( - self, - command_prefix: PrefixType[BotT], - *, - help_command: Optional[HelpCommand] = _default, - tree_cls: Type[app_commands.CommandTree[Any]] = app_commands.CommandTree, - description: Optional[str] = None, - intents: discord.Intents, - **options: Any, - ) -> None: - super().__init__(intents=intents, **options) - self.command_prefix: PrefixType[BotT] = command_prefix - self.extra_events: Dict[str, List[CoroFunc]] = {} - # Self doesn't have the ClientT bound, but since this is a mixin it technically does - self.__tree: app_commands.CommandTree[Self] = tree_cls(self) # type: ignore - self.__cogs: Dict[str, Cog] = {} - self.__extensions: Dict[str, types.ModuleType] = {} - self._checks: List[UserCheck] = [] - self._check_once: List[UserCheck] = [] - self._before_invoke: Optional[CoroFunc] = None - self._after_invoke: Optional[CoroFunc] = None - self._help_command: Optional[HelpCommand] = None - self.description: str = inspect.cleandoc(description) if description else '' - self.owner_id: Optional[int] = options.get('owner_id') - self.owner_ids: Optional[Collection[int]] = options.get('owner_ids', set()) - self.strip_after_prefix: bool = options.get('strip_after_prefix', False) - - if self.owner_id and self.owner_ids: - raise TypeError('Both owner_id and owner_ids are set.') - - if self.owner_ids and not isinstance(self.owner_ids, collections.abc.Collection): - raise TypeError(f'owner_ids must be a collection not {self.owner_ids.__class__!r}') - - if help_command is _default: - self.help_command = DefaultHelpCommand() - else: - self.help_command = help_command - - # internal helpers - - async def _async_setup_hook(self) -> None: - # self/super() resolves to Client/AutoShardedClient - await super()._async_setup_hook() # type: ignore - prefix = self.command_prefix - - # This has to be here because for the default logging set up to capture - # the logging calls, they have to come after the `Client.run` call. - # The best place to do this is in an async init scenario - if not self.intents.message_content: # type: ignore - trigger_warning = ( - (callable(prefix) and prefix is not when_mentioned) - or isinstance(prefix, str) - or (isinstance(prefix, collections.abc.Iterable) and len(list(prefix)) >= 1) - ) - if trigger_warning: - _log.warning('Privileged message content intent is missing, commands may not work as expected.') - - def dispatch(self, event_name: str, /, *args: Any, **kwargs: Any) -> None: - # super() will resolve to Client - super().dispatch(event_name, *args, **kwargs) # type: ignore - ev = 'on_' + event_name - for event in self.extra_events.get(ev, []): - self._schedule_event(event, ev, *args, **kwargs) # type: ignore - - @discord.utils.copy_doc(discord.Client.close) - async def close(self) -> None: - for extension in tuple(self.__extensions): - try: - await self.unload_extension(extension) - except Exception: - pass - - for cog in tuple(self.__cogs): - try: - await self.remove_cog(cog) - except Exception: - pass - - await super().close() # type: ignore - - # GroupMixin overrides - - @discord.utils.copy_doc(GroupMixin.add_command) - def add_command(self, command: Command[Any, ..., Any], /) -> None: - super().add_command(command) - if isinstance(command, (HybridCommand, HybridGroup)) and command.app_command: - # If a cog is also inheriting from app_commands.Group then it'll also - # add the hybrid commands as text commands, which would recursively add the - # hybrid commands as slash commands. This check just terminates that recursion - # from happening - if command.cog is None or not command.cog.__cog_is_app_commands_group__: - self.tree.add_command(command.app_command) - - @discord.utils.copy_doc(GroupMixin.remove_command) - def remove_command(self, name: str, /) -> Optional[Command[Any, ..., Any]]: - cmd: Optional[Command[Any, ..., Any]] = super().remove_command(name) - if isinstance(cmd, (HybridCommand, HybridGroup)) and cmd.app_command: - # See above - if cmd.cog is not None and cmd.cog.__cog_is_app_commands_group__: - return cmd - - guild_ids: Optional[List[int]] = cmd.app_command._guild_ids - if guild_ids is None: - self.__tree.remove_command(name) - else: - for guild_id in guild_ids: - self.__tree.remove_command(name, guild=discord.Object(id=guild_id)) - - return cmd - - def hybrid_command( - self, - name: Union[str, app_commands.locale_str] = MISSING, - with_app_command: bool = True, - *args: Any, - **kwargs: Any, - ) -> Callable[[CommandCallback[Any, ContextT, P, T]], HybridCommand[Any, P, T]]: - """A shortcut decorator that invokes :func:`~discord.ext.commands.hybrid_command` and adds it to - the internal command list via :meth:`add_command`. - - Returns - -------- - Callable[..., :class:`HybridCommand`] - A decorator that converts the provided method into a Command, adds it to the bot, then returns it. - """ - - def decorator(func: CommandCallback[Any, ContextT, P, T]): - kwargs.setdefault('parent', self) - result = hybrid_command(name=name, *args, with_app_command=with_app_command, **kwargs)(func) - self.add_command(result) - return result - - return decorator - - def hybrid_group( - self, - name: Union[str, app_commands.locale_str] = MISSING, - with_app_command: bool = True, - *args: Any, - **kwargs: Any, - ) -> Callable[[CommandCallback[Any, ContextT, P, T]], HybridGroup[Any, P, T]]: - """A shortcut decorator that invokes :func:`~discord.ext.commands.hybrid_group` and adds it to - the internal command list via :meth:`add_command`. - - Returns - -------- - Callable[..., :class:`HybridGroup`] - A decorator that converts the provided method into a Group, adds it to the bot, then returns it. - """ - - def decorator(func: CommandCallback[Any, ContextT, P, T]): - kwargs.setdefault('parent', self) - result = hybrid_group(name=name, *args, with_app_command=with_app_command, **kwargs)(func) - self.add_command(result) - return result - - return decorator - - # Error handler - - async def on_command_error(self, context: Context[BotT], exception: errors.CommandError, /) -> None: - """|coro| - - The default command error handler provided by the bot. - - By default this logs to the library logger, however it could be - overridden to have a different implementation. - - This only fires if you do not specify any listeners for command error. - - .. versionchanged:: 2.0 - - ``context`` and ``exception`` parameters are now positional-only. - Instead of writing to ``sys.stderr`` this now uses the library logger. - """ - if self.extra_events.get('on_command_error', None): - return - - command = context.command - if command and command.has_error_handler(): - return - - cog = context.cog - if cog and cog.has_error_handler(): - return - - _log.error('Ignoring exception in command %s', command, exc_info=exception) - - # global check registration - - def check(self, func: T, /) -> T: - r"""A decorator that adds a global check to the bot. - - A global check is similar to a :func:`.check` that is applied - on a per command basis except it is run before any command checks - have been verified and applies to every command the bot has. - - .. note:: - - This function can either be a regular function or a coroutine. - - Similar to a command :func:`.check`\, this takes a single parameter - of type :class:`.Context` and can only raise exceptions inherited from - :exc:`.CommandError`. - - Example - --------- - - .. code-block:: python3 - - @bot.check - def check_commands(ctx): - return ctx.command.qualified_name in allowed_commands - - .. versionchanged:: 2.0 - - ``func`` parameter is now positional-only. - """ - # T was used instead of Check to ensure the type matches on return - self.add_check(func) # type: ignore - return func - - def add_check(self, func: UserCheck[ContextT], /, *, call_once: bool = False) -> None: - """Adds a global check to the bot. - - This is the non-decorator interface to :meth:`.check` - and :meth:`.check_once`. - - .. versionchanged:: 2.0 - - ``func`` parameter is now positional-only. - - .. seealso:: The :func:`~discord.ext.commands.check` decorator - - Parameters - ----------- - func - The function that was used as a global check. - call_once: :class:`bool` - If the function should only be called once per - :meth:`.invoke` call. - """ - - if call_once: - self._check_once.append(func) - else: - self._checks.append(func) - - def remove_check(self, func: UserCheck[ContextT], /, *, call_once: bool = False) -> None: - """Removes a global check from the bot. - - This function is idempotent and will not raise an exception - if the function is not in the global checks. - - .. versionchanged:: 2.0 - - ``func`` parameter is now positional-only. - - Parameters - ----------- - func - The function to remove from the global checks. - call_once: :class:`bool` - If the function was added with ``call_once=True`` in - the :meth:`.Bot.add_check` call or using :meth:`.check_once`. - """ - l = self._check_once if call_once else self._checks - - try: - l.remove(func) - except ValueError: - pass - - def check_once(self, func: CFT, /) -> CFT: - r"""A decorator that adds a "call once" global check to the bot. - - Unlike regular global checks, this one is called only once - per :meth:`.invoke` call. - - Regular global checks are called whenever a command is called - or :meth:`.Command.can_run` is called. This type of check - bypasses that and ensures that it's called only once, even inside - the default help command. - - .. note:: - - When using this function the :class:`.Context` sent to a group subcommand - may only parse the parent command and not the subcommands due to it - being invoked once per :meth:`.Bot.invoke` call. - - .. note:: - - This function can either be a regular function or a coroutine. - - Similar to a command :func:`.check`\, this takes a single parameter - of type :class:`.Context` and can only raise exceptions inherited from - :exc:`.CommandError`. - - Example - --------- - - .. code-block:: python3 - - @bot.check_once - def whitelist(ctx): - return ctx.message.author.id in my_whitelist - - .. versionchanged:: 2.0 - - ``func`` parameter is now positional-only. - - """ - self.add_check(func, call_once=True) - return func - - async def can_run(self, ctx: Context[BotT], /, *, call_once: bool = False) -> bool: - data = self._check_once if call_once else self._checks - - if len(data) == 0: - return True - - return await discord.utils.async_all(f(ctx) for f in data) - - async def is_owner(self, user: User, /) -> bool: - """|coro| - - Checks if a :class:`~discord.User` or :class:`~discord.Member` is the owner of - this bot. - - If an :attr:`owner_id` is not set, it is fetched automatically - through the use of :meth:`~.Bot.application_info`. - - .. versionchanged:: 1.3 - The function also checks if the application is team-owned if - :attr:`owner_ids` is not set. - - .. versionchanged:: 2.0 - - ``user`` parameter is now positional-only. - - Parameters - ----------- - user: :class:`.abc.User` - The user to check for. - - Returns - -------- - :class:`bool` - Whether the user is the owner. - """ - - if self.owner_id: - return user.id == self.owner_id - elif self.owner_ids: - return user.id in self.owner_ids - else: - - app = await self.application_info() # type: ignore - if app.team: - self.owner_ids = ids = {m.id for m in app.team.members} - return user.id in ids - else: - self.owner_id = owner_id = app.owner.id - return user.id == owner_id - - def before_invoke(self, coro: CFT, /) -> CFT: - """A decorator that registers a coroutine as a pre-invoke hook. - - A pre-invoke hook is called directly before the command is - called. This makes it a useful function to set up database - connections or any type of set up required. - - This pre-invoke hook takes a sole parameter, a :class:`.Context`. - - .. note:: - - The :meth:`~.Bot.before_invoke` and :meth:`~.Bot.after_invoke` hooks are - only called if all checks and argument parsing procedures pass - without error. If any check or argument parsing procedures fail - then the hooks are not called. - - .. versionchanged:: 2.0 - - ``coro`` parameter is now positional-only. - - Parameters - ----------- - coro: :ref:`coroutine ` - The coroutine to register as the pre-invoke hook. - - Raises - ------- - TypeError - The coroutine passed is not actually a coroutine. - """ - if not asyncio.iscoroutinefunction(coro): - raise TypeError('The pre-invoke hook must be a coroutine.') - - self._before_invoke = coro - return coro - - def after_invoke(self, coro: CFT, /) -> CFT: - r"""A decorator that registers a coroutine as a post-invoke hook. - - A post-invoke hook is called directly after the command is - called. This makes it a useful function to clean-up database - connections or any type of clean up required. - - This post-invoke hook takes a sole parameter, a :class:`.Context`. - - .. note:: - - Similar to :meth:`~.Bot.before_invoke`\, this is not called unless - checks and argument parsing procedures succeed. This hook is, - however, **always** called regardless of the internal command - callback raising an error (i.e. :exc:`.CommandInvokeError`\). - This makes it ideal for clean-up scenarios. - - .. versionchanged:: 2.0 - - ``coro`` parameter is now positional-only. - - Parameters - ----------- - coro: :ref:`coroutine ` - The coroutine to register as the post-invoke hook. - - Raises - ------- - TypeError - The coroutine passed is not actually a coroutine. - """ - if not asyncio.iscoroutinefunction(coro): - raise TypeError('The post-invoke hook must be a coroutine.') - - self._after_invoke = coro - return coro - - # listener registration - - def add_listener(self, func: CoroFunc, /, name: str = MISSING) -> None: - """The non decorator alternative to :meth:`.listen`. - - .. versionchanged:: 2.0 - - ``func`` parameter is now positional-only. - - Parameters - ----------- - func: :ref:`coroutine ` - The function to call. - name: :class:`str` - The name of the event to listen for. Defaults to ``func.__name__``. - - Example - -------- - - .. code-block:: python3 - - async def on_ready(): pass - async def my_message(message): pass - - bot.add_listener(on_ready) - bot.add_listener(my_message, 'on_message') - - """ - name = func.__name__ if name is MISSING else name - - if not asyncio.iscoroutinefunction(func): - raise TypeError('Listeners must be coroutines') - - if name in self.extra_events: - self.extra_events[name].append(func) - else: - self.extra_events[name] = [func] - - def remove_listener(self, func: CoroFunc, /, name: str = MISSING) -> None: - """Removes a listener from the pool of listeners. - - .. versionchanged:: 2.0 - - ``func`` parameter is now positional-only. - - Parameters - ----------- - func - The function that was used as a listener to remove. - name: :class:`str` - The name of the event we want to remove. Defaults to - ``func.__name__``. - """ - - name = func.__name__ if name is MISSING else name - - if name in self.extra_events: - try: - self.extra_events[name].remove(func) - except ValueError: - pass - - def listen(self, name: str = MISSING) -> Callable[[CFT], CFT]: - """A decorator that registers another function as an external - event listener. Basically this allows you to listen to multiple - events from different places e.g. such as :func:`.on_ready` - - The functions being listened to must be a :ref:`coroutine `. - - Example - -------- - - .. code-block:: python3 - - @bot.listen() - async def on_message(message): - print('one') - - # in some other file... - - @bot.listen('on_message') - async def my_message(message): - print('two') - - Would print one and two in an unspecified order. - - Raises - ------- - TypeError - The function being listened to is not a coroutine. - """ - - def decorator(func: CFT) -> CFT: - self.add_listener(func, name) - return func - - return decorator - - # cogs - - async def add_cog( - self, - cog: Cog, - /, - *, - override: bool = False, - guild: Optional[Snowflake] = MISSING, - guilds: List[Snowflake] = MISSING, - ) -> None: - """|coro| - - Adds a "cog" to the bot. - - A cog is a class that has its own event listeners and commands. - - If the cog is a :class:`.app_commands.Group` then it is added to - the bot's :class:`~discord.app_commands.CommandTree` as well. - - .. note:: - - Exceptions raised inside a :class:`.Cog`'s :meth:`~.Cog.cog_load` method will be - propagated to the caller. - - .. versionchanged:: 2.0 - - :exc:`.ClientException` is raised when a cog with the same name - is already loaded. - - .. versionchanged:: 2.0 - - ``cog`` parameter is now positional-only. - - .. versionchanged:: 2.0 - - This method is now a :term:`coroutine`. - - Parameters - ----------- - cog: :class:`.Cog` - The cog to register to the bot. - override: :class:`bool` - If a previously loaded cog with the same name should be ejected - instead of raising an error. - - .. versionadded:: 2.0 - guild: Optional[:class:`~discord.abc.Snowflake`] - If the cog is an application command group, then this would be the - guild where the cog group would be added to. If not given then - it becomes a global command instead. - - .. versionadded:: 2.0 - guilds: List[:class:`~discord.abc.Snowflake`] - If the cog is an application command group, then this would be the - guilds where the cog group would be added to. If not given then - it becomes a global command instead. Cannot be mixed with - ``guild``. - - .. versionadded:: 2.0 - - Raises - ------- - TypeError - The cog does not inherit from :class:`.Cog`. - CommandError - An error happened during loading. - ClientException - A cog with the same name is already loaded. - """ - - if not isinstance(cog, Cog): - raise TypeError('cogs must derive from Cog') - - cog_name = cog.__cog_name__ - existing = self.__cogs.get(cog_name) - - if existing is not None: - if not override: - raise discord.ClientException(f'Cog named {cog_name!r} already loaded') - await self.remove_cog(cog_name, guild=guild, guilds=guilds) - - if cog.__cog_app_commands_group__: - self.__tree.add_command(cog.__cog_app_commands_group__, override=override, guild=guild, guilds=guilds) - - cog = await cog._inject(self, override=override, guild=guild, guilds=guilds) - self.__cogs[cog_name] = cog - - def get_cog(self, name: str, /) -> Optional[Cog]: - """Gets the cog instance requested. - - If the cog is not found, ``None`` is returned instead. - - .. versionchanged:: 2.0 - - ``name`` parameter is now positional-only. - - Parameters - ----------- - name: :class:`str` - The name of the cog you are requesting. - This is equivalent to the name passed via keyword - argument in class creation or the class name if unspecified. - - Returns - -------- - Optional[:class:`Cog`] - The cog that was requested. If not found, returns ``None``. - """ - return self.__cogs.get(name) - - async def remove_cog( - self, - name: str, - /, - *, - guild: Optional[Snowflake] = MISSING, - guilds: List[Snowflake] = MISSING, - ) -> Optional[Cog]: - """|coro| - - Removes a cog from the bot and returns it. - - All registered commands and event listeners that the - cog has registered will be removed as well. - - If no cog is found then this method has no effect. - - .. versionchanged:: 2.0 - - ``name`` parameter is now positional-only. - - .. versionchanged:: 2.0 - - This method is now a :term:`coroutine`. - - Parameters - ----------- - name: :class:`str` - The name of the cog to remove. - guild: Optional[:class:`~discord.abc.Snowflake`] - If the cog is an application command group, then this would be the - guild where the cog group would be removed from. If not given then - a global command is removed instead instead. - - .. versionadded:: 2.0 - guilds: List[:class:`~discord.abc.Snowflake`] - If the cog is an application command group, then this would be the - guilds where the cog group would be removed from. If not given then - a global command is removed instead instead. Cannot be mixed with - ``guild``. - - .. versionadded:: 2.0 - - Returns - ------- - Optional[:class:`.Cog`] - The cog that was removed. ``None`` if not found. - """ - - cog = self.__cogs.pop(name, None) - if cog is None: - return - - help_command = self._help_command - if help_command and help_command.cog is cog: - help_command.cog = None - - guild_ids = _retrieve_guild_ids(cog, guild, guilds) - if cog.__cog_app_commands_group__: - if guild_ids is None: - self.__tree.remove_command(name) - else: - for guild_id in guild_ids: - self.__tree.remove_command(name, guild=discord.Object(guild_id)) - - await cog._eject(self, guild_ids=guild_ids) - - return cog - - @property - def cogs(self) -> Mapping[str, Cog]: - """Mapping[:class:`str`, :class:`Cog`]: A read-only mapping of cog name to cog.""" - return types.MappingProxyType(self.__cogs) - - # extensions - - async def _remove_module_references(self, name: str) -> None: - # find all references to the module - # remove the cogs registered from the module - for cogname, cog in self.__cogs.copy().items(): - if _is_submodule(name, cog.__module__): - await self.remove_cog(cogname) - - # remove all the commands from the module - for cmd in self.all_commands.copy().values(): - if cmd.module is not None and _is_submodule(name, cmd.module): - if isinstance(cmd, GroupMixin): - cmd.recursively_remove_all_commands() - self.remove_command(cmd.name) - - # remove all the listeners from the module - for event_list in self.extra_events.copy().values(): - remove = [] - for index, event in enumerate(event_list): - if event.__module__ is not None and _is_submodule(name, event.__module__): - remove.append(index) - - for index in reversed(remove): - del event_list[index] - - # remove all relevant application commands from the tree - self.__tree._remove_with_module(name) - - async def _call_module_finalizers(self, lib: types.ModuleType, key: str) -> None: - try: - func = getattr(lib, 'teardown') - except AttributeError: - pass - else: - try: - await func(self) - except Exception: - pass - finally: - self.__extensions.pop(key, None) - sys.modules.pop(key, None) - name = lib.__name__ - for module in list(sys.modules.keys()): - if _is_submodule(name, module): - del sys.modules[module] - - async def _load_from_module_spec(self, spec: importlib.machinery.ModuleSpec, key: str) -> None: - # precondition: key not in self.__extensions - lib = importlib.util.module_from_spec(spec) - sys.modules[key] = lib - try: - spec.loader.exec_module(lib) # type: ignore - except Exception as e: - del sys.modules[key] - raise errors.ExtensionFailed(key, e) from e - - try: - setup = getattr(lib, 'setup') - except AttributeError: - del sys.modules[key] - raise errors.NoEntryPointError(key) - - try: - await setup(self) - except Exception as e: - del sys.modules[key] - await self._remove_module_references(lib.__name__) - await self._call_module_finalizers(lib, key) - raise errors.ExtensionFailed(key, e) from e - else: - self.__extensions[key] = lib - - def _resolve_name(self, name: str, package: Optional[str]) -> str: - try: - return importlib.util.resolve_name(name, package) - except ImportError: - raise errors.ExtensionNotFound(name) - - async def load_extension(self, name: str, *, package: Optional[str] = None) -> None: - """|coro| - - Loads an extension. - - An extension is a python module that contains commands, cogs, or - listeners. - - An extension must have a global function, ``setup`` defined as - the entry point on what to do when the extension is loaded. This entry - point must have a single argument, the ``bot``. - - .. versionchanged:: 2.0 - - This method is now a :term:`coroutine`. - - Parameters - ------------ - name: :class:`str` - The extension name to load. It must be dot separated like - regular Python imports if accessing a sub-module. e.g. - ``foo.test`` if you want to import ``foo/test.py``. - package: Optional[:class:`str`] - The package name to resolve relative imports with. - This is required when loading an extension using a relative path, e.g ``.foo.test``. - Defaults to ``None``. - - .. versionadded:: 1.7 - - Raises - -------- - ExtensionNotFound - The extension could not be imported. - This is also raised if the name of the extension could not - be resolved using the provided ``package`` parameter. - ExtensionAlreadyLoaded - The extension is already loaded. - NoEntryPointError - The extension does not have a setup function. - ExtensionFailed - The extension or its setup function had an execution error. - """ - - name = self._resolve_name(name, package) - if name in self.__extensions: - raise errors.ExtensionAlreadyLoaded(name) - - spec = importlib.util.find_spec(name) - if spec is None: - raise errors.ExtensionNotFound(name) - - await self._load_from_module_spec(spec, name) - - async def unload_extension(self, name: str, *, package: Optional[str] = None) -> None: - """|coro| - - Unloads an extension. - - When the extension is unloaded, all commands, listeners, and cogs are - removed from the bot and the module is un-imported. - - The extension can provide an optional global function, ``teardown``, - to do miscellaneous clean-up if necessary. This function takes a single - parameter, the ``bot``, similar to ``setup`` from - :meth:`~.Bot.load_extension`. - - .. versionchanged:: 2.0 - - This method is now a :term:`coroutine`. - - Parameters - ------------ - name: :class:`str` - The extension name to unload. It must be dot separated like - regular Python imports if accessing a sub-module. e.g. - ``foo.test`` if you want to import ``foo/test.py``. - package: Optional[:class:`str`] - The package name to resolve relative imports with. - This is required when unloading an extension using a relative path, e.g ``.foo.test``. - Defaults to ``None``. - - .. versionadded:: 1.7 - - Raises - ------- - ExtensionNotFound - The name of the extension could not - be resolved using the provided ``package`` parameter. - ExtensionNotLoaded - The extension was not loaded. - """ - - name = self._resolve_name(name, package) - lib = self.__extensions.get(name) - if lib is None: - raise errors.ExtensionNotLoaded(name) - - await self._remove_module_references(lib.__name__) - await self._call_module_finalizers(lib, name) - - async def reload_extension(self, name: str, *, package: Optional[str] = None) -> None: - """Atomically reloads an extension. - - This replaces the extension with the same extension, only refreshed. This is - equivalent to a :meth:`unload_extension` followed by a :meth:`load_extension` - except done in an atomic way. That is, if an operation fails mid-reload then - the bot will roll-back to the prior working state. - - Parameters - ------------ - name: :class:`str` - The extension name to reload. It must be dot separated like - regular Python imports if accessing a sub-module. e.g. - ``foo.test`` if you want to import ``foo/test.py``. - package: Optional[:class:`str`] - The package name to resolve relative imports with. - This is required when reloading an extension using a relative path, e.g ``.foo.test``. - Defaults to ``None``. - - .. versionadded:: 1.7 - - Raises - ------- - ExtensionNotLoaded - The extension was not loaded. - ExtensionNotFound - The extension could not be imported. - This is also raised if the name of the extension could not - be resolved using the provided ``package`` parameter. - NoEntryPointError - The extension does not have a setup function. - ExtensionFailed - The extension setup function had an execution error. - """ - - name = self._resolve_name(name, package) - lib = self.__extensions.get(name) - if lib is None: - raise errors.ExtensionNotLoaded(name) - - # get the previous module states from sys modules - # fmt: off - modules = { - name: module - for name, module in sys.modules.items() - if _is_submodule(lib.__name__, name) - } - # fmt: on - - try: - # Unload and then load the module... - await self._remove_module_references(lib.__name__) - await self._call_module_finalizers(lib, name) - await self.load_extension(name) - except Exception: - # if the load failed, the remnants should have been - # cleaned from the load_extension function call - # so let's load it from our old compiled library. - await lib.setup(self) - self.__extensions[name] = lib - - # revert sys.modules back to normal and raise back to caller - sys.modules.update(modules) - raise - - @property - def extensions(self) -> Mapping[str, types.ModuleType]: - """Mapping[:class:`str`, :class:`py:types.ModuleType`]: A read-only mapping of extension name to extension.""" - return types.MappingProxyType(self.__extensions) - - # help command stuff - - @property - def help_command(self) -> Optional[HelpCommand]: - return self._help_command - - @help_command.setter - def help_command(self, value: Optional[HelpCommand]) -> None: - if value is not None: - if not isinstance(value, HelpCommand): - raise TypeError('help_command must be a subclass of HelpCommand') - if self._help_command is not None: - self._help_command._remove_from_bot(self) - self._help_command = value - value._add_to_bot(self) - elif self._help_command is not None: - self._help_command._remove_from_bot(self) - self._help_command = None - else: - self._help_command = None - - # application command interop - - # As mentioned above, this is a mixin so the Self type hint fails here. - # However, since the only classes that can use this are subclasses of Client - # anyway, then this is sound. - @property - def tree(self) -> app_commands.CommandTree[Self]: # type: ignore - """:class:`~discord.app_commands.CommandTree`: The command tree responsible for handling the application commands - in this bot. - - .. versionadded:: 2.0 - """ - return self.__tree - - # command processing - - async def get_prefix(self, message: Message, /) -> Union[List[str], str]: - """|coro| - - Retrieves the prefix the bot is listening to - with the message as a context. - - .. versionchanged:: 2.0 - - ``message`` parameter is now positional-only. - - Parameters - ----------- - message: :class:`discord.Message` - The message context to get the prefix of. - - Returns - -------- - Union[List[:class:`str`], :class:`str`] - A list of prefixes or a single prefix that the bot is - listening for. - """ - prefix = ret = self.command_prefix - - if callable(prefix): - # self will be a Bot or AutoShardedBot - ret = await discord.utils.maybe_coroutine(prefix, self, message) # type: ignore - - if not isinstance(ret, str): - try: - ret = list(ret) # type: ignore - except TypeError: - # It's possible that a generator raised this exception. Don't - # replace it with our own error if that's the case. - if isinstance(ret, collections.abc.Iterable): - raise - - raise TypeError( - "command_prefix must be plain string, iterable of strings, or callable " - f"returning either of these, not {ret.__class__.__name__}" - ) - - return ret - - @overload - async def get_context( - self, - origin: Union[Message, Interaction], - /, - ) -> Context[Self]: # type: ignore - ... - - @overload - async def get_context( - self, - origin: Union[Message, Interaction], - /, - *, - cls: Type[ContextT], - ) -> ContextT: - ... - - async def get_context( - self, - origin: Union[Message, Interaction], - /, - *, - cls: Type[ContextT] = MISSING, - ) -> Any: - r"""|coro| - - Returns the invocation context from the message or interaction. - - This is a more low-level counter-part for :meth:`.process_commands` - to allow users more fine grained control over the processing. - - The returned context is not guaranteed to be a valid invocation - context, :attr:`.Context.valid` must be checked to make sure it is. - If the context is not valid then it is not a valid candidate to be - invoked under :meth:`~.Bot.invoke`. - - .. note:: - - In order for the custom context to be used inside an interaction-based - context (such as :class:`HybridCommand`) then this method must be - overridden to return that class. - - .. versionchanged:: 2.0 - - ``message`` parameter is now positional-only and renamed to ``origin``. - - Parameters - ----------- - origin: Union[:class:`discord.Message`, :class:`discord.Interaction`] - The message or interaction to get the invocation context from. - cls - The factory class that will be used to create the context. - By default, this is :class:`.Context`. Should a custom - class be provided, it must be similar enough to :class:`.Context`\'s - interface. - - Returns - -------- - :class:`.Context` - The invocation context. The type of this can change via the - ``cls`` parameter. - """ - if cls is MISSING: - cls = Context # type: ignore - - if isinstance(origin, discord.Interaction): - return await cls.from_interaction(origin) - - view = StringView(origin.content) - ctx = cls(prefix=None, view=view, bot=self, message=origin) - - if origin.author.id == self.user.id: # type: ignore - return ctx - - prefix = await self.get_prefix(origin) - invoked_prefix = prefix - - if isinstance(prefix, str): - if not view.skip_string(prefix): - return ctx - else: - try: - # if the context class' __init__ consumes something from the view this - # will be wrong. That seems unreasonable though. - if origin.content.startswith(tuple(prefix)): - invoked_prefix = discord.utils.find(view.skip_string, prefix) - else: - return ctx - - except TypeError: - if not isinstance(prefix, list): - raise TypeError( - "get_prefix must return either a string or a list of string, " f"not {prefix.__class__.__name__}" - ) - - # It's possible a bad command_prefix got us here. - for value in prefix: - if not isinstance(value, str): - raise TypeError( - "Iterable command_prefix or list returned from get_prefix must " - f"contain only strings, not {value.__class__.__name__}" - ) - - # Getting here shouldn't happen - raise - - if self.strip_after_prefix: - view.skip_ws() - - invoker = view.get_word() - ctx.invoked_with = invoker - # type-checker fails to narrow invoked_prefix type. - ctx.prefix = invoked_prefix # type: ignore - ctx.command = self.all_commands.get(invoker) - return ctx - - async def invoke(self, ctx: Context[BotT], /) -> None: - """|coro| - - Invokes the command given under the invocation context and - handles all the internal event dispatch mechanisms. - - .. versionchanged:: 2.0 - - ``ctx`` parameter is now positional-only. - - Parameters - ----------- - ctx: :class:`.Context` - The invocation context to invoke. - """ - if ctx.command is not None: - self.dispatch('command', ctx) - try: - if await self.can_run(ctx, call_once=True): - await ctx.command.invoke(ctx) - else: - raise errors.CheckFailure('The global check once functions failed.') - except errors.CommandError as exc: - await ctx.command.dispatch_error(ctx, exc) - else: - self.dispatch('command_completion', ctx) - elif ctx.invoked_with: - exc = errors.CommandNotFound(f'Command "{ctx.invoked_with}" is not found') - self.dispatch('command_error', ctx, exc) - - async def process_commands(self, message: Message, /) -> None: - """|coro| - - This function processes the commands that have been registered - to the bot and other groups. Without this coroutine, none of the - commands will be triggered. - - By default, this coroutine is called inside the :func:`.on_message` - event. If you choose to override the :func:`.on_message` event, then - you should invoke this coroutine as well. - - This is built using other low level tools, and is equivalent to a - call to :meth:`~.Bot.get_context` followed by a call to :meth:`~.Bot.invoke`. - - This also checks if the message's author is a bot and doesn't - call :meth:`~.Bot.get_context` or :meth:`~.Bot.invoke` if so. - - .. versionchanged:: 2.0 - - ``message`` parameter is now positional-only. - - Parameters - ----------- - message: :class:`discord.Message` - The message to process commands for. - """ - if message.author.bot: - return - - ctx = await self.get_context(message) - # the type of the invocation context's bot attribute will be correct - await self.invoke(ctx) # type: ignore - - async def on_message(self, message: Message, /) -> None: - await self.process_commands(message) - - -class Bot(BotBase, discord.Client): - """Represents a Discord bot. - - This class is a subclass of :class:`discord.Client` and as a result - anything that you can do with a :class:`discord.Client` you can do with - this bot. - - This class also subclasses :class:`.GroupMixin` to provide the functionality - to manage commands. - - Unlike :class:`discord.Client`, this class does not require manually setting - a :class:`~discord.app_commands.CommandTree` and is automatically set upon - instantiating the class. - - .. container:: operations - - .. describe:: async with x - - Asynchronously initialises the bot and automatically cleans up. - - .. versionadded:: 2.0 - - Attributes - ----------- - command_prefix - The command prefix is what the message content must contain initially - to have a command invoked. This prefix could either be a string to - indicate what the prefix should be, or a callable that takes in the bot - as its first parameter and :class:`discord.Message` as its second - parameter and returns the prefix. This is to facilitate "dynamic" - command prefixes. This callable can be either a regular function or - a coroutine. - - An empty string as the prefix always matches, enabling prefix-less - command invocation. While this may be useful in DMs it should be avoided - in servers, as it's likely to cause performance issues and unintended - command invocations. - - The command prefix could also be an iterable of strings indicating that - multiple checks for the prefix should be used and the first one to - match will be the invocation prefix. You can get this prefix via - :attr:`.Context.prefix`. - - .. note:: - - When passing multiple prefixes be careful to not pass a prefix - that matches a longer prefix occurring later in the sequence. For - example, if the command prefix is ``('!', '!?')`` the ``'!?'`` - prefix will never be matched to any message as the previous one - matches messages starting with ``!?``. This is especially important - when passing an empty string, it should always be last as no prefix - after it will be matched. - case_insensitive: :class:`bool` - Whether the commands should be case insensitive. Defaults to ``False``. This - attribute does not carry over to groups. You must set it to every group if - you require group commands to be case insensitive as well. - description: :class:`str` - The content prefixed into the default help message. - help_command: Optional[:class:`.HelpCommand`] - The help command implementation to use. This can be dynamically - set at runtime. To remove the help command pass ``None``. For more - information on implementing a help command, see :ref:`ext_commands_help_command`. - owner_id: Optional[:class:`int`] - The user ID that owns the bot. If this is not set and is then queried via - :meth:`.is_owner` then it is fetched automatically using - :meth:`~.Bot.application_info`. - owner_ids: Optional[Collection[:class:`int`]] - The user IDs that owns the bot. This is similar to :attr:`owner_id`. - If this is not set and the application is team based, then it is - fetched automatically using :meth:`~.Bot.application_info`. - For performance reasons it is recommended to use a :class:`set` - for the collection. You cannot set both ``owner_id`` and ``owner_ids``. - - .. versionadded:: 1.3 - strip_after_prefix: :class:`bool` - Whether to strip whitespace characters after encountering the command - prefix. This allows for ``! hello`` and ``!hello`` to both work if - the ``command_prefix`` is set to ``!``. Defaults to ``False``. - - .. versionadded:: 1.7 - tree_cls: Type[:class:`~discord.app_commands.CommandTree`] - The type of application command tree to use. Defaults to :class:`~discord.app_commands.CommandTree`. - - .. versionadded:: 2.0 - """ - - pass - - -class AutoShardedBot(BotBase, discord.AutoShardedClient): - """This is similar to :class:`.Bot` except that it is inherited from - :class:`discord.AutoShardedClient` instead. - - .. container:: operations - - .. describe:: async with x - - Asynchronously initialises the bot and automatically cleans. - - .. versionadded:: 2.0 - """ - - pass diff --git a/.venv/Lib/site-packages/discord/ext/commands/cog.py b/.venv/Lib/site-packages/discord/ext/commands/cog.py deleted file mode 100644 index 6112a22..0000000 --- a/.venv/Lib/site-packages/discord/ext/commands/cog.py +++ /dev/null @@ -1,744 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" -from __future__ import annotations - -import inspect -import discord -from discord import app_commands -from discord.utils import maybe_coroutine - -from typing import ( - Any, - Callable, - ClassVar, - Coroutine, - Dict, - Generator, - Iterable, - List, - Optional, - TYPE_CHECKING, - Tuple, - TypeVar, - Union, -) - -from ._types import _BaseCommand, BotT - -if TYPE_CHECKING: - from typing_extensions import Self - from discord.abc import Snowflake - - from .bot import BotBase - from .context import Context - from .core import Command - -__all__ = ( - 'CogMeta', - 'Cog', - 'GroupCog', -) - -FuncT = TypeVar('FuncT', bound=Callable[..., Any]) - -MISSING: Any = discord.utils.MISSING - - -class CogMeta(type): - """A metaclass for defining a cog. - - Note that you should probably not use this directly. It is exposed - purely for documentation purposes along with making custom metaclasses to intermix - with other metaclasses such as the :class:`abc.ABCMeta` metaclass. - - For example, to create an abstract cog mixin class, the following would be done. - - .. code-block:: python3 - - import abc - - class CogABCMeta(commands.CogMeta, abc.ABCMeta): - pass - - class SomeMixin(metaclass=abc.ABCMeta): - pass - - class SomeCogMixin(SomeMixin, commands.Cog, metaclass=CogABCMeta): - pass - - .. note:: - - When passing an attribute of a metaclass that is documented below, note - that you must pass it as a keyword-only argument to the class creation - like the following example: - - .. code-block:: python3 - - class MyCog(commands.Cog, name='My Cog'): - pass - - Attributes - ----------- - name: :class:`str` - The cog name. By default, it is the name of the class with no modification. - description: :class:`str` - The cog description. By default, it is the cleaned docstring of the class. - - .. versionadded:: 1.6 - - command_attrs: :class:`dict` - A list of attributes to apply to every command inside this cog. The dictionary - is passed into the :class:`Command` options at ``__init__``. - If you specify attributes inside the command attribute in the class, it will - override the one specified inside this attribute. For example: - - .. code-block:: python3 - - class MyCog(commands.Cog, command_attrs=dict(hidden=True)): - @commands.command() - async def foo(self, ctx): - pass # hidden -> True - - @commands.command(hidden=False) - async def bar(self, ctx): - pass # hidden -> False - - group_name: Union[:class:`str`, :class:`~discord.app_commands.locale_str`] - The group name of a cog. This is only applicable for :class:`GroupCog` instances. - By default, it's the same value as :attr:`name`. - - .. versionadded:: 2.0 - group_description: Union[:class:`str`, :class:`~discord.app_commands.locale_str`] - The group description of a cog. This is only applicable for :class:`GroupCog` instances. - By default, it's the same value as :attr:`description`. - - .. versionadded:: 2.0 - group_nsfw: :class:`bool` - Whether the application command group is NSFW. This is only applicable for :class:`GroupCog` instances. - By default, it's ``False``. - - .. versionadded:: 2.0 - group_auto_locale_strings: :class:`bool` - If this is set to ``True``, then all translatable strings will implicitly - be wrapped into :class:`~discord.app_commands.locale_str` rather - than :class:`str`. Defaults to ``True``. - - .. versionadded:: 2.0 - """ - - __cog_name__: str - __cog_description__: str - __cog_group_name__: Union[str, app_commands.locale_str] - __cog_group_description__: Union[str, app_commands.locale_str] - __cog_group_nsfw__: bool - __cog_group_auto_locale_strings__: bool - __cog_settings__: Dict[str, Any] - __cog_commands__: List[Command[Any, ..., Any]] - __cog_app_commands__: List[Union[app_commands.Group, app_commands.Command[Any, ..., Any]]] - __cog_listeners__: List[Tuple[str, str]] - - def __new__(cls, *args: Any, **kwargs: Any) -> Self: - name, bases, attrs = args - if any(issubclass(base, app_commands.Group) for base in bases): - raise TypeError( - 'Cannot inherit from app_commands.Group with commands.Cog, consider using commands.GroupCog instead' - ) - - # If name='...' is given but not group_name='...' then name='...' is used for both. - # If neither is given then cog name is the class name but group name is kebab case - try: - cog_name = kwargs.pop('name') - except KeyError: - cog_name = name - try: - group_name = kwargs.pop('group_name') - except KeyError: - group_name = app_commands.commands._to_kebab_case(name) - else: - group_name = kwargs.pop('group_name', cog_name) - - attrs['__cog_settings__'] = kwargs.pop('command_attrs', {}) - attrs['__cog_name__'] = cog_name - attrs['__cog_group_name__'] = group_name - attrs['__cog_group_nsfw__'] = kwargs.pop('group_nsfw', False) - attrs['__cog_group_auto_locale_strings__'] = kwargs.pop('group_auto_locale_strings', True) - - description = kwargs.pop('description', None) - if description is None: - description = inspect.cleandoc(attrs.get('__doc__', '')) - - attrs['__cog_description__'] = description - attrs['__cog_group_description__'] = kwargs.pop('group_description', description or '\u2026') - - commands = {} - cog_app_commands = {} - listeners = {} - no_bot_cog = 'Commands or listeners must not start with cog_ or bot_ (in method {0.__name__}.{1})' - - new_cls = super().__new__(cls, name, bases, attrs, **kwargs) - for base in reversed(new_cls.__mro__): - for elem, value in base.__dict__.items(): - if elem in commands: - del commands[elem] - if elem in listeners: - del listeners[elem] - - is_static_method = isinstance(value, staticmethod) - if is_static_method: - value = value.__func__ - if isinstance(value, _BaseCommand): - if is_static_method: - raise TypeError(f'Command in method {base}.{elem!r} must not be staticmethod.') - if elem.startswith(('cog_', 'bot_')): - raise TypeError(no_bot_cog.format(base, elem)) - commands[elem] = value - elif isinstance(value, (app_commands.Group, app_commands.Command)) and value.parent is None: - if is_static_method: - raise TypeError(f'Command in method {base}.{elem!r} must not be staticmethod.') - if elem.startswith(('cog_', 'bot_')): - raise TypeError(no_bot_cog.format(base, elem)) - cog_app_commands[elem] = value - elif inspect.iscoroutinefunction(value): - try: - getattr(value, '__cog_listener__') - except AttributeError: - continue - else: - if elem.startswith(('cog_', 'bot_')): - raise TypeError(no_bot_cog.format(base, elem)) - listeners[elem] = value - - new_cls.__cog_commands__ = list(commands.values()) # this will be copied in Cog.__new__ - new_cls.__cog_app_commands__ = list(cog_app_commands.values()) - - listeners_as_list = [] - for listener in listeners.values(): - for listener_name in listener.__cog_listener_names__: - # I use __name__ instead of just storing the value so I can inject - # the self attribute when the time comes to add them to the bot - listeners_as_list.append((listener_name, listener.__name__)) - - new_cls.__cog_listeners__ = listeners_as_list - return new_cls - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args) - - @classmethod - def qualified_name(cls) -> str: - return cls.__cog_name__ - - -def _cog_special_method(func: FuncT) -> FuncT: - func.__cog_special_method__ = None - return func - - -class Cog(metaclass=CogMeta): - """The base class that all cogs must inherit from. - - A cog is a collection of commands, listeners, and optional state to - help group commands together. More information on them can be found on - the :ref:`ext_commands_cogs` page. - - When inheriting from this class, the options shown in :class:`CogMeta` - are equally valid here. - """ - - __cog_name__: str - __cog_description__: str - __cog_group_name__: Union[str, app_commands.locale_str] - __cog_group_description__: Union[str, app_commands.locale_str] - __cog_settings__: Dict[str, Any] - __cog_commands__: List[Command[Self, ..., Any]] - __cog_app_commands__: List[Union[app_commands.Group, app_commands.Command[Self, ..., Any]]] - __cog_listeners__: List[Tuple[str, str]] - __cog_is_app_commands_group__: ClassVar[bool] = False - __cog_app_commands_group__: Optional[app_commands.Group] - __discord_app_commands_error_handler__: Optional[ - Callable[[discord.Interaction, app_commands.AppCommandError], Coroutine[Any, Any, None]] - ] - - def __new__(cls, *args: Any, **kwargs: Any) -> Self: - # For issue 426, we need to store a copy of the command objects - # since we modify them to inject `self` to them. - # To do this, we need to interfere with the Cog creation process. - self = super().__new__(cls) - cmd_attrs = cls.__cog_settings__ - - # Either update the command with the cog provided defaults or copy it. - # r.e type ignore, type-checker complains about overriding a ClassVar - self.__cog_commands__ = tuple(c._update_copy(cmd_attrs) for c in cls.__cog_commands__) # type: ignore - - lookup = {cmd.qualified_name: cmd for cmd in self.__cog_commands__} - - # Register the application commands - children: List[Union[app_commands.Group, app_commands.Command[Self, ..., Any]]] = [] - - if cls.__cog_is_app_commands_group__: - group = app_commands.Group( - name=cls.__cog_group_name__, - description=cls.__cog_group_description__, - nsfw=cls.__cog_group_nsfw__, - auto_locale_strings=cls.__cog_group_auto_locale_strings__, - parent=None, - guild_ids=getattr(cls, '__discord_app_commands_default_guilds__', None), - guild_only=getattr(cls, '__discord_app_commands_guild_only__', False), - default_permissions=getattr(cls, '__discord_app_commands_default_permissions__', None), - ) - else: - group = None - - self.__cog_app_commands_group__ = group - - # Update the Command instances dynamically as well - for command in self.__cog_commands__: - setattr(self, command.callback.__name__, command) - parent = command.parent - if parent is not None: - # Get the latest parent reference - parent = lookup[parent.qualified_name] # type: ignore - - # Update our parent's reference to our self - parent.remove_command(command.name) # type: ignore - parent.add_command(command) # type: ignore - - if hasattr(command, '__commands_is_hybrid__') and parent is None: - app_command: Optional[Union[app_commands.Group, app_commands.Command[Self, ..., Any]]] = getattr( - command, 'app_command', None - ) - if app_command: - group_parent = self.__cog_app_commands_group__ - app_command = app_command._copy_with(parent=group_parent, binding=self) - # The type checker does not see the app_command attribute even though it exists - command.app_command = app_command # type: ignore - - if self.__cog_app_commands_group__: - children.append(app_command) - - if Cog._get_overridden_method(self.cog_app_command_error) is not None: - error_handler = self.cog_app_command_error - else: - error_handler = None - - self.__discord_app_commands_error_handler__ = error_handler - - for command in cls.__cog_app_commands__: - copy = command._copy_with(parent=self.__cog_app_commands_group__, binding=self) - - # Update set bindings - if copy._attr: - setattr(self, copy._attr, copy) - - if isinstance(copy, app_commands.Group): - copy.__discord_app_commands_error_handler__ = error_handler - for command in copy._children.values(): - if isinstance(command, app_commands.Group): - command.__discord_app_commands_error_handler__ = error_handler - - children.append(copy) - - self.__cog_app_commands__ = children - if self.__cog_app_commands_group__: - self.__cog_app_commands_group__.module = cls.__module__ - mapping = {cmd.name: cmd for cmd in children} - if len(mapping) > 25: - raise TypeError('maximum number of application command children exceeded') - - self.__cog_app_commands_group__._children = mapping # type: ignore # Variance issue - - return self - - def get_commands(self) -> List[Command[Self, ..., Any]]: - r"""Returns the commands that are defined inside this cog. - - This does *not* include :class:`discord.app_commands.Command` or :class:`discord.app_commands.Group` - instances. - - Returns - -------- - List[:class:`.Command`] - A :class:`list` of :class:`.Command`\s that are - defined inside this cog, not including subcommands. - """ - return [c for c in self.__cog_commands__ if c.parent is None] - - def get_app_commands(self) -> List[Union[app_commands.Command[Self, ..., Any], app_commands.Group]]: - r"""Returns the app commands that are defined inside this cog. - - Returns - -------- - List[Union[:class:`discord.app_commands.Command`, :class:`discord.app_commands.Group`]] - A :class:`list` of :class:`discord.app_commands.Command`\s and :class:`discord.app_commands.Group`\s that are - defined inside this cog, not including subcommands. - """ - return [c for c in self.__cog_app_commands__ if c.parent is None] - - @property - def qualified_name(self) -> str: - """:class:`str`: Returns the cog's specified name, not the class name.""" - return self.__cog_name__ - - @property - def description(self) -> str: - """:class:`str`: Returns the cog's description, typically the cleaned docstring.""" - return self.__cog_description__ - - @description.setter - def description(self, description: str) -> None: - self.__cog_description__ = description - - def walk_commands(self) -> Generator[Command[Self, ..., Any], None, None]: - """An iterator that recursively walks through this cog's commands and subcommands. - - Yields - ------ - Union[:class:`.Command`, :class:`.Group`] - A command or group from the cog. - """ - from .core import GroupMixin - - for command in self.__cog_commands__: - if command.parent is None: - yield command - if isinstance(command, GroupMixin): - yield from command.walk_commands() - - def walk_app_commands(self) -> Generator[Union[app_commands.Command[Self, ..., Any], app_commands.Group], None, None]: - """An iterator that recursively walks through this cog's app commands and subcommands. - - Yields - ------ - Union[:class:`discord.app_commands.Command`, :class:`discord.app_commands.Group`] - An app command or group from the cog. - """ - for command in self.__cog_app_commands__: - yield command - if isinstance(command, app_commands.Group): - yield from command.walk_commands() - - @property - def app_command(self) -> Optional[app_commands.Group]: - """Optional[:class:`discord.app_commands.Group`]: Returns the associated group with this cog. - - This is only available if inheriting from :class:`GroupCog`. - """ - return self.__cog_app_commands_group__ - - def get_listeners(self) -> List[Tuple[str, Callable[..., Any]]]: - """Returns a :class:`list` of (name, function) listener pairs that are defined in this cog. - - Returns - -------- - List[Tuple[:class:`str`, :ref:`coroutine `]] - The listeners defined in this cog. - """ - return [(name, getattr(self, method_name)) for name, method_name in self.__cog_listeners__] - - @classmethod - def _get_overridden_method(cls, method: FuncT) -> Optional[FuncT]: - """Return None if the method is not overridden. Otherwise returns the overridden method.""" - return getattr(method.__func__, '__cog_special_method__', method) - - @classmethod - def listener(cls, name: str = MISSING) -> Callable[[FuncT], FuncT]: - """A decorator that marks a function as a listener. - - This is the cog equivalent of :meth:`.Bot.listen`. - - Parameters - ------------ - name: :class:`str` - The name of the event being listened to. If not provided, it - defaults to the function's name. - - Raises - -------- - TypeError - The function is not a coroutine function or a string was not passed as - the name. - """ - - if name is not MISSING and not isinstance(name, str): - raise TypeError(f'Cog.listener expected str but received {name.__class__.__name__!r} instead.') - - def decorator(func: FuncT) -> FuncT: - actual = func - if isinstance(actual, staticmethod): - actual = actual.__func__ - if not inspect.iscoroutinefunction(actual): - raise TypeError('Listener function must be a coroutine function.') - actual.__cog_listener__ = True - to_assign = name or actual.__name__ - try: - actual.__cog_listener_names__.append(to_assign) - except AttributeError: - actual.__cog_listener_names__ = [to_assign] - # we have to return `func` instead of `actual` because - # we need the type to be `staticmethod` for the metaclass - # to pick it up but the metaclass unfurls the function and - # thus the assignments need to be on the actual function - return func - - return decorator - - def has_error_handler(self) -> bool: - """:class:`bool`: Checks whether the cog has an error handler. - - .. versionadded:: 1.7 - """ - return not hasattr(self.cog_command_error.__func__, '__cog_special_method__') - - @_cog_special_method - async def cog_load(self) -> None: - """|maybecoro| - - A special method that is called when the cog gets loaded. - - Subclasses must replace this if they want special asynchronous loading behaviour. - Note that the ``__init__`` special method does not allow asynchronous code to run - inside it, thus this is helpful for setting up code that needs to be asynchronous. - - .. versionadded:: 2.0 - """ - pass - - @_cog_special_method - async def cog_unload(self) -> None: - """|maybecoro| - - A special method that is called when the cog gets removed. - - Subclasses must replace this if they want special unloading behaviour. - - .. versionchanged:: 2.0 - - This method can now be a :term:`coroutine`. - """ - pass - - @_cog_special_method - def bot_check_once(self, ctx: Context[BotT]) -> bool: - """A special method that registers as a :meth:`.Bot.check_once` - check. - - This function **can** be a coroutine and must take a sole parameter, - ``ctx``, to represent the :class:`.Context`. - """ - return True - - @_cog_special_method - def bot_check(self, ctx: Context[BotT]) -> bool: - """A special method that registers as a :meth:`.Bot.check` - check. - - This function **can** be a coroutine and must take a sole parameter, - ``ctx``, to represent the :class:`.Context`. - """ - return True - - @_cog_special_method - def cog_check(self, ctx: Context[BotT]) -> bool: - """A special method that registers as a :func:`~discord.ext.commands.check` - for every command and subcommand in this cog. - - This function **can** be a coroutine and must take a sole parameter, - ``ctx``, to represent the :class:`.Context`. - """ - return True - - @_cog_special_method - async def cog_command_error(self, ctx: Context[BotT], error: Exception) -> None: - """A special method that is called whenever an error - is dispatched inside this cog. - - This is similar to :func:`.on_command_error` except only applying - to the commands inside this cog. - - This **must** be a coroutine. - - Parameters - ----------- - ctx: :class:`.Context` - The invocation context where the error happened. - error: :class:`CommandError` - The error that happened. - """ - pass - - @_cog_special_method - async def cog_app_command_error(self, interaction: discord.Interaction, error: app_commands.AppCommandError) -> None: - """A special method that is called whenever an error within - an application command is dispatched inside this cog. - - This is similar to :func:`discord.app_commands.CommandTree.on_error` except - only applying to the application commands inside this cog. - - This **must** be a coroutine. - - Parameters - ----------- - interaction: :class:`~discord.Interaction` - The interaction that is being handled. - error: :exc:`~discord.app_commands.AppCommandError` - The exception that was raised. - """ - pass - - @_cog_special_method - async def cog_before_invoke(self, ctx: Context[BotT]) -> None: - """A special method that acts as a cog local pre-invoke hook. - - This is similar to :meth:`.Command.before_invoke`. - - This **must** be a coroutine. - - Parameters - ----------- - ctx: :class:`.Context` - The invocation context. - """ - pass - - @_cog_special_method - async def cog_after_invoke(self, ctx: Context[BotT]) -> None: - """A special method that acts as a cog local post-invoke hook. - - This is similar to :meth:`.Command.after_invoke`. - - This **must** be a coroutine. - - Parameters - ----------- - ctx: :class:`.Context` - The invocation context. - """ - pass - - async def _inject(self, bot: BotBase, override: bool, guild: Optional[Snowflake], guilds: List[Snowflake]) -> Self: - cls = self.__class__ - - # we'll call this first so that errors can propagate without - # having to worry about undoing anything - await maybe_coroutine(self.cog_load) - - # realistically, the only thing that can cause loading errors - # is essentially just the command loading, which raises if there are - # duplicates. When this condition is met, we want to undo all what - # we've added so far for some form of atomic loading. - for index, command in enumerate(self.__cog_commands__): - command.cog = self - if command.parent is None: - try: - bot.add_command(command) - except Exception as e: - # undo our additions - for to_undo in self.__cog_commands__[:index]: - if to_undo.parent is None: - bot.remove_command(to_undo.name) - try: - await maybe_coroutine(self.cog_unload) - finally: - raise e - - # check if we're overriding the default - if cls.bot_check is not Cog.bot_check: - bot.add_check(self.bot_check) - - if cls.bot_check_once is not Cog.bot_check_once: - bot.add_check(self.bot_check_once, call_once=True) - - # while Bot.add_listener can raise if it's not a coroutine, - # this precondition is already met by the listener decorator - # already, thus this should never raise. - # Outside of, memory errors and the like... - for name, method_name in self.__cog_listeners__: - bot.add_listener(getattr(self, method_name), name) - - # Only do this if these are "top level" commands - if not self.__cog_app_commands_group__: - for command in self.__cog_app_commands__: - # This is already atomic - bot.tree.add_command(command, override=override, guild=guild, guilds=guilds) - - return self - - async def _eject(self, bot: BotBase, guild_ids: Optional[Iterable[int]]) -> None: - cls = self.__class__ - - try: - for command in self.__cog_commands__: - if command.parent is None: - bot.remove_command(command.name) - - if not self.__cog_app_commands_group__: - for command in self.__cog_app_commands__: - guild_ids = guild_ids or command._guild_ids - if guild_ids is None: - bot.tree.remove_command(command.name) - else: - for guild_id in guild_ids: - bot.tree.remove_command(command.name, guild=discord.Object(id=guild_id)) - - for name, method_name in self.__cog_listeners__: - bot.remove_listener(getattr(self, method_name), name) - - if cls.bot_check is not Cog.bot_check: - bot.remove_check(self.bot_check) - - if cls.bot_check_once is not Cog.bot_check_once: - bot.remove_check(self.bot_check_once, call_once=True) - finally: - try: - await maybe_coroutine(self.cog_unload) - except Exception: - pass - - -class GroupCog(Cog): - """Represents a cog that also doubles as a parent :class:`discord.app_commands.Group` for - the application commands defined within it. - - This inherits from :class:`Cog` and the options in :class:`CogMeta` also apply to this. - See the :class:`Cog` documentation for methods. - - Decorators such as :func:`~discord.app_commands.guild_only`, :func:`~discord.app_commands.guilds`, - and :func:`~discord.app_commands.default_permissions` will apply to the group if used on top of the - cog. - - For example: - - .. code-block:: python3 - - from discord import app_commands - from discord.ext import commands - - @app_commands.guild_only() - class MyCog(commands.GroupCog, group_name='my-cog'): - pass - - .. versionadded:: 2.0 - """ - - __cog_is_app_commands_group__: ClassVar[bool] = True diff --git a/.venv/Lib/site-packages/discord/ext/commands/context.py b/.venv/Lib/site-packages/discord/ext/commands/context.py deleted file mode 100644 index 616cab9..0000000 --- a/.venv/Lib/site-packages/discord/ext/commands/context.py +++ /dev/null @@ -1,880 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" -from __future__ import annotations - -import re -from typing import TYPE_CHECKING, Any, Dict, Generator, Generic, List, Optional, TypeVar, Union, Sequence, Type - -import discord.abc -import discord.utils -from discord import Interaction, Message, Attachment, MessageType, User, PartialMessageable, Permissions, ChannelType, Thread -from discord.context_managers import Typing -from .view import StringView - -from ._types import BotT - -if TYPE_CHECKING: - from typing_extensions import Self, ParamSpec, TypeGuard - - from discord.abc import MessageableChannel - from discord.guild import Guild - from discord.member import Member - from discord.state import ConnectionState - from discord.user import ClientUser - from discord.voice_client import VoiceProtocol - from discord.embeds import Embed - from discord.file import File - from discord.mentions import AllowedMentions - from discord.sticker import GuildSticker, StickerItem - from discord.message import MessageReference, PartialMessage - from discord.ui import View - from discord.types.interactions import ApplicationCommandInteractionData - - from .cog import Cog - from .core import Command - from .parameters import Parameter - - from types import TracebackType - - BE = TypeVar('BE', bound=BaseException) - -# fmt: off -__all__ = ( - 'Context', -) -# fmt: on - -MISSING: Any = discord.utils.MISSING - - -T = TypeVar('T') -CogT = TypeVar('CogT', bound="Cog") - -if TYPE_CHECKING: - P = ParamSpec('P') -else: - P = TypeVar('P') - - -def is_cog(obj: Any) -> TypeGuard[Cog]: - return hasattr(obj, '__cog_commands__') - - -class DeferTyping: - def __init__(self, ctx: Context[BotT], *, ephemeral: bool): - self.ctx: Context[BotT] = ctx - self.ephemeral: bool = ephemeral - - def __await__(self) -> Generator[Any, None, None]: - return self.ctx.defer(ephemeral=self.ephemeral).__await__() - - async def __aenter__(self) -> None: - await self.ctx.defer(ephemeral=self.ephemeral) - - async def __aexit__( - self, - exc_type: Optional[Type[BE]], - exc: Optional[BE], - traceback: Optional[TracebackType], - ) -> None: - pass - - -class Context(discord.abc.Messageable, Generic[BotT]): - r"""Represents the context in which a command is being invoked under. - - This class contains a lot of meta data to help you understand more about - the invocation context. This class is not created manually and is instead - passed around to commands as the first parameter. - - This class implements the :class:`~discord.abc.Messageable` ABC. - - Attributes - ----------- - message: :class:`.Message` - The message that triggered the command being executed. - - .. note:: - - In the case of an interaction based context, this message is "synthetic" - and does not actually exist. Therefore, the ID on it is invalid similar - to ephemeral messages. - bot: :class:`.Bot` - The bot that contains the command being executed. - args: :class:`list` - The list of transformed arguments that were passed into the command. - If this is accessed during the :func:`.on_command_error` event - then this list could be incomplete. - kwargs: :class:`dict` - A dictionary of transformed arguments that were passed into the command. - Similar to :attr:`args`\, if this is accessed in the - :func:`.on_command_error` event then this dict could be incomplete. - current_parameter: Optional[:class:`Parameter`] - The parameter that is currently being inspected and converted. - This is only of use for within converters. - - .. versionadded:: 2.0 - current_argument: Optional[:class:`str`] - The argument string of the :attr:`current_parameter` that is currently being converted. - This is only of use for within converters. - - .. versionadded:: 2.0 - interaction: Optional[:class:`~discord.Interaction`] - The interaction associated with this context. - - .. versionadded:: 2.0 - prefix: Optional[:class:`str`] - The prefix that was used to invoke the command. For interaction based contexts, - this is ``/`` for slash commands and ``\u200b`` for context menu commands. - command: Optional[:class:`Command`] - The command that is being invoked currently. - invoked_with: Optional[:class:`str`] - The command name that triggered this invocation. Useful for finding out - which alias called the command. - invoked_parents: List[:class:`str`] - The command names of the parents that triggered this invocation. Useful for - finding out which aliases called the command. - - For example in commands ``?a b c test``, the invoked parents are ``['a', 'b', 'c']``. - - .. versionadded:: 1.7 - - invoked_subcommand: Optional[:class:`Command`] - The subcommand that was invoked. - If no valid subcommand was invoked then this is equal to ``None``. - subcommand_passed: Optional[:class:`str`] - The string that was attempted to call a subcommand. This does not have - to point to a valid registered subcommand and could just point to a - nonsense string. If nothing was passed to attempt a call to a - subcommand then this is set to ``None``. - command_failed: :class:`bool` - A boolean that indicates if the command failed to be parsed, checked, - or invoked. - """ - - def __init__( - self, - *, - message: Message, - bot: BotT, - view: StringView, - args: List[Any] = MISSING, - kwargs: Dict[str, Any] = MISSING, - prefix: Optional[str] = None, - command: Optional[Command[Any, ..., Any]] = None, - invoked_with: Optional[str] = None, - invoked_parents: List[str] = MISSING, - invoked_subcommand: Optional[Command[Any, ..., Any]] = None, - subcommand_passed: Optional[str] = None, - command_failed: bool = False, - current_parameter: Optional[Parameter] = None, - current_argument: Optional[str] = None, - interaction: Optional[Interaction] = None, - ): - self.message: Message = message - self.bot: BotT = bot - self.args: List[Any] = args or [] - self.kwargs: Dict[str, Any] = kwargs or {} - self.prefix: Optional[str] = prefix - self.command: Optional[Command[Any, ..., Any]] = command - self.view: StringView = view - self.invoked_with: Optional[str] = invoked_with - self.invoked_parents: List[str] = invoked_parents or [] - self.invoked_subcommand: Optional[Command[Any, ..., Any]] = invoked_subcommand - self.subcommand_passed: Optional[str] = subcommand_passed - self.command_failed: bool = command_failed - self.current_parameter: Optional[Parameter] = current_parameter - self.current_argument: Optional[str] = current_argument - self.interaction: Optional[Interaction] = interaction - self._state: ConnectionState = self.message._state - - @classmethod - async def from_interaction(cls, interaction: Interaction, /) -> Self: - """|coro| - - Creates a context from a :class:`discord.Interaction`. This only - works on application command based interactions, such as slash commands - or context menus. - - On slash command based interactions this creates a synthetic :class:`~discord.Message` - that points to an ephemeral message that the command invoker has executed. This means - that :attr:`Context.author` returns the member that invoked the command. - - In a message context menu based interaction, the :attr:`Context.message` attribute - is the message that the command is being executed on. This means that :attr:`Context.author` - returns the author of the message being targetted. To get the member that invoked - the command then :attr:`discord.Interaction.user` should be used instead. - - .. versionadded:: 2.0 - - Parameters - ----------- - interaction: :class:`discord.Interaction` - The interaction to create a context with. - - Raises - ------- - ValueError - The interaction does not have a valid command. - TypeError - The interaction client is not derived from :class:`Bot` or :class:`AutoShardedBot`. - """ - - # Circular import - from .bot import BotBase - - if not isinstance(interaction.client, BotBase): - raise TypeError('Interaction client is not derived from commands.Bot or commands.AutoShardedBot') - - command = interaction.command - if command is None: - raise ValueError('interaction does not have command data') - - bot: BotT = interaction.client # type: ignore - data: ApplicationCommandInteractionData = interaction.data # type: ignore - if interaction.message is None: - synthetic_payload = { - 'id': interaction.id, - 'reactions': [], - 'embeds': [], - 'mention_everyone': False, - 'tts': False, - 'pinned': False, - 'edited_timestamp': None, - 'type': MessageType.chat_input_command if data.get('type', 1) == 1 else MessageType.context_menu_command, - 'flags': 64, - 'content': '', - 'mentions': [], - 'mention_roles': [], - 'attachments': [], - } - - if interaction.channel_id is None: - raise RuntimeError('interaction channel ID is null, this is probably a Discord bug') - - channel = interaction.channel or PartialMessageable( - state=interaction._state, guild_id=interaction.guild_id, id=interaction.channel_id - ) - message = Message(state=interaction._state, channel=channel, data=synthetic_payload) # type: ignore - message.author = interaction.user - message.attachments = [a for _, a in interaction.namespace if isinstance(a, Attachment)] - else: - message = interaction.message - - prefix = '/' if data.get('type', 1) == 1 else '\u200b' # Mock the prefix - ctx = cls( - message=message, - bot=bot, - view=StringView(''), - args=[], - kwargs={}, - prefix=prefix, - interaction=interaction, - invoked_with=command.name, - command=command, # type: ignore # this will be a hybrid command, technically - ) - interaction._baton = ctx - return ctx - - async def invoke(self, command: Command[CogT, P, T], /, *args: P.args, **kwargs: P.kwargs) -> T: - r"""|coro| - - Calls a command with the arguments given. - - This is useful if you want to just call the callback that a - :class:`.Command` holds internally. - - .. note:: - - This does not handle converters, checks, cooldowns, pre-invoke, - or after-invoke hooks in any matter. It calls the internal callback - directly as-if it was a regular function. - - You must take care in passing the proper arguments when - using this function. - - .. versionchanged:: 2.0 - - ``command`` parameter is now positional-only. - - Parameters - ----------- - command: :class:`.Command` - The command that is going to be called. - \*args - The arguments to use. - \*\*kwargs - The keyword arguments to use. - - Raises - ------- - TypeError - The command argument to invoke is missing. - """ - return await command(self, *args, **kwargs) - - async def reinvoke(self, *, call_hooks: bool = False, restart: bool = True) -> None: - """|coro| - - Calls the command again. - - This is similar to :meth:`~.Context.invoke` except that it bypasses - checks, cooldowns, and error handlers. - - .. note:: - - If you want to bypass :exc:`.UserInputError` derived exceptions, - it is recommended to use the regular :meth:`~.Context.invoke` - as it will work more naturally. After all, this will end up - using the old arguments the user has used and will thus just - fail again. - - Parameters - ------------ - call_hooks: :class:`bool` - Whether to call the before and after invoke hooks. - restart: :class:`bool` - Whether to start the call chain from the very beginning - or where we left off (i.e. the command that caused the error). - The default is to start where we left off. - - Raises - ------- - ValueError - The context to reinvoke is not valid. - """ - cmd = self.command - view = self.view - if cmd is None: - raise ValueError('This context is not valid.') - - # some state to revert to when we're done - index, previous = view.index, view.previous - invoked_with = self.invoked_with - invoked_subcommand = self.invoked_subcommand - invoked_parents = self.invoked_parents - subcommand_passed = self.subcommand_passed - - if restart: - to_call = cmd.root_parent or cmd - view.index = len(self.prefix or '') - view.previous = 0 - self.invoked_parents = [] - self.invoked_with = view.get_word() # advance to get the root command - else: - to_call = cmd - - try: - await to_call.reinvoke(self, call_hooks=call_hooks) - finally: - self.command = cmd - view.index = index - view.previous = previous - self.invoked_with = invoked_with - self.invoked_subcommand = invoked_subcommand - self.invoked_parents = invoked_parents - self.subcommand_passed = subcommand_passed - - @property - def valid(self) -> bool: - """:class:`bool`: Checks if the invocation context is valid to be invoked with.""" - return self.prefix is not None and self.command is not None - - async def _get_channel(self) -> discord.abc.Messageable: - return self.channel - - @property - def clean_prefix(self) -> str: - """:class:`str`: The cleaned up invoke prefix. i.e. mentions are ``@name`` instead of ``<@id>``. - - .. versionadded:: 2.0 - """ - if self.prefix is None: - return '' - - user = self.me - # this breaks if the prefix mention is not the bot itself but I - # consider this to be an *incredibly* strange use case. I'd rather go - # for this common use case rather than waste performance for the - # odd one. - pattern = re.compile(r"<@!?%s>" % user.id) - return pattern.sub("@%s" % user.display_name.replace('\\', r'\\'), self.prefix) - - @property - def cog(self) -> Optional[Cog]: - """Optional[:class:`.Cog`]: Returns the cog associated with this context's command. None if it does not exist.""" - - if self.command is None: - return None - return self.command.cog - - @discord.utils.cached_property - def guild(self) -> Optional[Guild]: - """Optional[:class:`.Guild`]: Returns the guild associated with this context's command. None if not available.""" - return self.message.guild - - @discord.utils.cached_property - def channel(self) -> MessageableChannel: - """Union[:class:`.abc.Messageable`]: Returns the channel associated with this context's command. - Shorthand for :attr:`.Message.channel`. - """ - return self.message.channel - - @discord.utils.cached_property - def author(self) -> Union[User, Member]: - """Union[:class:`~discord.User`, :class:`.Member`]: - Returns the author associated with this context's command. Shorthand for :attr:`.Message.author` - """ - return self.message.author - - @discord.utils.cached_property - def me(self) -> Union[Member, ClientUser]: - """Union[:class:`.Member`, :class:`.ClientUser`]: - Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message contexts. - """ - # bot.user will never be None at this point. - return self.guild.me if self.guild is not None else self.bot.user # type: ignore - - @discord.utils.cached_property - def permissions(self) -> Permissions: - """:class:`.Permissions`: Returns the resolved permissions for the invoking user in this channel. - Shorthand for :meth:`.abc.GuildChannel.permissions_for` or :attr:`.Interaction.permissions`. - - .. versionadded:: 2.0 - """ - if self.channel.type is ChannelType.private: - return Permissions._dm_permissions() - if not self.interaction: - # channel and author will always match relevant types here - return self.channel.permissions_for(self.author) # type: ignore - base = self.interaction.permissions - if self.channel.type in (ChannelType.voice, ChannelType.stage_voice): - if not base.connect: - # voice channels cannot be edited by people who can't connect to them - # It also implicitly denies all other voice perms - denied = Permissions.voice() - denied.update(manage_channels=True, manage_roles=True) - base.value &= ~denied.value - else: - # text channels do not have voice related permissions - denied = Permissions.voice() - base.value &= ~denied.value - return base - - @discord.utils.cached_property - def bot_permissions(self) -> Permissions: - """:class:`.Permissions`: Returns the resolved permissions for the bot in this channel. - Shorthand for :meth:`.abc.GuildChannel.permissions_for` or :attr:`.Interaction.app_permissions`. - - For interaction-based commands, this will reflect the effective permissions - for :class:`Context` calls, which may differ from calls through - other :class:`.abc.Messageable` endpoints, like :attr:`channel`. - - Notably, sending messages, embedding links, and attaching files are always - permitted, while reading messages might not be. - - .. versionadded:: 2.0 - """ - channel = self.channel - if channel.type == ChannelType.private: - return Permissions._dm_permissions() - if not self.interaction: - # channel and me will always match relevant types here - return channel.permissions_for(self.me) # type: ignore - guild = channel.guild - base = self.interaction.app_permissions - if self.channel.type in (ChannelType.voice, ChannelType.stage_voice): - if not base.connect: - # voice channels cannot be edited by people who can't connect to them - # It also implicitly denies all other voice perms - denied = Permissions.voice() - denied.update(manage_channels=True, manage_roles=True) - base.value &= ~denied.value - else: - # text channels do not have voice related permissions - denied = Permissions.voice() - base.value &= ~denied.value - base.update( - embed_links=True, - attach_files=True, - send_tts_messages=False, - ) - if isinstance(channel, Thread): - base.send_messages_in_threads = True - else: - base.send_messages = True - return base - - @property - def voice_client(self) -> Optional[VoiceProtocol]: - r"""Optional[:class:`.VoiceProtocol`]: A shortcut to :attr:`.Guild.voice_client`\, if applicable.""" - g = self.guild - return g.voice_client if g else None - - async def send_help(self, *args: Any) -> Any: - """send_help(entity=) - - |coro| - - Shows the help command for the specified entity if given. - The entity can be a command or a cog. - - If no entity is given, then it'll show help for the - entire bot. - - If the entity is a string, then it looks up whether it's a - :class:`Cog` or a :class:`Command`. - - .. note:: - - Due to the way this function works, instead of returning - something similar to :meth:`~.commands.HelpCommand.command_not_found` - this returns ``None`` on bad input or no help command. - - Parameters - ------------ - entity: Optional[Union[:class:`Command`, :class:`Cog`, :class:`str`]] - The entity to show help for. - - Returns - -------- - Any - The result of the help command, if any. - """ - from .core import Command, Group, wrap_callback - from .errors import CommandError - - bot = self.bot - cmd = bot.help_command - - if cmd is None: - return None - - cmd = cmd.copy() - cmd.context = self - - if len(args) == 0: - await cmd.prepare_help_command(self, None) - mapping = cmd.get_bot_mapping() - injected = wrap_callback(cmd.send_bot_help) - try: - return await injected(mapping) - except CommandError as e: - await cmd.on_help_command_error(self, e) - return None - - entity = args[0] - if isinstance(entity, str): - entity = bot.get_cog(entity) or bot.get_command(entity) - - if entity is None: - return None - - try: - entity.qualified_name - except AttributeError: - # if we're here then it's not a cog, group, or command. - return None - - await cmd.prepare_help_command(self, entity.qualified_name) - - try: - if is_cog(entity): - injected = wrap_callback(cmd.send_cog_help) - return await injected(entity) - elif isinstance(entity, Group): - injected = wrap_callback(cmd.send_group_help) - return await injected(entity) - elif isinstance(entity, Command): - injected = wrap_callback(cmd.send_command_help) - return await injected(entity) - else: - return None - except CommandError as e: - await cmd.on_help_command_error(self, e) - - async def reply(self, content: Optional[str] = None, **kwargs: Any) -> Message: - """|coro| - - A shortcut method to :meth:`send` to reply to the - :class:`~discord.Message` referenced by this context. - - For interaction based contexts, this is the same as :meth:`send`. - - .. versionadded:: 1.6 - - .. versionchanged:: 2.0 - This function will now raise :exc:`TypeError` or - :exc:`ValueError` instead of ``InvalidArgument``. - - Raises - -------- - ~discord.HTTPException - Sending the message failed. - ~discord.Forbidden - You do not have the proper permissions to send the message. - ValueError - The ``files`` list is not of the appropriate size - TypeError - You specified both ``file`` and ``files``. - - Returns - --------- - :class:`~discord.Message` - The message that was sent. - """ - if self.interaction is None: - return await self.send(content, reference=self.message, **kwargs) - else: - return await self.send(content, **kwargs) - - def typing(self, *, ephemeral: bool = False) -> Union[Typing, DeferTyping]: - """Returns an asynchronous context manager that allows you to send a typing indicator to - the destination for an indefinite period of time, or 10 seconds if the context manager - is called using ``await``. - - In an interaction based context, this is equivalent to a :meth:`defer` call and - does not do any typing calls. - - Example Usage: :: - - async with channel.typing(): - # simulate something heavy - await asyncio.sleep(20) - - await channel.send('Done!') - - Example Usage: :: - - await channel.typing() - # Do some computational magic for about 10 seconds - await channel.send('Done!') - - .. versionchanged:: 2.0 - This no longer works with the ``with`` syntax, ``async with`` must be used instead. - - .. versionchanged:: 2.0 - Added functionality to ``await`` the context manager to send a typing indicator for 10 seconds. - - Parameters - ----------- - ephemeral: :class:`bool` - Indicates whether the deferred message will eventually be ephemeral. - Only valid for interaction based contexts. - - .. versionadded:: 2.0 - """ - if self.interaction is None: - return Typing(self) - return DeferTyping(self, ephemeral=ephemeral) - - async def defer(self, *, ephemeral: bool = False) -> None: - """|coro| - - Defers the interaction based contexts. - - This is typically used when the interaction is acknowledged - and a secondary action will be done later. - - If this isn't an interaction based context then it does nothing. - - Parameters - ----------- - ephemeral: :class:`bool` - Indicates whether the deferred message will eventually be ephemeral. - - Raises - ------- - HTTPException - Deferring the interaction failed. - InteractionResponded - This interaction has already been responded to before. - """ - - if self.interaction: - await self.interaction.response.defer(ephemeral=ephemeral) - - async def send( - self, - content: Optional[str] = None, - *, - tts: bool = False, - embed: Optional[Embed] = None, - embeds: Optional[Sequence[Embed]] = None, - file: Optional[File] = None, - files: Optional[Sequence[File]] = None, - stickers: Optional[Sequence[Union[GuildSticker, StickerItem]]] = None, - delete_after: Optional[float] = None, - nonce: Optional[Union[str, int]] = None, - allowed_mentions: Optional[AllowedMentions] = None, - reference: Optional[Union[Message, MessageReference, PartialMessage]] = None, - mention_author: Optional[bool] = None, - view: Optional[View] = None, - suppress_embeds: bool = False, - ephemeral: bool = False, - ) -> Message: - """|coro| - - Sends a message to the destination with the content given. - - This works similarly to :meth:`~discord.abc.Messageable.send` for non-interaction contexts. - - For interaction based contexts this does one of the following: - - - :meth:`discord.InteractionResponse.send_message` if no response has been given. - - A followup message if a response has been given. - - Regular send if the interaction has expired - - .. versionchanged:: 2.0 - This function will now raise :exc:`TypeError` or - :exc:`ValueError` instead of ``InvalidArgument``. - - Parameters - ------------ - content: Optional[:class:`str`] - The content of the message to send. - tts: :class:`bool` - Indicates if the message should be sent using text-to-speech. - embed: :class:`~discord.Embed` - The rich embed for the content. - file: :class:`~discord.File` - The file to upload. - files: List[:class:`~discord.File`] - A list of files to upload. Must be a maximum of 10. - nonce: :class:`int` - The nonce to use for sending this message. If the message was successfully sent, - then the message will have a nonce with this value. - delete_after: :class:`float` - If provided, the number of seconds to wait in the background - before deleting the message we just sent. If the deletion fails, - then it is silently ignored. This is ignored for interaction based contexts. - allowed_mentions: :class:`~discord.AllowedMentions` - Controls the mentions being processed in this message. If this is - passed, then the object is merged with :attr:`~discord.Client.allowed_mentions`. - The merging behaviour only overrides attributes that have been explicitly passed - to the object, otherwise it uses the attributes set in :attr:`~discord.Client.allowed_mentions`. - If no object is passed at all then the defaults given by :attr:`~discord.Client.allowed_mentions` - are used instead. - - .. versionadded:: 1.4 - - reference: Union[:class:`~discord.Message`, :class:`~discord.MessageReference`, :class:`~discord.PartialMessage`] - A reference to the :class:`~discord.Message` to which you are replying, this can be created using - :meth:`~discord.Message.to_reference` or passed directly as a :class:`~discord.Message`. You can control - whether this mentions the author of the referenced message using the :attr:`~discord.AllowedMentions.replied_user` - attribute of ``allowed_mentions`` or by setting ``mention_author``. - - This is ignored for interaction based contexts. - - .. versionadded:: 1.6 - - mention_author: Optional[:class:`bool`] - If set, overrides the :attr:`~discord.AllowedMentions.replied_user` attribute of ``allowed_mentions``. - This is ignored for interaction based contexts. - - .. versionadded:: 1.6 - view: :class:`discord.ui.View` - A Discord UI View to add to the message. - - .. versionadded:: 2.0 - embeds: List[:class:`~discord.Embed`] - A list of embeds to upload. Must be a maximum of 10. - - .. versionadded:: 2.0 - stickers: Sequence[Union[:class:`~discord.GuildSticker`, :class:`~discord.StickerItem`]] - A list of stickers to upload. Must be a maximum of 3. This is ignored for interaction based contexts. - - .. versionadded:: 2.0 - suppress_embeds: :class:`bool` - Whether to suppress embeds for the message. This sends the message without any embeds if set to ``True``. - - .. versionadded:: 2.0 - ephemeral: :class:`bool` - Indicates if the message should only be visible to the user who started the interaction. - If a view is sent with an ephemeral message and it has no timeout set then the timeout - is set to 15 minutes. **This is only applicable in contexts with an interaction**. - - .. versionadded:: 2.0 - - Raises - -------- - ~discord.HTTPException - Sending the message failed. - ~discord.Forbidden - You do not have the proper permissions to send the message. - ValueError - The ``files`` list is not of the appropriate size. - TypeError - You specified both ``file`` and ``files``, - or you specified both ``embed`` and ``embeds``, - or the ``reference`` object is not a :class:`~discord.Message`, - :class:`~discord.MessageReference` or :class:`~discord.PartialMessage`. - - Returns - --------- - :class:`~discord.Message` - The message that was sent. - """ - - if self.interaction is None or self.interaction.is_expired(): - return await super().send( - content=content, - tts=tts, - embed=embed, - embeds=embeds, - file=file, - files=files, - stickers=stickers, - delete_after=delete_after, - nonce=nonce, - allowed_mentions=allowed_mentions, - reference=reference, - mention_author=mention_author, - view=view, - suppress_embeds=suppress_embeds, - ) # type: ignore # The overloads don't support Optional but the implementation does - - # Convert the kwargs from None to MISSING to appease the remaining implementations - kwargs = { - 'content': content, - 'tts': tts, - 'embed': MISSING if embed is None else embed, - 'embeds': MISSING if embeds is None else embeds, - 'file': MISSING if file is None else file, - 'files': MISSING if files is None else files, - 'allowed_mentions': MISSING if allowed_mentions is None else allowed_mentions, - 'view': MISSING if view is None else view, - 'suppress_embeds': suppress_embeds, - 'ephemeral': ephemeral, - } - - if self.interaction.response.is_done(): - msg = await self.interaction.followup.send(**kwargs, wait=True) - else: - await self.interaction.response.send_message(**kwargs) - msg = await self.interaction.original_response() - - if delete_after is not None and not (ephemeral and self.interaction is not None): - await msg.delete(delay=delete_after) - return msg diff --git a/.venv/Lib/site-packages/discord/ext/commands/converter.py b/.venv/Lib/site-packages/discord/ext/commands/converter.py deleted file mode 100644 index 2658237..0000000 --- a/.venv/Lib/site-packages/discord/ext/commands/converter.py +++ /dev/null @@ -1,1323 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations - -import inspect -import re -from typing import ( - TYPE_CHECKING, - Any, - Dict, - Generic, - Iterable, - List, - Literal, - Optional, - overload, - Protocol, - Tuple, - Type, - TypeVar, - Union, - runtime_checkable, -) -import types - -import discord - -from .errors import * - -if TYPE_CHECKING: - from discord.state import Channel - from discord.threads import Thread - - from .parameters import Parameter - from ._types import BotT, _Bot - from .context import Context - -__all__ = ( - 'Converter', - 'ObjectConverter', - 'MemberConverter', - 'UserConverter', - 'MessageConverter', - 'PartialMessageConverter', - 'TextChannelConverter', - 'InviteConverter', - 'GuildConverter', - 'RoleConverter', - 'GameConverter', - 'ColourConverter', - 'ColorConverter', - 'VoiceChannelConverter', - 'StageChannelConverter', - 'EmojiConverter', - 'PartialEmojiConverter', - 'CategoryChannelConverter', - 'ForumChannelConverter', - 'IDConverter', - 'ThreadConverter', - 'GuildChannelConverter', - 'GuildStickerConverter', - 'ScheduledEventConverter', - 'clean_content', - 'Greedy', - 'Range', - 'run_converters', -) - - -def _get_from_guilds(bot: _Bot, getter: str, argument: Any) -> Any: - result = None - for guild in bot.guilds: - result = getattr(guild, getter)(argument) - if result: - return result - return result - - -_utils_get = discord.utils.get -T = TypeVar('T') -T_co = TypeVar('T_co', covariant=True) -CT = TypeVar('CT', bound=discord.abc.GuildChannel) -TT = TypeVar('TT', bound=discord.Thread) - - -@runtime_checkable -class Converter(Protocol[T_co]): - """The base class of custom converters that require the :class:`.Context` - to be passed to be useful. - - This allows you to implement converters that function similar to the - special cased ``discord`` classes. - - Classes that derive from this should override the :meth:`~.Converter.convert` - method to do its conversion logic. This method must be a :ref:`coroutine `. - """ - - async def convert(self, ctx: Context[BotT], argument: str) -> T_co: - """|coro| - - The method to override to do conversion logic. - - If an error is found while converting, it is recommended to - raise a :exc:`.CommandError` derived exception as it will - properly propagate to the error handlers. - - Parameters - ----------- - ctx: :class:`.Context` - The invocation context that the argument is being used in. - argument: :class:`str` - The argument that is being converted. - - Raises - ------- - CommandError - A generic exception occurred when converting the argument. - BadArgument - The converter failed to convert the argument. - """ - raise NotImplementedError('Derived classes need to implement this.') - - -_ID_REGEX = re.compile(r'([0-9]{15,20})$') - - -class IDConverter(Converter[T_co]): - @staticmethod - def _get_id_match(argument): - return _ID_REGEX.match(argument) - - -class ObjectConverter(IDConverter[discord.Object]): - """Converts to a :class:`~discord.Object`. - - The argument must follow the valid ID or mention formats (e.g. `<@80088516616269824>`). - - .. versionadded:: 2.0 - - The lookup strategy is as follows (in order): - - 1. Lookup by ID. - 2. Lookup by member, role, or channel mention. - """ - - async def convert(self, ctx: Context[BotT], argument: str) -> discord.Object: - match = self._get_id_match(argument) or re.match(r'<(?:@(?:!|&)?|#)([0-9]{15,20})>$', argument) - - if match is None: - raise ObjectNotFound(argument) - - result = int(match.group(1)) - - return discord.Object(id=result) - - -class MemberConverter(IDConverter[discord.Member]): - """Converts to a :class:`~discord.Member`. - - All lookups are via the local guild. If in a DM context, then the lookup - is done by the global cache. - - The lookup strategy is as follows (in order): - - 1. Lookup by ID. - 2. Lookup by mention. - 3. Lookup by name#discrim - 4. Lookup by name - 5. Lookup by nickname - - .. versionchanged:: 1.5 - Raise :exc:`.MemberNotFound` instead of generic :exc:`.BadArgument` - - .. versionchanged:: 1.5.1 - This converter now lazily fetches members from the gateway and HTTP APIs, - optionally caching the result if :attr:`.MemberCacheFlags.joined` is enabled. - """ - - async def query_member_named(self, guild: discord.Guild, argument: str) -> Optional[discord.Member]: - cache = guild._state.member_cache_flags.joined - if len(argument) > 5 and argument[-5] == '#': - username, _, discriminator = argument.rpartition('#') - members = await guild.query_members(username, limit=100, cache=cache) - return discord.utils.get(members, name=username, discriminator=discriminator) - else: - members = await guild.query_members(argument, limit=100, cache=cache) - return discord.utils.find(lambda m: m.name == argument or m.nick == argument, members) - - async def query_member_by_id(self, bot: _Bot, guild: discord.Guild, user_id: int) -> Optional[discord.Member]: - ws = bot._get_websocket(shard_id=guild.shard_id) - cache = guild._state.member_cache_flags.joined - if ws.is_ratelimited(): - # If we're being rate limited on the WS, then fall back to using the HTTP API - # So we don't have to wait ~60 seconds for the query to finish - try: - member = await guild.fetch_member(user_id) - except discord.HTTPException: - return None - - if cache: - guild._add_member(member) - return member - - # If we're not being rate limited then we can use the websocket to actually query - members = await guild.query_members(limit=1, user_ids=[user_id], cache=cache) - if not members: - return None - return members[0] - - async def convert(self, ctx: Context[BotT], argument: str) -> discord.Member: - bot = ctx.bot - match = self._get_id_match(argument) or re.match(r'<@!?([0-9]{15,20})>$', argument) - guild = ctx.guild - result = None - user_id = None - - if match is None: - # not a mention... - if guild: - result = guild.get_member_named(argument) - else: - result = _get_from_guilds(bot, 'get_member_named', argument) - else: - user_id = int(match.group(1)) - if guild: - result = guild.get_member(user_id) or _utils_get(ctx.message.mentions, id=user_id) - else: - result = _get_from_guilds(bot, 'get_member', user_id) - - if not isinstance(result, discord.Member): - if guild is None: - raise MemberNotFound(argument) - - if user_id is not None: - result = await self.query_member_by_id(bot, guild, user_id) - else: - result = await self.query_member_named(guild, argument) - - if not result: - raise MemberNotFound(argument) - - return result - - -class UserConverter(IDConverter[discord.User]): - """Converts to a :class:`~discord.User`. - - All lookups are via the global user cache. - - The lookup strategy is as follows (in order): - - 1. Lookup by ID. - 2. Lookup by mention. - 3. Lookup by name#discrim - 4. Lookup by name - - .. versionchanged:: 1.5 - Raise :exc:`.UserNotFound` instead of generic :exc:`.BadArgument` - - .. versionchanged:: 1.6 - This converter now lazily fetches users from the HTTP APIs if an ID is passed - and it's not available in cache. - """ - - async def convert(self, ctx: Context[BotT], argument: str) -> discord.User: - match = self._get_id_match(argument) or re.match(r'<@!?([0-9]{15,20})>$', argument) - result = None - state = ctx._state - - if match is not None: - user_id = int(match.group(1)) - result = ctx.bot.get_user(user_id) or _utils_get(ctx.message.mentions, id=user_id) - if result is None: - try: - result = await ctx.bot.fetch_user(user_id) - except discord.HTTPException: - raise UserNotFound(argument) from None - - return result # type: ignore - - arg = argument - - # Remove the '@' character if this is the first character from the argument - if arg[0] == '@': - # Remove first character - arg = arg[1:] - - # check for discriminator if it exists, - if len(arg) > 5 and arg[-5] == '#': - discrim = arg[-4:] - name = arg[:-5] - predicate = lambda u: u.name == name and u.discriminator == discrim - result = discord.utils.find(predicate, state._users.values()) - if result is not None: - return result - - predicate = lambda u: u.name == arg - result = discord.utils.find(predicate, state._users.values()) - - if result is None: - raise UserNotFound(argument) - - return result - - -class PartialMessageConverter(Converter[discord.PartialMessage]): - """Converts to a :class:`discord.PartialMessage`. - - .. versionadded:: 1.7 - - The creation strategy is as follows (in order): - - 1. By "{channel ID}-{message ID}" (retrieved by shift-clicking on "Copy ID") - 2. By message ID (The message is assumed to be in the context channel.) - 3. By message URL - """ - - @staticmethod - def _get_id_matches(ctx: Context[BotT], argument: str) -> Tuple[Optional[int], int, int]: - id_regex = re.compile(r'(?:(?P[0-9]{15,20})-)?(?P[0-9]{15,20})$') - link_regex = re.compile( - r'https?://(?:(ptb|canary|www)\.)?discord(?:app)?\.com/channels/' - r'(?P[0-9]{15,20}|@me)' - r'/(?P[0-9]{15,20})/(?P[0-9]{15,20})/?$' - ) - match = id_regex.match(argument) or link_regex.match(argument) - if not match: - raise MessageNotFound(argument) - data = match.groupdict() - channel_id = discord.utils._get_as_snowflake(data, 'channel_id') or ctx.channel.id - message_id = int(data['message_id']) - guild_id = data.get('guild_id') - if guild_id is None: - guild_id = ctx.guild and ctx.guild.id - elif guild_id == '@me': - guild_id = None - else: - guild_id = int(guild_id) - return guild_id, message_id, channel_id - - @staticmethod - def _resolve_channel( - ctx: Context[BotT], guild_id: Optional[int], channel_id: Optional[int] - ) -> Optional[Union[Channel, Thread]]: - if channel_id is None: - # we were passed just a message id so we can assume the channel is the current context channel - return ctx.channel - - if guild_id is not None: - guild = ctx.bot.get_guild(guild_id) - if guild is None: - return None - return guild._resolve_channel(channel_id) - - return ctx.bot.get_channel(channel_id) - - async def convert(self, ctx: Context[BotT], argument: str) -> discord.PartialMessage: - guild_id, message_id, channel_id = self._get_id_matches(ctx, argument) - channel = self._resolve_channel(ctx, guild_id, channel_id) - if not channel or not isinstance(channel, discord.abc.Messageable): - raise ChannelNotFound(channel_id) - return discord.PartialMessage(channel=channel, id=message_id) - - -class MessageConverter(IDConverter[discord.Message]): - """Converts to a :class:`discord.Message`. - - .. versionadded:: 1.1 - - The lookup strategy is as follows (in order): - - 1. Lookup by "{channel ID}-{message ID}" (retrieved by shift-clicking on "Copy ID") - 2. Lookup by message ID (the message **must** be in the context channel) - 3. Lookup by message URL - - .. versionchanged:: 1.5 - Raise :exc:`.ChannelNotFound`, :exc:`.MessageNotFound` or :exc:`.ChannelNotReadable` instead of generic :exc:`.BadArgument` - """ - - async def convert(self, ctx: Context[BotT], argument: str) -> discord.Message: - guild_id, message_id, channel_id = PartialMessageConverter._get_id_matches(ctx, argument) - message = ctx.bot._connection._get_message(message_id) - if message: - return message - channel = PartialMessageConverter._resolve_channel(ctx, guild_id, channel_id) - if not channel or not isinstance(channel, discord.abc.Messageable): - raise ChannelNotFound(channel_id) - try: - return await channel.fetch_message(message_id) - except discord.NotFound: - raise MessageNotFound(argument) - except discord.Forbidden: - raise ChannelNotReadable(channel) # type: ignore # type-checker thinks channel could be a DMChannel at this point - - -class GuildChannelConverter(IDConverter[discord.abc.GuildChannel]): - """Converts to a :class:`~discord.abc.GuildChannel`. - - All lookups are via the local guild. If in a DM context, then the lookup - is done by the global cache. - - The lookup strategy is as follows (in order): - - 1. Lookup by ID. - 2. Lookup by mention. - 3. Lookup by name. - - .. versionadded:: 2.0 - """ - - async def convert(self, ctx: Context[BotT], argument: str) -> discord.abc.GuildChannel: - return self._resolve_channel(ctx, argument, 'channels', discord.abc.GuildChannel) - - @staticmethod - def _resolve_channel(ctx: Context[BotT], argument: str, attribute: str, type: Type[CT]) -> CT: - bot = ctx.bot - - match = IDConverter._get_id_match(argument) or re.match(r'<#([0-9]{15,20})>$', argument) - result = None - guild = ctx.guild - - if match is None: - # not a mention - if guild: - iterable: Iterable[CT] = getattr(guild, attribute) - result: Optional[CT] = discord.utils.get(iterable, name=argument) - else: - - def check(c): - return isinstance(c, type) and c.name == argument - - result = discord.utils.find(check, bot.get_all_channels()) # type: ignore - else: - channel_id = int(match.group(1)) - if guild: - # guild.get_channel returns an explicit union instead of the base class - result = guild.get_channel(channel_id) # type: ignore - else: - result = _get_from_guilds(bot, 'get_channel', channel_id) - - if not isinstance(result, type): - raise ChannelNotFound(argument) - - return result - - @staticmethod - def _resolve_thread(ctx: Context[BotT], argument: str, attribute: str, type: Type[TT]) -> TT: - match = IDConverter._get_id_match(argument) or re.match(r'<#([0-9]{15,20})>$', argument) - result = None - guild = ctx.guild - - if match is None: - # not a mention - if guild: - iterable: Iterable[TT] = getattr(guild, attribute) - result: Optional[TT] = discord.utils.get(iterable, name=argument) - else: - thread_id = int(match.group(1)) - if guild: - result = guild.get_thread(thread_id) # type: ignore - - if not result or not isinstance(result, type): - raise ThreadNotFound(argument) - - return result - - -class TextChannelConverter(IDConverter[discord.TextChannel]): - """Converts to a :class:`~discord.TextChannel`. - - All lookups are via the local guild. If in a DM context, then the lookup - is done by the global cache. - - The lookup strategy is as follows (in order): - - 1. Lookup by ID. - 2. Lookup by mention. - 3. Lookup by name - - .. versionchanged:: 1.5 - Raise :exc:`.ChannelNotFound` instead of generic :exc:`.BadArgument` - """ - - async def convert(self, ctx: Context[BotT], argument: str) -> discord.TextChannel: - return GuildChannelConverter._resolve_channel(ctx, argument, 'text_channels', discord.TextChannel) - - -class VoiceChannelConverter(IDConverter[discord.VoiceChannel]): - """Converts to a :class:`~discord.VoiceChannel`. - - All lookups are via the local guild. If in a DM context, then the lookup - is done by the global cache. - - The lookup strategy is as follows (in order): - - 1. Lookup by ID. - 2. Lookup by mention. - 3. Lookup by name - - .. versionchanged:: 1.5 - Raise :exc:`.ChannelNotFound` instead of generic :exc:`.BadArgument` - """ - - async def convert(self, ctx: Context[BotT], argument: str) -> discord.VoiceChannel: - return GuildChannelConverter._resolve_channel(ctx, argument, 'voice_channels', discord.VoiceChannel) - - -class StageChannelConverter(IDConverter[discord.StageChannel]): - """Converts to a :class:`~discord.StageChannel`. - - .. versionadded:: 1.7 - - All lookups are via the local guild. If in a DM context, then the lookup - is done by the global cache. - - The lookup strategy is as follows (in order): - - 1. Lookup by ID. - 2. Lookup by mention. - 3. Lookup by name - """ - - async def convert(self, ctx: Context[BotT], argument: str) -> discord.StageChannel: - return GuildChannelConverter._resolve_channel(ctx, argument, 'stage_channels', discord.StageChannel) - - -class CategoryChannelConverter(IDConverter[discord.CategoryChannel]): - """Converts to a :class:`~discord.CategoryChannel`. - - All lookups are via the local guild. If in a DM context, then the lookup - is done by the global cache. - - The lookup strategy is as follows (in order): - - 1. Lookup by ID. - 2. Lookup by mention. - 3. Lookup by name - - .. versionchanged:: 1.5 - Raise :exc:`.ChannelNotFound` instead of generic :exc:`.BadArgument` - """ - - async def convert(self, ctx: Context[BotT], argument: str) -> discord.CategoryChannel: - return GuildChannelConverter._resolve_channel(ctx, argument, 'categories', discord.CategoryChannel) - - -class ThreadConverter(IDConverter[discord.Thread]): - """Coverts to a :class:`~discord.Thread`. - - All lookups are via the local guild. - - The lookup strategy is as follows (in order): - - 1. Lookup by ID. - 2. Lookup by mention. - 3. Lookup by name. - - .. versionadded: 2.0 - """ - - async def convert(self, ctx: Context[BotT], argument: str) -> discord.Thread: - return GuildChannelConverter._resolve_thread(ctx, argument, 'threads', discord.Thread) - - -class ForumChannelConverter(IDConverter[discord.ForumChannel]): - """Converts to a :class:`~discord.ForumChannel`. - - All lookups are via the local guild. If in a DM context, then the lookup - is done by the global cache. - - The lookup strategy is as follows (in order): - - 1. Lookup by ID. - 2. Lookup by mention. - 3. Lookup by name - - .. versionadded:: 2.0 - """ - - async def convert(self, ctx: Context[BotT], argument: str) -> discord.ForumChannel: - return GuildChannelConverter._resolve_channel(ctx, argument, 'forums', discord.ForumChannel) - - -class ColourConverter(Converter[discord.Colour]): - """Converts to a :class:`~discord.Colour`. - - .. versionchanged:: 1.5 - Add an alias named ColorConverter - - The following formats are accepted: - - - ``0x`` - - ``#`` - - ``0x#`` - - ``rgb(, , )`` - - Any of the ``classmethod`` in :class:`~discord.Colour` - - - The ``_`` in the name can be optionally replaced with spaces. - - Like CSS, ```` can be either 0-255 or 0-100% and ```` can be - either a 6 digit hex number or a 3 digit hex shortcut (e.g. #fff). - - .. versionchanged:: 1.5 - Raise :exc:`.BadColourArgument` instead of generic :exc:`.BadArgument` - - .. versionchanged:: 1.7 - Added support for ``rgb`` function and 3-digit hex shortcuts - """ - - async def convert(self, ctx: Context[BotT], argument: str) -> discord.Colour: - try: - return discord.Colour.from_str(argument) - except ValueError: - arg = argument.lower().replace(' ', '_') - method = getattr(discord.Colour, arg, None) - if arg.startswith('from_') or method is None or not inspect.ismethod(method): - raise BadColourArgument(arg) - return method() - - -ColorConverter = ColourConverter - - -class RoleConverter(IDConverter[discord.Role]): - """Converts to a :class:`~discord.Role`. - - All lookups are via the local guild. If in a DM context, the converter raises - :exc:`.NoPrivateMessage` exception. - - The lookup strategy is as follows (in order): - - 1. Lookup by ID. - 2. Lookup by mention. - 3. Lookup by name - - .. versionchanged:: 1.5 - Raise :exc:`.RoleNotFound` instead of generic :exc:`.BadArgument` - """ - - async def convert(self, ctx: Context[BotT], argument: str) -> discord.Role: - guild = ctx.guild - if not guild: - raise NoPrivateMessage() - - match = self._get_id_match(argument) or re.match(r'<@&([0-9]{15,20})>$', argument) - if match: - result = guild.get_role(int(match.group(1))) - else: - result = discord.utils.get(guild._roles.values(), name=argument) - - if result is None: - raise RoleNotFound(argument) - return result - - -class GameConverter(Converter[discord.Game]): - """Converts to :class:`~discord.Game`.""" - - async def convert(self, ctx: Context[BotT], argument: str) -> discord.Game: - return discord.Game(name=argument) - - -class InviteConverter(Converter[discord.Invite]): - """Converts to a :class:`~discord.Invite`. - - This is done via an HTTP request using :meth:`.Bot.fetch_invite`. - - .. versionchanged:: 1.5 - Raise :exc:`.BadInviteArgument` instead of generic :exc:`.BadArgument` - """ - - async def convert(self, ctx: Context[BotT], argument: str) -> discord.Invite: - try: - invite = await ctx.bot.fetch_invite(argument) - return invite - except Exception as exc: - raise BadInviteArgument(argument) from exc - - -class GuildConverter(IDConverter[discord.Guild]): - """Converts to a :class:`~discord.Guild`. - - The lookup strategy is as follows (in order): - - 1. Lookup by ID. - 2. Lookup by name. (There is no disambiguation for Guilds with multiple matching names). - - .. versionadded:: 1.7 - """ - - async def convert(self, ctx: Context[BotT], argument: str) -> discord.Guild: - match = self._get_id_match(argument) - result = None - - if match is not None: - guild_id = int(match.group(1)) - result = ctx.bot.get_guild(guild_id) - - if result is None: - result = discord.utils.get(ctx.bot.guilds, name=argument) - - if result is None: - raise GuildNotFound(argument) - return result - - -class EmojiConverter(IDConverter[discord.Emoji]): - """Converts to a :class:`~discord.Emoji`. - - All lookups are done for the local guild first, if available. If that lookup - fails, then it checks the client's global cache. - - The lookup strategy is as follows (in order): - - 1. Lookup by ID. - 2. Lookup by extracting ID from the emoji. - 3. Lookup by name - - .. versionchanged:: 1.5 - Raise :exc:`.EmojiNotFound` instead of generic :exc:`.BadArgument` - """ - - async def convert(self, ctx: Context[BotT], argument: str) -> discord.Emoji: - match = self._get_id_match(argument) or re.match(r'$', argument) - result = None - bot = ctx.bot - guild = ctx.guild - - if match is None: - # Try to get the emoji by name. Try local guild first. - if guild: - result = discord.utils.get(guild.emojis, name=argument) - - if result is None: - result = discord.utils.get(bot.emojis, name=argument) - else: - emoji_id = int(match.group(1)) - - # Try to look up emoji by id. - result = bot.get_emoji(emoji_id) - - if result is None: - raise EmojiNotFound(argument) - - return result - - -class PartialEmojiConverter(Converter[discord.PartialEmoji]): - """Converts to a :class:`~discord.PartialEmoji`. - - This is done by extracting the animated flag, name and ID from the emoji. - - .. versionchanged:: 1.5 - Raise :exc:`.PartialEmojiConversionFailure` instead of generic :exc:`.BadArgument` - """ - - async def convert(self, ctx: Context[BotT], argument: str) -> discord.PartialEmoji: - match = re.match(r'<(a?):([a-zA-Z0-9\_]{1,32}):([0-9]{15,20})>$', argument) - - if match: - emoji_animated = bool(match.group(1)) - emoji_name = match.group(2) - emoji_id = int(match.group(3)) - - return discord.PartialEmoji.with_state( - ctx.bot._connection, animated=emoji_animated, name=emoji_name, id=emoji_id - ) - - raise PartialEmojiConversionFailure(argument) - - -class GuildStickerConverter(IDConverter[discord.GuildSticker]): - """Converts to a :class:`~discord.GuildSticker`. - - All lookups are done for the local guild first, if available. If that lookup - fails, then it checks the client's global cache. - - The lookup strategy is as follows (in order): - - 1. Lookup by ID. - 2. Lookup by name. - - .. versionadded:: 2.0 - """ - - async def convert(self, ctx: Context[BotT], argument: str) -> discord.GuildSticker: - match = self._get_id_match(argument) - result = None - bot = ctx.bot - guild = ctx.guild - - if match is None: - # Try to get the sticker by name. Try local guild first. - if guild: - result = discord.utils.get(guild.stickers, name=argument) - - if result is None: - result = discord.utils.get(bot.stickers, name=argument) - else: - sticker_id = int(match.group(1)) - - # Try to look up sticker by id. - result = bot.get_sticker(sticker_id) - - if result is None: - raise GuildStickerNotFound(argument) - - return result - - -class ScheduledEventConverter(IDConverter[discord.ScheduledEvent]): - """Converts to a :class:`~discord.ScheduledEvent`. - - Lookups are done for the local guild if available. Otherwise, for a DM context, - lookup is done by the global cache. - - The lookup strategy is as follows (in order): - - 1. Lookup by ID. - 2. Lookup by url. - 3. Lookup by name. - - .. versionadded:: 2.0 - """ - - async def convert(self, ctx: Context[BotT], argument: str) -> discord.ScheduledEvent: - guild = ctx.guild - match = self._get_id_match(argument) - result = None - - if match: - # ID match - event_id = int(match.group(1)) - if guild: - result = guild.get_scheduled_event(event_id) - else: - for guild in ctx.bot.guilds: - result = guild.get_scheduled_event(event_id) - if result: - break - else: - pattern = ( - r'https?://(?:(ptb|canary|www)\.)?discord\.com/events/' - r'(?P[0-9]{15,20})/' - r'(?P[0-9]{15,20})$' - ) - match = re.match(pattern, argument, flags=re.I) - if match: - # URL match - guild = ctx.bot.get_guild(int(match.group('guild_id'))) - - if guild: - event_id = int(match.group('event_id')) - result = guild.get_scheduled_event(event_id) - else: - # lookup by name - if guild: - result = discord.utils.get(guild.scheduled_events, name=argument) - else: - for guild in ctx.bot.guilds: - result = discord.utils.get(guild.scheduled_events, name=argument) - if result: - break - if result is None: - raise ScheduledEventNotFound(argument) - - return result - - -class clean_content(Converter[str]): - """Converts the argument to mention scrubbed version of - said content. - - This behaves similarly to :attr:`~discord.Message.clean_content`. - - Attributes - ------------ - fix_channel_mentions: :class:`bool` - Whether to clean channel mentions. - use_nicknames: :class:`bool` - Whether to use nicknames when transforming mentions. - escape_markdown: :class:`bool` - Whether to also escape special markdown characters. - remove_markdown: :class:`bool` - Whether to also remove special markdown characters. This option is not supported with ``escape_markdown`` - - .. versionadded:: 1.7 - """ - - def __init__( - self, - *, - fix_channel_mentions: bool = False, - use_nicknames: bool = True, - escape_markdown: bool = False, - remove_markdown: bool = False, - ) -> None: - self.fix_channel_mentions = fix_channel_mentions - self.use_nicknames = use_nicknames - self.escape_markdown = escape_markdown - self.remove_markdown = remove_markdown - - async def convert(self, ctx: Context[BotT], argument: str) -> str: - msg = ctx.message - - if ctx.guild: - - def resolve_member(id: int) -> str: - m = _utils_get(msg.mentions, id=id) or ctx.guild.get_member(id) # type: ignore - return f'@{m.display_name if self.use_nicknames else m.name}' if m else '@deleted-user' - - def resolve_role(id: int) -> str: - r = _utils_get(msg.role_mentions, id=id) or ctx.guild.get_role(id) # type: ignore - return f'@{r.name}' if r else '@deleted-role' - - else: - - def resolve_member(id: int) -> str: - m = _utils_get(msg.mentions, id=id) or ctx.bot.get_user(id) - return f'@{m.display_name}' if m else '@deleted-user' - - def resolve_role(id: int) -> str: - return '@deleted-role' - - if self.fix_channel_mentions and ctx.guild: - - def resolve_channel(id: int) -> str: - c = ctx.guild._resolve_channel(id) # type: ignore - return f'#{c.name}' if c else '#deleted-channel' - - else: - - def resolve_channel(id: int) -> str: - return f'<#{id}>' - - transforms = { - '@': resolve_member, - '@!': resolve_member, - '#': resolve_channel, - '@&': resolve_role, - } - - def repl(match: re.Match) -> str: - type = match[1] - id = int(match[2]) - transformed = transforms[type](id) - return transformed - - result = re.sub(r'<(@[!&]?|#)([0-9]{15,20})>', repl, argument) - if self.escape_markdown: - result = discord.utils.escape_markdown(result) - elif self.remove_markdown: - result = discord.utils.remove_markdown(result) - - # Completely ensure no mentions escape: - return discord.utils.escape_mentions(result) - - -class Greedy(List[T]): - r"""A special converter that greedily consumes arguments until it can't. - As a consequence of this behaviour, most input errors are silently discarded, - since it is used as an indicator of when to stop parsing. - - When a parser error is met the greedy converter stops converting, undoes the - internal string parsing routine, and continues parsing regularly. - - For example, in the following code: - - .. code-block:: python3 - - @commands.command() - async def test(ctx, numbers: Greedy[int], reason: str): - await ctx.send("numbers: {}, reason: {}".format(numbers, reason)) - - An invocation of ``[p]test 1 2 3 4 5 6 hello`` would pass ``numbers`` with - ``[1, 2, 3, 4, 5, 6]`` and ``reason`` with ``hello``\. - - For more information, check :ref:`ext_commands_special_converters`. - - .. note:: - - For interaction based contexts the conversion error is propagated - rather than swallowed due to the difference in user experience with - application commands. - """ - - __slots__ = ('converter',) - - def __init__(self, *, converter: T) -> None: - self.converter: T = converter - - def __repr__(self) -> str: - converter = getattr(self.converter, '__name__', repr(self.converter)) - return f'Greedy[{converter}]' - - def __class_getitem__(cls, params: Union[Tuple[T], T]) -> Greedy[T]: - if not isinstance(params, tuple): - params = (params,) - if len(params) != 1: - raise TypeError('Greedy[...] only takes a single argument') - converter = params[0] - - args = getattr(converter, '__args__', ()) - if discord.utils.PY_310 and converter.__class__ is types.UnionType: # type: ignore - converter = Union[args] # type: ignore - - origin = getattr(converter, '__origin__', None) - - if not (callable(converter) or isinstance(converter, Converter) or origin is not None): - raise TypeError('Greedy[...] expects a type or a Converter instance.') - - if converter in (str, type(None)) or origin is Greedy: - raise TypeError(f'Greedy[{converter.__name__}] is invalid.') # type: ignore - - if origin is Union and type(None) in args: - raise TypeError(f'Greedy[{converter!r}] is invalid.') - - return cls(converter=converter) - - -if TYPE_CHECKING: - from typing_extensions import Annotated as Range -else: - - class Range: - """A special converter that can be applied to a parameter to require a numeric - or string type to fit within the range provided. - - During type checking time this is equivalent to :obj:`typing.Annotated` so type checkers understand - the intent of the code. - - Some example ranges: - - - ``Range[int, 10]`` means the minimum is 10 with no maximum. - - ``Range[int, None, 10]`` means the maximum is 10 with no minimum. - - ``Range[int, 1, 10]`` means the minimum is 1 and the maximum is 10. - - Inside a :class:`HybridCommand` this functions equivalently to :class:`discord.app_commands.Range`. - - If the value cannot be converted to the provided type or is outside the given range, - :class:`~.ext.commands.BadArgument` or :class:`~.ext.commands.RangeError` is raised to - the appropriate error handlers respectively. - - .. versionadded:: 2.0 - - Examples - ---------- - - .. code-block:: python3 - - @bot.command() - async def range(ctx: commands.Context, value: commands.Range[int, 10, 12]): - await ctx.send(f'Your value is {value}') - """ - - def __init__( - self, - *, - annotation: Any, - min: Optional[Union[int, float]] = None, - max: Optional[Union[int, float]] = None, - ) -> None: - self.annotation: Any = annotation - self.min: Optional[Union[int, float]] = min - self.max: Optional[Union[int, float]] = max - - if min and max and min > max: - raise TypeError('minimum cannot be larger than maximum') - - async def convert(self, ctx: Context[BotT], value: str) -> Union[int, float]: - try: - count = converted = self.annotation(value) - except ValueError: - raise BadArgument( - f'Converting to "{self.annotation.__name__}" failed for parameter "{ctx.current_parameter.name}".' - ) - - if self.annotation is str: - count = len(value) - - if (self.min is not None and count < self.min) or (self.max is not None and count > self.max): - raise RangeError(converted, minimum=self.min, maximum=self.max) - - return converted - - def __call__(self) -> None: - # Trick to allow it inside typing.Union - pass - - def __class_getitem__(cls, obj) -> Range: - if not isinstance(obj, tuple): - raise TypeError(f'expected tuple for arguments, received {obj.__class__!r} instead') - - if len(obj) == 2: - obj = (*obj, None) - elif len(obj) != 3: - raise TypeError('Range accepts either two or three arguments with the first being the type of range.') - - annotation, min, max = obj - - if min is None and max is None: - raise TypeError('Range must not be empty') - - if min is not None and max is not None: - # At this point max and min are both not none - if type(min) != type(max): - raise TypeError('Both min and max in Range must be the same type') - - if annotation not in (int, float, str): - raise TypeError(f'expected int, float, or str as range type, received {annotation!r} instead') - - if annotation in (str, int): - cast = int - else: - cast = float - - return cls( - annotation=annotation, - min=cast(min) if min is not None else None, - max=cast(max) if max is not None else None, - ) - - -def _convert_to_bool(argument: str) -> bool: - lowered = argument.lower() - if lowered in ('yes', 'y', 'true', 't', '1', 'enable', 'on'): - return True - elif lowered in ('no', 'n', 'false', 'f', '0', 'disable', 'off'): - return False - else: - raise BadBoolArgument(lowered) - - -_GenericAlias = type(List[T]) - - -def is_generic_type(tp: Any, *, _GenericAlias: type = _GenericAlias) -> bool: - return isinstance(tp, type) and issubclass(tp, Generic) or isinstance(tp, _GenericAlias) - - -CONVERTER_MAPPING: Dict[type, Any] = { - discord.Object: ObjectConverter, - discord.Member: MemberConverter, - discord.User: UserConverter, - discord.Message: MessageConverter, - discord.PartialMessage: PartialMessageConverter, - discord.TextChannel: TextChannelConverter, - discord.Invite: InviteConverter, - discord.Guild: GuildConverter, - discord.Role: RoleConverter, - discord.Game: GameConverter, - discord.Colour: ColourConverter, - discord.VoiceChannel: VoiceChannelConverter, - discord.StageChannel: StageChannelConverter, - discord.Emoji: EmojiConverter, - discord.PartialEmoji: PartialEmojiConverter, - discord.CategoryChannel: CategoryChannelConverter, - discord.Thread: ThreadConverter, - discord.abc.GuildChannel: GuildChannelConverter, - discord.GuildSticker: GuildStickerConverter, - discord.ScheduledEvent: ScheduledEventConverter, - discord.ForumChannel: ForumChannelConverter, -} - - -async def _actual_conversion(ctx: Context[BotT], converter: Any, argument: str, param: inspect.Parameter): - if converter is bool: - return _convert_to_bool(argument) - - try: - module = converter.__module__ - except AttributeError: - pass - else: - if module is not None and (module.startswith('discord.') and not module.endswith('converter')): - converter = CONVERTER_MAPPING.get(converter, converter) - - try: - if inspect.isclass(converter) and issubclass(converter, Converter): - if inspect.ismethod(converter.convert): - return await converter.convert(ctx, argument) - else: - return await converter().convert(ctx, argument) - elif isinstance(converter, Converter): - return await converter.convert(ctx, argument) # type: ignore - except CommandError: - raise - except Exception as exc: - raise ConversionError(converter, exc) from exc # type: ignore - - try: - return converter(argument) - except CommandError: - raise - except Exception as exc: - try: - name = converter.__name__ - except AttributeError: - name = converter.__class__.__name__ - - raise BadArgument(f'Converting to "{name}" failed for parameter "{param.name}".') from exc - - -@overload -async def run_converters( - ctx: Context[BotT], converter: Union[Type[Converter[T]], Converter[T]], argument: str, param: Parameter -) -> T: - ... - - -@overload -async def run_converters(ctx: Context[BotT], converter: Any, argument: str, param: Parameter) -> Any: - ... - - -async def run_converters(ctx: Context[BotT], converter: Any, argument: str, param: Parameter) -> Any: - """|coro| - - Runs converters for a given converter, argument, and parameter. - - This function does the same work that the library does under the hood. - - .. versionadded:: 2.0 - - Parameters - ------------ - ctx: :class:`Context` - The invocation context to run the converters under. - converter: Any - The converter to run, this corresponds to the annotation in the function. - argument: :class:`str` - The argument to convert to. - param: :class:`Parameter` - The parameter being converted. This is mainly for error reporting. - - Raises - ------- - CommandError - The converter failed to convert. - - Returns - -------- - Any - The resulting conversion. - """ - origin = getattr(converter, '__origin__', None) - - if origin is Union: - errors = [] - _NoneType = type(None) - union_args = converter.__args__ - for conv in union_args: - # if we got to this part in the code, then the previous conversions have failed - # so we should just undo the view, return the default, and allow parsing to continue - # with the other parameters - if conv is _NoneType and param.kind != param.VAR_POSITIONAL: - ctx.view.undo() - return None if param.required else await param.get_default(ctx) - - try: - value = await run_converters(ctx, conv, argument, param) - except CommandError as exc: - errors.append(exc) - else: - return value - - # if we're here, then we failed all the converters - raise BadUnionArgument(param, union_args, errors) - - if origin is Literal: - errors = [] - conversions = {} - literal_args = converter.__args__ - for literal in literal_args: - literal_type = type(literal) - try: - value = conversions[literal_type] - except KeyError: - try: - value = await _actual_conversion(ctx, literal_type, argument, param) - except CommandError as exc: - errors.append(exc) - conversions[literal_type] = object() - continue - else: - conversions[literal_type] = value - - if value == literal: - return value - - # if we're here, then we failed to match all the literals - raise BadLiteralArgument(param, literal_args, errors) - - # This must be the last if-clause in the chain of origin checking - # Nearly every type is a generic type within the typing library - # So care must be taken to make sure a more specialised origin handle - # isn't overwritten by the widest if clause - if origin is not None and is_generic_type(converter): - converter = origin - - return await _actual_conversion(ctx, converter, argument, param) diff --git a/.venv/Lib/site-packages/discord/ext/commands/cooldowns.py b/.venv/Lib/site-packages/discord/ext/commands/cooldowns.py deleted file mode 100644 index 2af7cb0..0000000 --- a/.venv/Lib/site-packages/discord/ext/commands/cooldowns.py +++ /dev/null @@ -1,285 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" - -from __future__ import annotations - - -from typing import Any, Callable, Deque, Dict, Optional, Union, Generic, TypeVar, TYPE_CHECKING -from discord.enums import Enum -import time -import asyncio -from collections import deque - -from ...abc import PrivateChannel -from .errors import MaxConcurrencyReached -from .context import Context -from discord.app_commands import Cooldown as Cooldown - -if TYPE_CHECKING: - from typing_extensions import Self - - from ...message import Message - -__all__ = ( - 'BucketType', - 'Cooldown', - 'CooldownMapping', - 'DynamicCooldownMapping', - 'MaxConcurrency', -) - -T_contra = TypeVar('T_contra', contravariant=True) - - -class BucketType(Enum): - default = 0 - user = 1 - guild = 2 - channel = 3 - member = 4 - category = 5 - role = 6 - - def get_key(self, msg: Union[Message, Context[Any]]) -> Any: - if self is BucketType.user: - return msg.author.id - elif self is BucketType.guild: - return (msg.guild or msg.author).id - elif self is BucketType.channel: - return msg.channel.id - elif self is BucketType.member: - return ((msg.guild and msg.guild.id), msg.author.id) - elif self is BucketType.category: - return (msg.channel.category or msg.channel).id # type: ignore - elif self is BucketType.role: - # we return the channel id of a private-channel as there are only roles in guilds - # and that yields the same result as for a guild with only the @everyone role - # NOTE: PrivateChannel doesn't actually have an id attribute but we assume we are - # receiving a DMChannel or GroupChannel which inherit from PrivateChannel and do - return (msg.channel if isinstance(msg.channel, PrivateChannel) else msg.author.top_role).id # type: ignore - - def __call__(self, msg: Union[Message, Context[Any]]) -> Any: - return self.get_key(msg) - - -class CooldownMapping(Generic[T_contra]): - def __init__( - self, - original: Optional[Cooldown], - type: Callable[[T_contra], Any], - ) -> None: - if not callable(type): - raise TypeError('Cooldown type must be a BucketType or callable') - - self._cache: Dict[Any, Cooldown] = {} - self._cooldown: Optional[Cooldown] = original - self._type: Callable[[T_contra], Any] = type - - def copy(self) -> CooldownMapping[T_contra]: - ret = CooldownMapping(self._cooldown, self._type) - ret._cache = self._cache.copy() - return ret - - @property - def valid(self) -> bool: - return self._cooldown is not None - - @property - def type(self) -> Callable[[T_contra], Any]: - return self._type - - @classmethod - def from_cooldown(cls, rate: float, per: float, type: Callable[[T_contra], Any]) -> Self: - return cls(Cooldown(rate, per), type) - - def _bucket_key(self, msg: T_contra) -> Any: - return self._type(msg) - - def _verify_cache_integrity(self, current: Optional[float] = None) -> None: - # we want to delete all cache objects that haven't been used - # in a cooldown window. e.g. if we have a command that has a - # cooldown of 60s and it has not been used in 60s then that key should be deleted - current = current or time.time() - dead_keys = [k for k, v in self._cache.items() if current > v._last + v.per] - for k in dead_keys: - del self._cache[k] - - def create_bucket(self, message: T_contra) -> Cooldown: - return self._cooldown.copy() # type: ignore - - def get_bucket(self, message: T_contra, current: Optional[float] = None) -> Optional[Cooldown]: - if self._type is BucketType.default: - return self._cooldown - - self._verify_cache_integrity(current) - key = self._bucket_key(message) - if key not in self._cache: - bucket = self.create_bucket(message) - if bucket is not None: - self._cache[key] = bucket - else: - bucket = self._cache[key] - - return bucket - - def update_rate_limit(self, message: T_contra, current: Optional[float] = None, tokens: int = 1) -> Optional[float]: - bucket = self.get_bucket(message, current) - if bucket is None: - return None - return bucket.update_rate_limit(current, tokens=tokens) - - -class DynamicCooldownMapping(CooldownMapping[T_contra]): - def __init__( - self, - factory: Callable[[T_contra], Optional[Cooldown]], - type: Callable[[T_contra], Any], - ) -> None: - super().__init__(None, type) - self._factory: Callable[[T_contra], Optional[Cooldown]] = factory - - def copy(self) -> DynamicCooldownMapping[T_contra]: - ret = DynamicCooldownMapping(self._factory, self._type) - ret._cache = self._cache.copy() - return ret - - @property - def valid(self) -> bool: - return True - - def create_bucket(self, message: T_contra) -> Optional[Cooldown]: - return self._factory(message) - - -class _Semaphore: - """This class is a version of a semaphore. - - If you're wondering why asyncio.Semaphore isn't being used, - it's because it doesn't expose the internal value. This internal - value is necessary because I need to support both `wait=True` and - `wait=False`. - - An asyncio.Queue could have been used to do this as well -- but it is - not as inefficient since internally that uses two queues and is a bit - overkill for what is basically a counter. - """ - - __slots__ = ('value', 'loop', '_waiters') - - def __init__(self, number: int) -> None: - self.value: int = number - self.loop: asyncio.AbstractEventLoop = asyncio.get_running_loop() - self._waiters: Deque[asyncio.Future] = deque() - - def __repr__(self) -> str: - return f'<_Semaphore value={self.value} waiters={len(self._waiters)}>' - - def locked(self) -> bool: - return self.value == 0 - - def is_active(self) -> bool: - return len(self._waiters) > 0 - - def wake_up(self) -> None: - while self._waiters: - future = self._waiters.popleft() - if not future.done(): - future.set_result(None) - return - - async def acquire(self, *, wait: bool = False) -> bool: - if not wait and self.value <= 0: - # signal that we're not acquiring - return False - - while self.value <= 0: - future = self.loop.create_future() - self._waiters.append(future) - try: - await future - except: - future.cancel() - if self.value > 0 and not future.cancelled(): - self.wake_up() - raise - - self.value -= 1 - return True - - def release(self) -> None: - self.value += 1 - self.wake_up() - - -class MaxConcurrency: - __slots__ = ('number', 'per', 'wait', '_mapping') - - def __init__(self, number: int, *, per: BucketType, wait: bool) -> None: - self._mapping: Dict[Any, _Semaphore] = {} - self.per: BucketType = per - self.number: int = number - self.wait: bool = wait - - if number <= 0: - raise ValueError('max_concurrency \'number\' cannot be less than 1') - - if not isinstance(per, BucketType): - raise TypeError(f'max_concurrency \'per\' must be of type BucketType not {type(per)!r}') - - def copy(self) -> Self: - return self.__class__(self.number, per=self.per, wait=self.wait) - - def __repr__(self) -> str: - return f'' - - def get_key(self, message: Union[Message, Context[Any]]) -> Any: - return self.per.get_key(message) - - async def acquire(self, message: Union[Message, Context[Any]]) -> None: - key = self.get_key(message) - - try: - sem = self._mapping[key] - except KeyError: - self._mapping[key] = sem = _Semaphore(self.number) - - acquired = await sem.acquire(wait=self.wait) - if not acquired: - raise MaxConcurrencyReached(self.number, self.per) - - async def release(self, message: Union[Message, Context[Any]]) -> None: - # Technically there's no reason for this function to be async - # But it might be more useful in the future - key = self.get_key(message) - - try: - sem = self._mapping[key] - except KeyError: - # ...? peculiar - return - else: - sem.release() - - if sem.value >= self.number and not sem.is_active(): - del self._mapping[key] diff --git a/.venv/Lib/site-packages/discord/ext/commands/core.py b/.venv/Lib/site-packages/discord/ext/commands/core.py deleted file mode 100644 index 44ddeaf..0000000 --- a/.venv/Lib/site-packages/discord/ext/commands/core.py +++ /dev/null @@ -1,2586 +0,0 @@ -""" -The MIT License (MIT) - -Copyright (c) 2015-present Rapptz - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the "Software"), -to deal in the Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, sublicense, -and/or sell copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. -""" -from __future__ import annotations - -import asyncio -import datetime -import functools -import inspect -from typing import ( - TYPE_CHECKING, - Any, - Callable, - Dict, - Generator, - Generic, - List, - Literal, - Optional, - Set, - Tuple, - Type, - TypeVar, - Union, - overload, -) - -import discord - -from ._types import _BaseCommand, CogT -from .cog import Cog -from .context import Context -from .converter import Greedy, run_converters -from .cooldowns import BucketType, Cooldown, CooldownMapping, DynamicCooldownMapping, MaxConcurrency -from .errors import * -from .parameters import Parameter, Signature - -if TYPE_CHECKING: - from typing_extensions import Concatenate, ParamSpec, Self - - from ._types import BotT, Check, ContextT, Coro, CoroFunc, Error, Hook, UserCheck - - -__all__ = ( - 'Command', - 'Group', - 'GroupMixin', - 'command', - 'group', - 'has_role', - 'has_permissions', - 'has_any_role', - 'check', - 'check_any', - 'before_invoke', - 'after_invoke', - 'bot_has_role', - 'bot_has_permissions', - 'bot_has_any_role', - 'cooldown', - 'dynamic_cooldown', - 'max_concurrency', - 'dm_only', - 'guild_only', - 'is_owner', - 'is_nsfw', - 'has_guild_permissions', - 'bot_has_guild_permissions', -) - -MISSING: Any = discord.utils.MISSING - -T = TypeVar('T') -CommandT = TypeVar('CommandT', bound='Command[Any, ..., Any]') -# CHT = TypeVar('CHT', bound='Check') -GroupT = TypeVar('GroupT', bound='Group[Any, ..., Any]') - -if TYPE_CHECKING: - P = ParamSpec('P') -else: - P = TypeVar('P') - - -def unwrap_function(function: Callable[..., Any], /) -> Callable[..., Any]: - partial = functools.partial - while True: - if hasattr(function, '__wrapped__'): - function = function.__wrapped__ - elif isinstance(function, partial): - function = function.func - else: - return function - - -def get_signature_parameters( - function: Callable[..., Any], - globalns: Dict[str, Any], - /, - *, - skip_parameters: Optional[int] = None, -) -> Dict[str, Parameter]: - signature = Signature.from_callable(function) - params: Dict[str, Parameter] = {} - cache: Dict[str, Any] = {} - eval_annotation = discord.utils.evaluate_annotation - required_params = discord.utils.is_inside_class(function) + 1 if skip_parameters is None else skip_parameters - if len(signature.parameters) < required_params: - raise TypeError(f'Command signature requires at least {required_params - 1} parameter(s)') - - iterator = iter(signature.parameters.items()) - for _ in range(0, required_params): - next(iterator) - - for name, parameter in iterator: - default = parameter.default - if isinstance(default, Parameter): # update from the default - if default.annotation is not Parameter.empty: - # There are a few cases to care about here. - # x: TextChannel = commands.CurrentChannel - # x = commands.CurrentChannel - # In both of these cases, the default parameter has an explicit annotation - # but in the second case it's only used as the fallback. - if default._fallback: - if parameter.annotation is Parameter.empty: - parameter._annotation = default.annotation - else: - parameter._annotation = default.annotation - - parameter._default = default.default - parameter._description = default._description - parameter._displayed_default = default._displayed_default - - annotation = parameter.annotation - - if annotation is None: - params[name] = parameter.replace(annotation=type(None)) - continue - - annotation = eval_annotation(annotation, globalns, globalns, cache) - if annotation is Greedy: - raise TypeError('Unparameterized Greedy[...] is disallowed in signature.') - - params[name] = parameter.replace(annotation=annotation) - - return params - - -def wrap_callback(coro: Callable[P, Coro[T]], /) -> Callable[P, Coro[Optional[T]]]: - @functools.wraps(coro) - async def wrapped(*args: P.args, **kwargs: P.kwargs) -> Optional[T]: - try: - ret = await coro(*args, **kwargs) - except CommandError: - raise - except asyncio.CancelledError: - return - except Exception as exc: - raise CommandInvokeError(exc) from exc - return ret - - return wrapped - - -def hooked_wrapped_callback( - command: Command[Any, ..., Any], ctx: Context[BotT], coro: Callable[P, Coro[T]], / -) -> Callable[P, Coro[Optional[T]]]: - @functools.wraps(coro) - async def wrapped(*args: P.args, **kwargs: P.kwargs) -> Optional[T]: - try: - ret = await coro(*args, **kwargs) - except CommandError: - ctx.command_failed = True - raise - except asyncio.CancelledError: - ctx.command_failed = True - return - except Exception as exc: - ctx.command_failed = True - raise CommandInvokeError(exc) from exc - finally: - if command._max_concurrency is not None: - await command._max_concurrency.release(ctx.message) - - await command.call_after_hooks(ctx) - return ret - - return wrapped - - -class _CaseInsensitiveDict(dict): - def __contains__(self, k): - return super().__contains__(k.casefold()) - - def __delitem__(self, k): - return super().__delitem__(k.casefold()) - - def __getitem__(self, k): - return super().__getitem__(k.casefold()) - - def get(self, k, default=None): - return super().get(k.casefold(), default) - - def pop(self, k, default=None): - return super().pop(k.casefold(), default) - - def __setitem__(self, k, v): - super().__setitem__(k.casefold(), v) - - -class _AttachmentIterator: - def __init__(self, data: List[discord.Attachment]): - self.data: List[discord.Attachment] = data - self.index: int = 0 - - def __iter__(self) -> Self: - return self - - def __next__(self) -> discord.Attachment: - try: - value = self.data[self.index] - except IndexError: - raise StopIteration - else: - self.index += 1 - return value - - def is_empty(self) -> bool: - return self.index >= len(self.data) - - -class Command(_BaseCommand, Generic[CogT, P, T]): - r"""A class that implements the protocol for a bot text command. - - These are not created manually, instead they are created via the - decorator or functional interface. - - Attributes - ----------- - name: :class:`str` - The name of the command. - callback: :ref:`coroutine ` - The coroutine that is executed when the command is called. - help: Optional[:class:`str`] - The long help text for the command. - brief: Optional[:class:`str`] - The short help text for the command. - usage: Optional[:class:`str`] - A replacement for arguments in the default help text. - aliases: Union[List[:class:`str`], Tuple[:class:`str`]] - The list of aliases the command can be invoked under. - enabled: :class:`bool` - A boolean that indicates if the command is currently enabled. - If the command is invoked while it is disabled, then - :exc:`.DisabledCommand` is raised to the :func:`.on_command_error` - event. Defaults to ``True``. - parent: Optional[:class:`Group`] - The parent group that this command belongs to. ``None`` if there - isn't one. - cog: Optional[:class:`Cog`] - The cog that this command belongs to. ``None`` if there isn't one. - checks: List[Callable[[:class:`.Context`], :class:`bool`]] - A list of predicates that verifies if the command could be executed - with the given :class:`.Context` as the sole parameter. If an exception - is necessary to be thrown to signal failure, then one inherited from - :exc:`.CommandError` should be used. Note that if the checks fail then - :exc:`.CheckFailure` exception is raised to the :func:`.on_command_error` - event. - description: :class:`str` - The message prefixed into the default help command. - hidden: :class:`bool` - If ``True``\, the default help command does not show this in the - help output. - rest_is_raw: :class:`bool` - If ``False`` and a keyword-only argument is provided then the keyword - only argument is stripped and handled as if it was a regular argument - that handles :exc:`.MissingRequiredArgument` and default values in a - regular matter rather than passing the rest completely raw. If ``True`` - then the keyword-only argument will pass in the rest of the arguments - in a completely raw matter. Defaults to ``False``. - invoked_subcommand: Optional[:class:`Command`] - The subcommand that was invoked, if any. - require_var_positional: :class:`bool` - If ``True`` and a variadic positional argument is specified, requires - the user to specify at least one argument. Defaults to ``False``. - - .. versionadded:: 1.5 - - ignore_extra: :class:`bool` - If ``True``\, ignores extraneous strings passed to a command if all its - requirements are met (e.g. ``?foo a b c`` when only expecting ``a`` - and ``b``). Otherwise :func:`.on_command_error` and local error handlers - are called with :exc:`.TooManyArguments`. Defaults to ``True``. - cooldown_after_parsing: :class:`bool` - If ``True``\, cooldown processing is done after argument parsing, - which calls converters. If ``False`` then cooldown processing is done - first and then the converters are called second. Defaults to ``False``. - extras: :class:`dict` - A dict of user provided extras to attach to the Command. - - .. note:: - This object may be copied by the library. - - - .. versionadded:: 2.0 - """ - __original_kwargs__: Dict[str, Any] - - def __new__(cls, *args: Any, **kwargs: Any) -> Self: - # if you're wondering why this is done, it's because we need to ensure - # we have a complete original copy of **kwargs even for classes that - # mess with it by popping before delegating to the subclass __init__. - # In order to do this, we need to control the instance creation and - # inject the original kwargs through __new__ rather than doing it - # inside __init__. - self = super().__new__(cls) - - # we do a shallow copy because it's probably the most common use case. - # this could potentially break if someone modifies a list or something - # while it's in movement, but for now this is the cheapest and - # fastest way to do what we want. - self.__original_kwargs__ = kwargs.copy() - return self - - def __init__( - self, - func: Union[ - Callable[Concatenate[CogT, Context[Any], P], Coro[T]], - Callable[Concatenate[Context[Any], P], Coro[T]], - ], - /, - **kwargs: Any, - ) -> None: - if not asyncio.iscoroutinefunction(func): - raise TypeError('Callback must be a coroutine.') - - name = kwargs.get('name') or func.__name__ - if not isinstance(name, str): - raise TypeError('Name of a command must be a string.') - self.name: str = name - - self.callback = func - self.enabled: bool = kwargs.get('enabled', True) - - help_doc = kwargs.get('help') - if help_doc is not None: - help_doc = inspect.cleandoc(help_doc) - else: - help_doc = inspect.getdoc(func) - if isinstance(help_doc, bytes): - help_doc = help_doc.decode('utf-8') - - self.help: Optional[str] = help_doc - - self.brief: Optional[str] = kwargs.get('brief') - self.usage: Optional[str] = kwargs.get('usage') - self.rest_is_raw: bool = kwargs.get('rest_is_raw', False) - self.aliases: Union[List[str], Tuple[str]] = kwargs.get('aliases', []) - self.extras: Dict[Any, Any] = kwargs.get('extras', {}) - - if not isinstance(self.aliases, (list, tuple)): - raise TypeError("Aliases of a command must be a list or a tuple of strings.") - - self.description: str = inspect.cleandoc(kwargs.get('description', '')) - self.hidden: bool = kwargs.get('hidden', False) - - try: - checks = func.__commands_checks__ - checks.reverse() - except AttributeError: - checks = kwargs.get('checks', []) - - self.checks: List[UserCheck[Context[Any]]] = checks - - try: - cooldown = func.__commands_cooldown__ - except AttributeError: - cooldown = kwargs.get('cooldown') - - if cooldown is None: - buckets = CooldownMapping(cooldown, BucketType.default) - elif isinstance(cooldown, CooldownMapping): - buckets: CooldownMapping[Context[Any]] = cooldown - else: - raise TypeError("Cooldown must be an instance of CooldownMapping or None.") - self._buckets: CooldownMapping[Context[Any]] = buckets - - try: - max_concurrency = func.__commands_max_concurrency__ - except AttributeError: - max_concurrency = kwargs.get('max_concurrency') - - self._max_concurrency: Optional[MaxConcurrency] = max_concurrency - - self.require_var_positional: bool = kwargs.get('require_var_positional', False) - self.ignore_extra: bool = kwargs.get('ignore_extra', True) - self.cooldown_after_parsing: bool = kwargs.get('cooldown_after_parsing', False) - self._cog: CogT = None - - # bandaid for the fact that sometimes parent can be the bot instance - parent: Optional[GroupMixin[Any]] = kwargs.get('parent') - self.parent: Optional[GroupMixin[Any]] = parent if isinstance(parent, _BaseCommand) else None - - self._before_invoke: Optional[Hook] = None - try: - before_invoke = func.__before_invoke__ - except AttributeError: - pass - else: - self.before_invoke(before_invoke) - - self._after_invoke: Optional[Hook] = None - try: - after_invoke = func.__after_invoke__ - except AttributeError: - pass - else: - self.after_invoke(after_invoke) - - @property - def cog(self) -> CogT: - return self._cog - - @cog.setter - def cog(self, value: CogT) -> None: - self._cog = value - - @property - def callback( - self, - ) -> Union[Callable[Concatenate[CogT, Context[Any], P], Coro[T]], Callable[Concatenate[Context[Any], P], Coro[T]],]: - return self._callback - - @callback.setter - def callback( - self, - function: Union[ - Callable[Concatenate[CogT, Context[Any], P], Coro[T]], - Callable[Concatenate[Context[Any], P], Coro[T]], - ], - ) -> None: - self._callback = function - unwrap = unwrap_function(function) - self.module: str = unwrap.__module__ - - try: - globalns = unwrap.__globals__ - except AttributeError: - globalns = {} - - self.params: Dict[str, Parameter] = get_signature_parameters(function, globalns) - - def add_check(self, func: UserCheck[Context[Any]], /) -> None: - """Adds a check to the command. - - This is the non-decorator interface to :func:`.check`. - - .. versionadded:: 1.3 - - .. versionchanged:: 2.0 - - ``func`` parameter is now positional-only. - - .. seealso:: The :func:`~discord.ext.commands.check` decorator - - Parameters - ----------- - func - The function that will be used as a check. - """ - - self.checks.append(func) - - def remove_check(self, func: UserCheck[Context[Any]], /) -> None: - """Removes a check from the command. - - This function is idempotent and will not raise an exception - if the function is not in the command's checks. - - .. versionadded:: 1.3 - - .. versionchanged:: 2.0 - - ``func`` parameter is now positional-only. - - Parameters - ----------- - func - The function to remove from the checks. - """ - - try: - self.checks.remove(func) - except ValueError: - pass - - def update(self, **kwargs: Any) -> None: - """Updates :class:`Command` instance with updated attribute. - - This works similarly to the :func:`~discord.ext.commands.command` decorator in terms - of parameters in that they are passed to the :class:`Command` or - subclass constructors, sans the name and callback. - """ - cog = self.cog - self.__init__(self.callback, **dict(self.__original_kwargs__, **kwargs)) - self.cog = cog - - async def __call__(self, context: Context[BotT], /, *args: P.args, **kwargs: P.kwargs) -> T: - """|coro| - - Calls the internal callback that the command holds. - - .. note:: - - This bypasses all mechanisms -- including checks, converters, - invoke hooks, cooldowns, etc. You must take care to pass - the proper arguments and types to this function. - - .. versionadded:: 1.3 - - .. versionchanged:: 2.0 - - ``context`` parameter is now positional-only. - """ - if self.cog is not None: - return await self.callback(self.cog, context, *args, **kwargs) # type: ignore - else: - return await self.callback(context, *args, **kwargs) # type: ignore - - def _ensure_assignment_on_copy(self, other: Self) -> Self: - other._before_invoke = self._before_invoke - other._after_invoke = self._after_invoke - other.extras = self.extras - if self.checks != other.checks: - other.checks = self.checks.copy() - if self._buckets.valid and not other._buckets.valid: - other._buckets = self._buckets.copy() - if self._max_concurrency and self._max_concurrency != other._max_concurrency: - other._max_concurrency = self._max_concurrency.copy() - - try: - other.on_error = self.on_error - except AttributeError: - pass - return other - - def copy(self) -> Self: - """Creates a copy of this command. - - Returns - -------- - :class:`Command` - A new instance of this command. - """ - ret = self.__class__(self.callback, **self.__original_kwargs__) - return self._ensure_assignment_on_copy(ret) - - def _update_copy(self, kwargs: Dict[str, Any]) -> Self: - if kwargs: - kw = kwargs.copy() - kw.update(self.__original_kwargs__) - copy = self.__class__(self.callback, **kw) - return self._ensure_assignment_on_copy(copy) - else: - return self.copy() - - async def dispatch_error(self, ctx: Context[BotT], error: CommandError, /) -> None: - ctx.command_failed = True - cog = self.cog - try: - coro = self.on_error - except AttributeError: - pass - else: - injected = wrap_callback(coro) # type: ignore - if cog is not None: - await injected(cog, ctx, error) - else: - await injected(ctx, error) # type: ignore - - try: - if cog is not None: - local = Cog._get_overridden_method(cog.cog_command_error) - if local is not None: - wrapped = wrap_callback(local) - await wrapped(ctx, error) - finally: - ctx.bot.dispatch('command_error', ctx, error) - - async def transform(self, ctx: Context[BotT], param: Parameter, attachments: _AttachmentIterator, /) -> Any: - converter = param.converter - consume_rest_is_special = param.kind == param.KEYWORD_ONLY and not self.rest_is_raw - view = ctx.view - view.skip_ws() - - # The greedy converter is simple -- it keeps going until it fails in which case, - # it undos the view ready for the next parameter to use instead - if isinstance(converter, Greedy): - # Special case for Greedy[discord.Attachment] to consume the attachments iterator - if converter.converter is discord.Attachment: - return list(attachments) - - if param.kind in (param.POSITIONAL_OR_KEYWORD, param.POSITIONAL_ONLY): - return await self._transform_greedy_pos(ctx, param, param.required, converter.converter) - elif param.kind == param.VAR_POSITIONAL: - return await self._transform_greedy_var_pos(ctx, param, converter.converter) - else: - # if we're here, then it's a KEYWORD_ONLY param type - # since this is mostly useless, we'll helpfully transform Greedy[X] - # into just X and do the parsing that way. - converter = converter.converter - - # Try to detect Optional[discord.Attachment] or discord.Attachment special converter - if converter is discord.Attachment: - try: - return next(attachments) - except StopIteration: - raise MissingRequiredAttachment(param) - - if self._is_typing_optional(param.annotation) and param.annotation.__args__[0] is discord.Attachment: - if attachments.is_empty(): - # I have no idea who would be doing Optional[discord.Attachment] = 1 - # but for those cases then 1 should be returned instead of None - return None if param.default is param.empty else param.default - return next(attachments) - - if view.eof: - if param.kind == param.VAR_POSITIONAL: - raise RuntimeError() # break the loop - if param.required: - if self._is_typing_optional(param.annotation): - return None - if hasattr(converter, '__commands_is_flag__') and converter._can_be_constructible(): - return await converter._construct_default(ctx) - raise MissingRequiredArgument(param) - return await param.get_default(ctx) - - previous = view.index - if consume_rest_is_special: - ctx.current_argument = argument = view.read_rest().strip() - else: - try: - ctx.current_argument = argument = view.get_quoted_word() - except ArgumentParsingError as exc: - if self._is_typing_optional(param.annotation): - view.index = previous - return None if param.required else await param.get_default(ctx) - else: - raise exc - view.previous = previous - - # type-checker fails to narrow argument - return await run_converters(ctx, converter, argument, param) # type: ignore - - async def _transform_greedy_pos(self, ctx: Context[BotT], param: Parameter, required: bool, converter: Any) -> Any: - view = ctx.view - result = [] - while not view.eof: - # for use with a manual undo - previous = view.index - - view.skip_ws() - try: - ctx.current_argument = argument = view.get_quoted_word() - value = await run_converters(ctx, converter, argument, param) # type: ignore - except (CommandError, ArgumentParsingError): - view.index = previous - break - else: - result.append(value) - - if not result and not required: - return await param.get_default(ctx) - return result - - async def _transform_greedy_var_pos(self, ctx: Context[BotT], param: Parameter, converter: Any) -> Any: - view = ctx.view - previous = view.index - try: - ctx.current_argument = argument = view.get_quoted_word() - value = await run_converters(ctx, converter, argument, param) # type: ignore - except (CommandError, ArgumentParsingError): - view.index = previous - raise RuntimeError() from None # break loop - else: - return value - - @property - def clean_params(self) -> Dict[str, Parameter]: - """Dict[:class:`str`, :class:`Parameter`]: - Retrieves the parameter dictionary without the context or self parameters. - - Useful for inspecting signature. - """ - return self.params.copy() - - @property - def cooldown(self) -> Optional[Cooldown]: - """Optional[:class:`~discord.app_commands.Cooldown`]: The cooldown of a command when invoked - or ``None`` if the command doesn't have a registered cooldown. - - .. versionadded:: 2.0 - """ - return self._buckets._cooldown - - @property - def full_parent_name(self) -> str: - """:class:`str`: Retrieves the fully qualified parent command name. - - This the base command name required to execute it. For example, - in ``?one two three`` the parent name would be ``one two``. - """ - entries = [] - command = self - # command.parent is type-hinted as GroupMixin some attributes are resolved via MRO - while command.parent is not None: # type: ignore - command = command.parent # type: ignore - entries.append(command.name) # type: ignore - - return ' '.join(reversed(entries)) - - @property - def parents(self) -> List[Group[Any, ..., Any]]: - """List[:class:`Group`]: Retrieves the parents of this command. - - If the command has no parents then it returns an empty :class:`list`. - - For example in commands ``?a b c test``, the parents are ``[c, b, a]``. - - .. versionadded:: 1.1 - """ - entries = [] - command = self - while command.parent is not None: # type: ignore - command = command.parent # type: ignore - entries.append(command) - - return entries - - @property - def root_parent(self) -> Optional[Group[Any, ..., Any]]: - """Optional[:class:`Group`]: Retrieves the root parent of this command. - - If the command has no parents then it returns ``None``. - - For example in commands ``?a b c test``, the root parent is ``a``. - """ - if not self.parent: - return None - return self.parents[-1] - - @property - def qualified_name(self) -> str: - """:class:`str`: Retrieves the fully qualified command name. - - This is the full parent name with the command name as well. - For example, in ``?one two three`` the qualified name would be - ``one two three``. - """ - - parent = self.full_parent_name - if parent: - return parent + ' ' + self.name - else: - return self.name - - def __str__(self) -> str: - return self.qualified_name - - async def _parse_arguments(self, ctx: Context[BotT]) -> None: - ctx.args = [ctx] if self.cog is None else [self.cog, ctx] - ctx.kwargs = {} - args = ctx.args - kwargs = ctx.kwargs - attachments = _AttachmentIterator(ctx.message.attachments) - - view = ctx.view - iterator = iter(self.params.items()) - - for name, param in iterator: - ctx.current_parameter = param - if param.kind in (param.POSITIONAL_OR_KEYWORD, param.POSITIONAL_ONLY): - transformed = await self.transform(ctx, param, attachments) - args.append(transformed) - elif param.kind == param.KEYWORD_ONLY: - # kwarg only param denotes "consume rest" semantics - if self.rest_is_raw: - ctx.current_argument = argument = view.read_rest() - kwargs[name] = await run_converters(ctx, param.converter, argument, param) - else: - kwargs[name] = await self.transform(ctx, param, attachments) - break - elif param.kind == param.VAR_POSITIONAL: - if view.eof and self.require_var_positional: - raise MissingRequiredArgument(param) - while not view.eof: - try: - transformed = await self.transform(ctx, param, attachments) - args.append(transformed) - except RuntimeError: - break - - if not self.ignore_extra and not view.eof: - raise TooManyArguments('Too many arguments passed to ' + self.qualified_name) - - async def call_before_hooks(self, ctx: Context[BotT], /) -> None: - # now that we're done preparing we can call the pre-command hooks - # first, call the command local hook: - cog = self.cog - if self._before_invoke is not None: - # should be cog if @commands.before_invoke is used - instance = getattr(self._before_invoke, '__self__', cog) - # __self__ only exists for methods, not functions - # however, if @command.before_invoke is used, it will be a function - if instance: - await self._before_invoke(instance, ctx) # type: ignore - else: - await self._before_invoke(ctx) # type: ignore - - # call the cog local hook if applicable: - if cog is not None: - hook = Cog._get_overridden_method(cog.cog_before_invoke) - if hook is not None: - await hook(ctx) - - # call the bot global hook if necessary - hook = ctx.bot._before_invoke - if hook is not None: - await hook(ctx) - - async def call_after_hooks(self, ctx: Context[BotT], /) -> None: - cog = self.cog - if self._after_invoke is not None: - instance = getattr(self._after_invoke, '__self__', cog) - if instance: - await self._after_invoke(instance, ctx) # type: ignore - else: - await self._after_invoke(ctx) # type: ignore - - # call the cog local hook if applicable: - if cog is not None: - hook = Cog._get_overridden_method(cog.cog_after_invoke) - if hook is not None: - await hook(ctx) - - hook = ctx.bot._after_invoke - if hook is not None: - await hook(ctx) - - def _prepare_cooldowns(self, ctx: Context[BotT]) -> None: - if self._buckets.valid: - dt = ctx.message.edited_at or ctx.message.created_at - current = dt.replace(tzinfo=datetime.timezone.utc).timestamp() - bucket = self._buckets.get_bucket(ctx, current) - if bucket is not None: - retry_after = bucket.update_rate_limit(current) - if retry_after: - raise CommandOnCooldown(bucket, retry_after, self._buckets.type) # type: ignore - - async def prepare(self, ctx: Context[BotT], /) -> None: - ctx.command = self - - if not await self.can_run(ctx): - raise CheckFailure(f'The check functions for command {self.qualified_name} failed.') - - if self._max_concurrency is not None: - # For this application, context can be duck-typed as a Message - await self._max_concurrency.acquire(ctx) - - try: - if self.cooldown_after_parsing: - await self._parse_arguments(ctx) - self._prepare_cooldowns(ctx) - else: - self._prepare_cooldowns(ctx) - await self._parse_arguments(ctx) - - await self.call_before_hooks(ctx) - except: - if self._max_concurrency is not None: - await self._max_concurrency.release(ctx) - raise - - def is_on_cooldown(self, ctx: Context[BotT], /) -> bool: - """Checks whether the command is currently on cooldown. - - .. versionchanged:: 2.0 - - ``ctx`` parameter is now positional-only. - - Parameters - ----------- - ctx: :class:`.Context` - The invocation context to use when checking the commands cooldown status. - - Returns - -------- - :class:`bool` - A boolean indicating if the command is on cooldown. - """ - if not self._buckets.valid: - return False - - bucket = self._buckets.get_bucket(ctx) - if bucket is None: - return False - dt = ctx.message.edited_at or ctx.message.created_at - current = dt.replace(tzinfo=datetime.timezone.utc).timestamp() - return bucket.get_tokens(current) == 0 - - def reset_cooldown(self, ctx: Context[BotT], /) -> None: - """Resets the cooldown on this command. - - .. versionchanged:: 2.0 - - ``ctx`` parameter is now positional-only. - - Parameters - ----------- - ctx: :class:`.Context` - The invocation context to reset the cooldown under. - """ - if self._buckets.valid: - bucket = self._buckets.get_bucket(ctx) - if bucket is not None: - bucket.reset() - - def get_cooldown_retry_after(self, ctx: Context[BotT], /) -> float: - """Retrieves the amount of seconds before this command can be tried again. - - .. versionadded:: 1.4 - - .. versionchanged:: 2.0 - - ``ctx`` parameter is now positional-only. - - Parameters - ----------- - ctx: :class:`.Context` - The invocation context to retrieve the cooldown from. - - Returns - -------- - :class:`float` - The amount of time left on this command's cooldown in seconds. - If this is ``0.0`` then the command isn't on cooldown. - """ - if self._buckets.valid: - bucket = self._buckets.get_bucket(ctx) - if bucket is None: - return 0.0 - dt = ctx.message.edited_at or ctx.message.created_at - current = dt.replace(tzinfo=datetime.timezone.utc).timestamp() - return bucket.get_retry_after(current) - - return 0.0 - - async def invoke(self, ctx: Context[BotT], /) -> None: - await self.prepare(ctx) - - # terminate the invoked_subcommand chain. - # since we're in a regular command (and not a group) then - # the invoked subcommand is None. - ctx.invoked_subcommand = None - ctx.subcommand_passed = None - injected = hooked_wrapped_callback(self, ctx, self.callback) # type: ignore - await injected(*ctx.args, **ctx.kwargs) # type: ignore - - async def reinvoke(self, ctx: Context[BotT], /, *, call_hooks: bool = False) -> None: - ctx.command = self - await self._parse_arguments(ctx) - - if call_hooks: - await self.call_before_hooks(ctx) - - ctx.invoked_subcommand = None - try: - await self.callback(*ctx.args, **ctx.kwargs) # type: ignore - except: - ctx.command_failed = True - raise - finally: - if call_hooks: - await self.call_after_hooks(ctx) - - def error(self, coro: Error[CogT, ContextT], /) -> Error[CogT, ContextT]: - """A decorator that registers a coroutine as a local error handler. - - A local error handler is an :func:`.on_command_error` event limited to - a single command. However, the :func:`.on_command_error` is still - invoked afterwards as the catch-all. - - .. versionchanged:: 2.0 - - ``coro`` parameter is now positional-only. - - Parameters - ----------- - coro: :ref:`coroutine ` - The coroutine to register as the local error handler. - - Raises - ------- - TypeError - The coroutine passed is not actually a coroutine. - """ - - if not asyncio.iscoroutinefunction(coro): - raise TypeError('The error handler must be a coroutine.') - - self.on_error: Error[CogT, Any] = coro - return coro - - def has_error_handler(self) -> bool: - """:class:`bool`: Checks whether the command has an error handler registered. - - .. versionadded:: 1.7 - """ - return hasattr(self, 'on_error') - - def before_invoke(self, coro: Hook[CogT, ContextT], /) -> Hook[CogT, ContextT]: - """A decorator that registers a coroutine as a pre-invoke hook. - - A pre-invoke hook is called directly before the command is - called. This makes it a useful function to set up database - connections or any type of set up required. - - This pre-invoke hook takes a sole parameter, a :class:`.Context`. - - See :meth:`.Bot.before_invoke` for more info. - - .. versionchanged:: 2.0 - - ``coro`` parameter is now positional-only. - - Parameters - ----------- - coro: :ref:`coroutine ` - The coroutine to register as the pre-invoke hook. - - Raises - ------- - TypeError - The coroutine passed is not actually a coroutine. - """ - if not asyncio.iscoroutinefunction(coro): - raise TypeError('The pre-invoke hook must be a coroutine.') - - self._before_invoke = coro - return coro - - def after_invoke(self, coro: Hook[CogT, ContextT], /) -> Hook[CogT, ContextT]: - """A decorator that registers a coroutine as a post-invoke hook. - - A post-invoke hook is called directly after the command is - called. This makes it a useful function to clean-up database - connections or any type of clean up required. - - This post-invoke hook takes a sole parameter, a :class:`.Context`. - - See :meth:`.Bot.after_invoke` for more info. - - .. versionchanged:: 2.0 - - ``coro`` parameter is now positional-only. - - Parameters - ----------- - coro: :ref:`coroutine ` - The coroutine to register as the post-invoke hook. - - Raises - ------- - TypeError - The coroutine passed is not actually a coroutine. - """ - if not asyncio.iscoroutinefunction(coro): - raise TypeError('The post-invoke hook must be a coroutine.') - - self._after_invoke = coro - return coro - - @property - def cog_name(self) -> Optional[str]: - """Optional[:class:`str`]: The name of the cog this command belongs to, if any.""" - return type(self.cog).__cog_name__ if self.cog is not None else None - - @property - def short_doc(self) -> str: - """:class:`str`: Gets the "short" documentation of a command. - - By default, this is the :attr:`.brief` attribute. - If that lookup leads to an empty string then the first line of the - :attr:`.help` attribute is used instead. - """ - if self.brief is not None: - return self.brief - if self.help is not None: - return self.help.split('\n', 1)[0] - return '' - - def _is_typing_optional(self, annotation: Union[T, Optional[T]]) -> bool: - return getattr(annotation, '__origin__', None) is Union and type(None) in annotation.__args__ # type: ignore - - @property - def signature(self) -> str: - """:class:`str`: Returns a POSIX-like signature useful for help command output.""" - if self.usage is not None: - return self.usage - - params = self.clean_params - if not params: - return '' - - result = [] - for name, param in params.items(): - greedy = isinstance(param.converter, Greedy) - optional = False # postpone evaluation of if it's an optional argument - - annotation: Any = param.converter.converter if greedy else param.converter - origin = getattr(annotation, '__origin__', None) - if not greedy and origin is Union: - none_cls = type(None) - union_args = annotation.__args__ - optional = union_args[-1] is none_cls - if len(union_args) == 2 and optional: - annotation = union_args[0] - origin = getattr(annotation, '__origin__', None) - - if annotation is discord.Attachment: - # For discord.Attachment we need to signal to the user that it's an attachment - # It's not exactly pretty but it's enough to differentiate - if optional: - result.append(f'[{name} (upload a file)]') - elif greedy: - result.append(f'[{name} (upload files)]...') - else: - result.append(f'<{name} (upload a file)>') - continue - - # for typing.Literal[...], typing.Optional[typing.Literal[...]], and Greedy[typing.Literal[...]], the - # parameter signature is a literal list of it's values - if origin is Literal: - name = '|'.join(f'"{v}"' if isinstance(v, str) else str(v) for v in annotation.__args__) - if not param.required: - # We don't want None or '' to trigger the [name=value] case and instead it should - # do [name] since [name=None] or [name=] are not exactly useful for the user. - if param.displayed_default: - result.append( - f'[{name}={param.displayed_default}]' if not greedy else f'[{name}={param.displayed_default}]...' - ) - continue - else: - result.append(f'[{name}]') - - elif param.kind == param.VAR_POSITIONAL: - if self.require_var_positional: - result.append(f'<{name}...>') - else: - result.append(f'[{name}...]') - elif greedy: - result.append(f'[{name}]...') - elif optional: - result.append(f'[{name}]') - else: - result.append(f'<{name}>') - - return ' '.join(result) - - async def can_run(self, ctx: Context[BotT], /) -> bool: - """|coro| - - Checks if the command can be executed by checking all the predicates - inside the :attr:`~Command.checks` attribute. This also checks whether the - command is disabled. - - .. versionchanged:: 1.3 - Checks whether the command is disabled or not - - .. versionchanged:: 2.0 - - ``ctx`` parameter is now positional-only. - - Parameters - ----------- - ctx: :class:`.Context` - The ctx of the command currently being invoked. - - Raises - ------- - :class:`CommandError` - Any command error that was raised during a check call will be propagated - by this function. - - Returns - -------- - :class:`bool` - A boolean indicating if the command can be invoked. - """ - - if not self.enabled: - raise DisabledCommand(f'{self.name} command is disabled') - - original = ctx.command - ctx.command = self - - try: - if not await ctx.bot.can_run(ctx): - raise CheckFailure(f'The global check functions for command {self.qualified_name} failed.') - - cog = self.cog - if cog is not None: - local_check = Cog._get_overridden_method(cog.cog_check) - if local_check is not None: - ret = await discord.utils.maybe_coroutine(local_check, ctx) - if not ret: - return False - - predicates = self.checks - if not predicates: - # since we have no checks, then we just return True. - return True - - return await discord.utils.async_all(predicate(ctx) for predicate in predicates) - finally: - ctx.command = original - - -class GroupMixin(Generic[CogT]): - """A mixin that implements common functionality for classes that behave - similar to :class:`.Group` and are allowed to register commands. - - Attributes - ----------- - all_commands: :class:`dict` - A mapping of command name to :class:`.Command` - objects. - case_insensitive: :class:`bool` - Whether the commands should be case insensitive. Defaults to ``False``. - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - case_insensitive = kwargs.get('case_insensitive', False) - self.all_commands: Dict[str, Command[CogT, ..., Any]] = _CaseInsensitiveDict() if case_insensitive else {} - self.case_insensitive: bool = case_insensitive - super().__init__(*args, **kwargs) - - @property - def commands(self) -> Set[Command[CogT, ..., Any]]: - """Set[:class:`.Command`]: A unique set of commands without aliases that are registered.""" - return set(self.all_commands.values()) - - def recursively_remove_all_commands(self) -> None: - for command in self.all_commands.copy().values(): - if isinstance(command, GroupMixin): - command.recursively_remove_all_commands() - self.remove_command(command.name) - - def add_command(self, command: Command[CogT, ..., Any], /) -> None: - """Adds a :class:`.Command` into the internal list of commands. - - This is usually not called, instead the :meth:`~.GroupMixin.command` or - :meth:`~.GroupMixin.group` shortcut decorators are used instead. - - .. versionchanged:: 1.4 - Raise :exc:`.CommandRegistrationError` instead of generic :exc:`.ClientException` - - .. versionchanged:: 2.0 - - ``command`` parameter is now positional-only. - - Parameters - ----------- - command: :class:`Command` - The command to add. - - Raises - ------- - CommandRegistrationError - If the command or its alias is already registered by different command. - TypeError - If the command passed is not a subclass of :class:`.Command`. - """ - - if not isinstance(command, Command): - raise TypeError('The command passed must be a subclass of Command') - - if isinstance(self, Command): - command.parent = self - - if command.name in self.all_commands: - raise CommandRegistrationError(command.name) - - self.all_commands[command.name] = command - for alias in command.aliases: - if alias in self.all_commands: - self.remove_command(command.name) - raise CommandRegistrationError(alias, alias_conflict=True) - self.all_commands[alias] = command - - def remove_command(self, name: str, /) -> Optional[Command[CogT, ..., Any]]: - """Remove a :class:`.Command` from the internal list - of commands. - - This could also be used as a way to remove aliases. - - .. versionchanged:: 2.0 - - ``name`` parameter is now positional-only. - - Parameters - ----------- - name: :class:`str` - The name of the command to remove. - - Returns - -------- - Optional[:class:`.Command`] - The command that was removed. If the name is not valid then - ``None`` is returned instead. - """ - command = self.all_commands.pop(name, None) - - # does not exist - if command is None: - return None - - if name in command.aliases: - # we're removing an alias so we don't want to remove the rest - return command - - # we're not removing the alias so let's delete the rest of them. - for alias in command.aliases: - cmd = self.all_commands.pop(alias, None) - # in the case of a CommandRegistrationError, an alias might conflict - # with an already existing command. If this is the case, we want to - # make sure the pre-existing command is not removed. - if cmd is not None and cmd != command: - self.all_commands[alias] = cmd - return command - - def walk_commands(self) -> Generator[Command[CogT, ..., Any], None, None]: - """An iterator that recursively walks through all commands and subcommands. - - .. versionchanged:: 1.4 - Duplicates due to aliases are no longer returned - - Yields - ------ - Union[:class:`.Command`, :class:`.Group`] - A command or group from the internal list of commands. - """ - for command in self.commands: - yield command - if isinstance(command, GroupMixin): - yield from command.walk_commands() - - def get_command(self, name: str, /) -> Optional[Command[CogT, ..., Any]]: - """Get a :class:`.Command` from the internal list - of commands. - - This could also be used as a way to get aliases. - - The name could be fully qualified (e.g. ``'foo bar'``) will get - the subcommand ``bar`` of the group command ``foo``. If a - subcommand is not found then ``None`` is returned just as usual. - - .. versionchanged:: 2.0 - - ``name`` parameter is now positional-only. - - Parameters - ----------- - name: :class:`str` - The name of the command to get. - - Returns - -------- - Optional[:class:`Command`] - The command that was requested. If not found, returns ``None``. - """ - - # fast path, no space in name. - if ' ' not in name: - return self.all_commands.get(name) - - names = name.split() - if not names: - return None - obj = self.all_commands.get(names[0]) - if not isinstance(obj, GroupMixin): - return obj - - for name in names[1:]: - try: - obj = obj.all_commands[name] # type: ignore - except (AttributeError, KeyError): - return None - - return obj - - @overload - def command( - self: GroupMixin[CogT], - name: str = ..., - *args: Any, - **kwargs: Any, - ) -> Callable[ - [ - Union[ - Callable[Concatenate[CogT, ContextT, P], Coro[T]], - Callable[Concatenate[ContextT, P], Coro[T]], - ] - ], - Command[CogT, P, T], - ]: - ... - - @overload - def command( - self: GroupMixin[CogT], - name: str = ..., - cls: Type[CommandT] = ..., # type: ignore # previous overload handles case where cls is not set - *args: Any, - **kwargs: Any, - ) -> Callable[ - [ - Union[ - Callable[Concatenate[CogT, ContextT, P], Coro[T]], - Callable[Concatenate[ContextT, P], Coro[T]], - ] - ], - CommandT, - ]: - ... - - def command( - self, - name: str = MISSING, - cls: Type[Command[Any, ..., Any]] = MISSING, - *args: Any, - **kwargs: Any, - ) -> Any: - """A shortcut decorator that invokes :func:`~discord.ext.commands.command` and adds it to - the internal command list via :meth:`~.GroupMixin.add_command`. - - Returns - -------- - Callable[..., :class:`Command`] - A decorator that converts the provided method into a Command, adds it to the bot, then returns it. - """ - - def decorator(func): - - kwargs.setdefault('parent', self) - result = command(name=name, cls=cls, *args, **kwargs)(func) - self.add_command(result) - return result - - return decorator - - @overload - def group( - self: GroupMixin[CogT], - name: str = ..., - *args: Any, - **kwargs: Any, - ) -> Callable[ - [ - Union[ - Callable[Concatenate[CogT, ContextT, P], Coro[T]], - Callable[Concatenate[ContextT, P], Coro[T]], - ] - ], - Group[CogT, P, T], - ]: - ... - - @overload - def group( - self: GroupMixin[CogT], - name: str = ..., - cls: Type[GroupT] = ..., # type: ignore # previous overload handles case where cls is not set - *args: Any, - **kwargs: Any, - ) -> Callable[ - [ - Union[ - Callable[Concatenate[CogT, ContextT, P], Coro[T]], - Callable[Concatenate[ContextT, P], Coro[T]], - ] - ], - GroupT, - ]: - ... - - def group( - self, - name: str = MISSING, - cls: Type[Group[Any, ..., Any]] = MISSING, - *args: Any, - **kwargs: Any, - ) -> Any: - """A shortcut decorator that invokes :func:`.group` and adds it to - the internal command list via :meth:`~.GroupMixin.add_command`. - - Returns - -------- - Callable[..., :class:`Group`] - A decorator that converts the provided method into a Group, adds it to the bot, then returns it. - """ - - def decorator(func): - kwargs.setdefault('parent', self) - result = group(name=name, cls=cls, *args, **kwargs)(func) - self.add_command(result) - return result - - return decorator - - -class Group(GroupMixin[CogT], Command[CogT, P, T]): - """A class that implements a grouping protocol for commands to be - executed as subcommands. - - This class is a subclass of :class:`.Command` and thus all options - valid in :class:`.Command` are valid in here as well. - - Attributes - ----------- - invoke_without_command: :class:`bool` - Indicates if the group callback should begin parsing and - invocation only if no subcommand was found. Useful for - making it an error handling function to tell the user that - no subcommand was found or to have different functionality - in case no subcommand was found. If this is ``False``, then - the group callback will always be invoked first. This means - that the checks and the parsing dictated by its parameters - will be executed. Defaults to ``False``. - case_insensitive: :class:`bool` - Indicates if the group's commands should be case insensitive. - Defaults to ``False``. - """ - - def __init__(self, *args: Any, **attrs: Any) -> None: - self.invoke_without_command: bool = attrs.pop('invoke_without_command', False) - super().__init__(*args, **attrs) - - def copy(self) -> Self: - """Creates a copy of this :class:`Group`. - - Returns - -------- - :class:`Group` - A new instance of this group. - """ - ret = super().copy() - for cmd in self.commands: - ret.add_command(cmd.copy()) - return ret - - async def invoke(self, ctx: Context[BotT], /) -> None: - ctx.invoked_subcommand = None - ctx.subcommand_passed = None - early_invoke = not self.invoke_without_command - if early_invoke: - await self.prepare(ctx) - - view = ctx.view - previous = view.index - view.skip_ws() - trigger = view.get_word() - - if trigger: - ctx.subcommand_passed = trigger - ctx.invoked_subcommand = self.all_commands.get(trigger, None) - - if early_invoke: - injected = hooked_wrapped_callback(self, ctx, self.callback) # type: ignore - await injected(*ctx.args, **ctx.kwargs) # type: ignore - - ctx.invoked_parents.append(ctx.invoked_with) # type: ignore - - if trigger and ctx.invoked_subcommand: - ctx.invoked_with = trigger - await ctx.invoked_subcommand.invoke(ctx) - elif not early_invoke: - # undo the trigger parsing - view.index = previous - view.previous = previous - await super().invoke(ctx) - - async def reinvoke(self, ctx: Context[BotT], /, *, call_hooks: bool = False) -> None: - ctx.invoked_subcommand = None - early_invoke = not self.invoke_without_command - if early_invoke: - ctx.command = self - await self._parse_arguments(ctx) - - if call_hooks: - await self.call_before_hooks(ctx) - - view = ctx.view - previous = view.index - view.skip_ws() - trigger = view.get_word() - - if trigger: - ctx.subcommand_passed = trigger - ctx.invoked_subcommand = self.all_commands.get(trigger, None) - - if early_invoke: - try: - await self.callback(*ctx.args, **ctx.kwargs) # type: ignore - except: - ctx.command_failed = True - raise - finally: - if call_hooks: - await self.call_after_hooks(ctx) - - ctx.invoked_parents.append(ctx.invoked_with) # type: ignore - - if trigger and ctx.invoked_subcommand: - ctx.invoked_with = trigger - await ctx.invoked_subcommand.reinvoke(ctx, call_hooks=call_hooks) - elif not early_invoke: - # undo the trigger parsing - view.index = previous - view.previous = previous - await super().reinvoke(ctx, call_hooks=call_hooks) - - -# Decorators - -if TYPE_CHECKING: - # Using a class to emulate a function allows for overloading the inner function in the decorator. - - class _CommandDecorator: - @overload - def __call__(self, func: Callable[Concatenate[CogT, ContextT, P], Coro[T]], /) -> Command[CogT, P, T]: - ... - - @overload - def __call__(self, func: Callable[Concatenate[ContextT, P], Coro[T]], /) -> Command[None, P, T]: - ... - - def __call__(self, func: Callable[..., Coro[T]], /) -> Any: - ... - - class _GroupDecorator: - @overload - def __call__(self, func: Callable[Concatenate[CogT, ContextT, P], Coro[T]], /) -> Group[CogT, P, T]: - ... - - @overload - def __call__(self, func: Callable[Concatenate[ContextT, P], Coro[T]], /) -> Group[None, P, T]: - ... - - def __call__(self, func: Callable[..., Coro[T]], /) -> Any: - ... - - -@overload -def command( - name: str = ..., - **attrs: Any, -) -> _CommandDecorator: - ... - - -@overload -def command( - name: str = ..., - cls: Type[CommandT] = ..., # type: ignore # previous overload handles case where cls is not set - **attrs: Any, -) -> Callable[ - [ - Union[ - Callable[Concatenate[ContextT, P], Coro[Any]], - Callable[Concatenate[CogT, ContextT, P], Coro[Any]], # type: ignore # CogT is used here to allow covariance - ] - ], - CommandT, -]: - ... - - -def command( - name: str = MISSING, - cls: Type[Command[Any, ..., Any]] = MISSING, - **attrs: Any, -) -> Any: - """A decorator that transforms a function into a :class:`.Command` - or if called with :func:`.group`, :class:`.Group`. - - By default the ``help`` attribute is received automatically from the - docstring of the function and is cleaned up with the use of - ``inspect.cleandoc``. If the docstring is ``bytes``, then it is decoded - into :class:`str` using utf-8 encoding. - - All checks added using the :func:`.check` & co. decorators are added into - the function. There is no way to supply your own checks through this - decorator. - - Parameters - ----------- - name: :class:`str` - The name to create the command with. By default this uses the - function name unchanged. - cls - The class to construct with. By default this is :class:`.Command`. - You usually do not change this. - attrs - Keyword arguments to pass into the construction of the class denoted - by ``cls``. - - Raises - ------- - TypeError - If the function is not a coroutine or is already a command. - """ - if cls is MISSING: - cls = Command - - def decorator(func): - if isinstance(func, Command): - raise TypeError('Callback is already a command.') - return cls(func, name=name, **attrs) - - return decorator - - -@overload -def group( - name: str = ..., - **attrs: Any, -) -> _GroupDecorator: - ... - - -@overload -def group( - name: str = ..., - cls: Type[GroupT] = ..., # type: ignore # previous overload handles case where cls is not set - **attrs: Any, -) -> Callable[ - [ - Union[ - Callable[Concatenate[CogT, ContextT, P], Coro[Any]], # type: ignore # CogT is used here to allow covariance - Callable[Concatenate[ContextT, P], Coro[Any]], - ] - ], - GroupT, -]: - ... - - -def group( - name: str = MISSING, - cls: Type[Group[Any, ..., Any]] = MISSING, - **attrs: Any, -) -> Any: - """A decorator that transforms a function into a :class:`.Group`. - - This is similar to the :func:`~discord.ext.commands.command` decorator but the ``cls`` - parameter is set to :class:`Group` by default. - - .. versionchanged:: 1.1 - The ``cls`` parameter can now be passed. - """ - if cls is MISSING: - cls = Group - - return command(name=name, cls=cls, **attrs) - - -def check(predicate: UserCheck[ContextT], /) -> Check[ContextT]: - r"""A decorator that adds a check to the :class:`.Command` or its - subclasses. These checks could be accessed via :attr:`.Command.checks`. - - These checks should be predicates that take in a single parameter taking - a :class:`.Context`. If the check returns a ``False``\-like value then - during invocation a :exc:`.CheckFailure` exception is raised and sent to - the :func:`.on_command_error` event. - - If an exception should be thrown in the predicate then it should be a - subclass of :exc:`.CommandError`. Any exception not subclassed from it - will be propagated while those subclassed will be sent to - :func:`.on_command_error`. - - A special attribute named ``predicate`` is bound to the value - returned by this decorator to retrieve the predicate passed to the - decorator. This allows the following introspection and chaining to be done: - - .. code-block:: python3 - - def owner_or_permissions(**perms): - original = commands.has_permissions(**perms).predicate - async def extended_check(ctx): - if ctx.guild is None: - return False - return ctx.guild.owner_id == ctx.author.id or await original(ctx) - return commands.check(extended_check) - - .. note:: - - The function returned by ``predicate`` is **always** a coroutine, - even if the original function was not a coroutine. - - .. versionchanged:: 1.3 - The ``predicate`` attribute was added. - - Examples - --------- - - Creating a basic check to see if the command invoker is you. - - .. code-block:: python3 - - def check_if_it_is_me(ctx): - return ctx.message.author.id == 85309593344815104 - - @bot.command() - @commands.check(check_if_it_is_me) - async def only_for_me(ctx): - await ctx.send('I know you!') - - Transforming common checks into its own decorator: - - .. code-block:: python3 - - def is_me(): - def predicate(ctx): - return ctx.message.author.id == 85309593344815104 - return commands.check(predicate) - - @bot.command() - @is_me() - async def only_me(ctx): - await ctx.send('Only you!') - - .. versionchanged:: 2.0 - - ``predicate`` parameter is now positional-only. - - Parameters - ----------- - predicate: Callable[[:class:`Context`], :class:`bool`] - The predicate to check if the command should be invoked. - """ - - def decorator(func: Union[Command[Any, ..., Any], CoroFunc]) -> Union[Command[Any, ..., Any], CoroFunc]: - if isinstance(func, Command): - func.checks.append(predicate) # type: ignore - else: - if not hasattr(func, '__commands_checks__'): - func.__commands_checks__ = [] - - func.__commands_checks__.append(predicate) - - return func - - if inspect.iscoroutinefunction(predicate): - decorator.predicate = predicate - else: - - @functools.wraps(predicate) - async def wrapper(ctx: ContextT): - return predicate(ctx) - - decorator.predicate = wrapper - - return decorator # type: ignore - - -def check_any(*checks: Check[ContextT]) -> Check[ContextT]: - r"""A :func:`check` that is added that checks if any of the checks passed - will pass, i.e. using logical OR. - - If all checks fail then :exc:`.CheckAnyFailure` is raised to signal the failure. - It inherits from :exc:`.CheckFailure`. - - .. note:: - - The ``predicate`` attribute for this function **is** a coroutine. - - .. versionadded:: 1.3 - - Parameters - ------------ - \*checks: Callable[[:class:`Context`], :class:`bool`] - An argument list of checks that have been decorated with - the :func:`check` decorator. - - Raises - ------- - TypeError - A check passed has not been decorated with the :func:`check` - decorator. - - Examples - --------- - - Creating a basic check to see if it's the bot owner or - the server owner: - - .. code-block:: python3 - - def is_guild_owner(): - def predicate(ctx): - return ctx.guild is not None and ctx.guild.owner_id == ctx.author.id - return commands.check(predicate) - - @bot.command() - @commands.check_any(commands.is_owner(), is_guild_owner()) - async def only_for_owners(ctx): - await ctx.send('Hello mister owner!') - """ - - unwrapped = [] - for wrapped in checks: - try: - pred = wrapped.predicate - except AttributeError: - raise TypeError(f'{wrapped!r} must be wrapped by commands.check decorator') from None - else: - unwrapped.append(pred) - - async def predicate(ctx: Context[BotT]) -> bool: - errors = [] - for func in unwrapped: - try: - value = await func(ctx) - except CheckFailure as e: - errors.append(e) - else: - if value: - return True - # if we're here, all checks failed - raise CheckAnyFailure(unwrapped, errors) - - return check(predicate) # type: ignore - - -def has_role(item: Union[int, str], /) -> Check[Any]: - """A :func:`.check` that is added that checks if the member invoking the - command has the role specified via the name or ID specified. - - If a string is specified, you must give the exact name of the role, including - caps and spelling. - - If an integer is specified, you must give the exact snowflake ID of the role. - - If the message is invoked in a private message context then the check will - return ``False``. - - This check raises one of two special exceptions, :exc:`.MissingRole` if the user - is missing a role, or :exc:`.NoPrivateMessage` if it is used in a private message. - Both inherit from :exc:`.CheckFailure`. - - .. versionchanged:: 1.1 - - Raise :exc:`.MissingRole` or :exc:`.NoPrivateMessage` - instead of generic :exc:`.CheckFailure` - - .. versionchanged:: 2.0 - - ``item`` parameter is now positional-only. - - Parameters - ----------- - item: Union[:class:`int`, :class:`str`] - The name or ID of the role to check. - """ - - def predicate(ctx: Context[BotT]) -> bool: - if ctx.guild is None: - raise NoPrivateMessage() - - # ctx.guild is None doesn't narrow ctx.author to Member - if isinstance(item, int): - role = discord.utils.get(ctx.author.roles, id=item) # type: ignore - else: - role = discord.utils.get(ctx.author.roles, name=item) # type: ignore - if role is None: - raise MissingRole(item) - return True - - return check(predicate) - - -def has_any_role(*items: Union[int, str]) -> Callable[[T], T]: - r"""A :func:`.check` that is added that checks if the member invoking the - command has **any** of the roles specified. This means that if they have - one out of the three roles specified, then this check will return `True`. - - Similar to :func:`.has_role`\, the names or IDs passed in must be exact. - - This check raises one of two special exceptions, :exc:`.MissingAnyRole` if the user - is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message. - Both inherit from :exc:`.CheckFailure`. - - .. versionchanged:: 1.1 - - Raise :exc:`.MissingAnyRole` or :exc:`.NoPrivateMessage` - instead of generic :exc:`.CheckFailure` - - Parameters - ----------- - items: List[Union[:class:`str`, :class:`int`]] - An argument list of names or IDs to check that the member has roles wise. - - Example - -------- - - .. code-block:: python3 - - @bot.command() - @commands.has_any_role('Library Devs', 'Moderators', 492212595072434186) - async def cool(ctx): - await ctx.send('You are cool indeed') - """ - - def predicate(ctx): - if ctx.guild is None: - raise NoPrivateMessage() - - # ctx.guild is None doesn't narrow ctx.author to Member - getter = functools.partial(discord.utils.get, ctx.author.roles) - if any(getter(id=item) is not None if isinstance(item, int) else getter(name=item) is not None for item in items): - return True - raise MissingAnyRole(list(items)) - - return check(predicate) - - -def bot_has_role(item: int, /) -> Callable[[T], T]: - """Similar to :func:`.has_role` except checks if the bot itself has the - role. - - This check raises one of two special exceptions, :exc:`.BotMissingRole` if the bot - is missing the role, or :exc:`.NoPrivateMessage` if it is used in a private message. - Both inherit from :exc:`.CheckFailure`. - - .. versionchanged:: 1.1 - - Raise :exc:`.BotMissingRole` or :exc:`.NoPrivateMessage` - instead of generic :exc:`.CheckFailure` - - .. versionchanged:: 2.0 - - ``item`` parameter is now positional-only. - """ - - def predicate(ctx): - if ctx.guild is None: - raise NoPrivateMessage() - - me = ctx.me - if isinstance(item, int): - role = discord.utils.get(me.roles, id=item) - else: - role = discord.utils.get(me.roles, name=item) - if role is None: - raise BotMissingRole(item) - return True - - return check(predicate) - - -def bot_has_any_role(*items: int) -> Callable[[T], T]: - """Similar to :func:`.has_any_role` except checks if the bot itself has - any of the roles listed. - - This check raises one of two special exceptions, :exc:`.BotMissingAnyRole` if the bot - is missing all roles, or :exc:`.NoPrivateMessage` if it is used in a private message. - Both inherit from :exc:`.CheckFailure`. - - .. versionchanged:: 1.1 - - Raise :exc:`.BotMissingAnyRole` or :exc:`.NoPrivateMessage` - instead of generic checkfailure - """ - - def predicate(ctx): - if ctx.guild is None: - raise NoPrivateMessage() - - me = ctx.me - getter = functools.partial(discord.utils.get, me.roles) - if any(getter(id=item) is not None if isinstance(item, int) else getter(name=item) is not None for item in items): - return True - raise BotMissingAnyRole(list(items)) - - return check(predicate) - - -def has_permissions(**perms: bool) -> Check[Any]: - """A :func:`.check` that is added that checks if the member has all of - the permissions necessary. - - Note that this check operates on the current channel permissions, not the - guild wide permissions. - - The permissions passed in must be exactly like the properties shown under - :class:`.discord.Permissions`. - - This check raises a special exception, :exc:`.MissingPermissions` - that is inherited from :exc:`.CheckFailure`. - - Parameters - ------------ - perms - An argument list of permissions to check for. - - Example - --------- - - .. code-block:: python3 - - @bot.command() - @commands.has_permissions(manage_messages=True) - async def test(ctx): - await ctx.send('You can manage messages.') - - """ - - invalid = set(perms) - set(discord.Permissions.VALID_FLAGS) - if invalid: - raise TypeError(f"Invalid permission(s): {', '.join(invalid)}") - - def predicate(ctx: Context[BotT]) -> bool: - permissions = ctx.permissions - - missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value] - - if not missing: - return True - - raise MissingPermissions(missing) - - return check(predicate) - - -def bot_has_permissions(**perms: bool) -> Check[Any]: - """Similar to :func:`.has_permissions` except checks if the bot itself has - the permissions listed. - - This check raises a special exception, :exc:`.BotMissingPermissions` - that is inherited from :exc:`.CheckFailure`. - """ - - invalid = set(perms) - set(discord.Permissions.VALID_FLAGS) - if invalid: - raise TypeError(f"Invalid permission(s): {', '.join(invalid)}") - - def predicate(ctx: Context[BotT]) -> bool: - permissions = ctx.bot_permissions - - missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value] - - if not missing: - return True - - raise BotMissingPermissions(missing) - - return check(predicate) - - -def has_guild_permissions(**perms: bool) -> Check[Any]: - """Similar to :func:`.has_permissions`, but operates on guild wide - permissions instead of the current channel permissions. - - If this check is called in a DM context, it will raise an - exception, :exc:`.NoPrivateMessage`. - - .. versionadded:: 1.3 - """ - - invalid = set(perms) - set(discord.Permissions.VALID_FLAGS) - if invalid: - raise TypeError(f"Invalid permission(s): {', '.join(invalid)}") - - def predicate(ctx: Context[BotT]) -> bool: - if not ctx.guild: - raise NoPrivateMessage - - permissions = ctx.author.guild_permissions # type: ignore - missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value] - - if not missing: - return True - - raise MissingPermissions(missing) - - return check(predicate) - - -def bot_has_guild_permissions(**perms: bool) -> Check[Any]: - """Similar to :func:`.has_guild_permissions`, but checks the bot - members guild permissions. - - .. versionadded:: 1.3 - """ - - invalid = set(perms) - set(discord.Permissions.VALID_FLAGS) - if invalid: - raise TypeError(f"Invalid permission(s): {', '.join(invalid)}") - - def predicate(ctx: Context[BotT]) -> bool: - if not ctx.guild: - raise NoPrivateMessage - - permissions = ctx.me.guild_permissions # type: ignore - missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value] - - if not missing: - return True - - raise BotMissingPermissions(missing) - - return check(predicate) - - -def dm_only() -> Check[Any]: - """A :func:`.check` that indicates this command must only be used in a - DM context. Only private messages are allowed when - using the command. - - This check raises a special exception, :exc:`.PrivateMessageOnly` - that is inherited from :exc:`.CheckFailure`. - - .. versionadded:: 1.1 - """ - - def predicate(ctx: Context[BotT]) -> bool: - if ctx.guild is not None: - raise PrivateMessageOnly() - return True - - return check(predicate) - - -def guild_only() -> Check[Any]: - """A :func:`.check` that indicates this command must only be used in a - guild context only. Basically, no private messages are allowed when - using the command. - - This check raises a special exception, :exc:`.NoPrivateMessage` - that is inherited from :exc:`.CheckFailure`. - - If used on hybrid commands, this will be equivalent to the - :func:`discord.app_commands.guild_only` decorator. In an unsupported - context, such as a subcommand, this will still fallback to applying the - check. - """ - - # Due to implementation quirks, this check has to be re-implemented completely - # to work with both app_commands and the command framework. - - def predicate(ctx: Context[BotT]) -> bool: - if ctx.guild is None: - raise NoPrivateMessage() - return True - - def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]: - if isinstance(func, Command): - func.checks.append(predicate) - if hasattr(func, '__commands_is_hybrid__'): - app_command = getattr(func, 'app_command', None) - if app_command: - app_command.guild_only = True - else: - if not hasattr(func, '__commands_checks__'): - func.__commands_checks__ = [] - - func.__commands_checks__.append(predicate) - func.__discord_app_commands_guild_only__ = True - - return func - - if inspect.iscoroutinefunction(predicate): - decorator.predicate = predicate - else: - - @functools.wraps(predicate) - async def wrapper(ctx: Context[BotT]): - return predicate(ctx) - - decorator.predicate = wrapper - - return decorator # type: ignore - - -def is_owner() -> Check[Any]: - """A :func:`.check` that checks if the person invoking this command is the - owner of the bot. - - This is powered by :meth:`.Bot.is_owner`. - - This check raises a special exception, :exc:`.NotOwner` that is derived - from :exc:`.CheckFailure`. - """ - - async def predicate(ctx: Context[BotT]) -> bool: - if not await ctx.bot.is_owner(ctx.author): - raise NotOwner('You do not own this bot.') - return True - - return check(predicate) - - -def is_nsfw() -> Check[Any]: - """A :func:`.check` that checks if the channel is a NSFW channel. - - This check raises a special exception, :exc:`.NSFWChannelRequired` - that is derived from :exc:`.CheckFailure`. - - If used on hybrid commands, this will be equivalent to setting the - application command's ``nsfw`` attribute to ``True``. In an unsupported - context, such as a subcommand, this will still fallback to applying the - check. - - .. versionchanged:: 1.1 - - Raise :exc:`.NSFWChannelRequired` instead of generic :exc:`.CheckFailure`. - DM channels will also now pass this check. - """ - - # Due to implementation quirks, this check has to be re-implemented completely - # to work with both app_commands and the command framework. - - def predicate(ctx: Context[BotT]) -> bool: - ch = ctx.channel - if ctx.guild is None or ( - isinstance(ch, (discord.TextChannel, discord.Thread, discord.VoiceChannel)) and ch.is_nsfw() - ): - return True - raise NSFWChannelRequired(ch) # type: ignore - - def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]: - if isinstance(func, Command): - func.checks.append(predicate) - if hasattr(func, '__commands_is_hybrid__'): - app_command = getattr(func, 'app_command', None) - if app_command: - app_command.nsfw = True - else: - if not hasattr(func, '__commands_checks__'): - func.__commands_checks__ = [] - - func.__commands_checks__.append(predicate) - func.__discord_app_commands_is_nsfw__ = True - - return func - - if inspect.iscoroutinefunction(predicate): - decorator.predicate = predicate - else: - - @functools.wraps(predicate) - async def wrapper(ctx: Context[BotT]): - return predicate(ctx) - - decorator.predicate = wrapper - - return decorator # type: ignore - - -def cooldown( - rate: int, - per: float, - type: Union[BucketType, Callable[[Context[Any]], Any]] = BucketType.default, -) -> Callable[[T], T]: - """A decorator that adds a cooldown to a :class:`.Command` - - A cooldown allows a command to only be used a specific amount - of times in a specific time frame. These cooldowns can be based - either on a per-guild, per-channel, per-user, per-role or global basis. - Denoted by the third argument of ``type`` which must be of enum - type :class:`.BucketType`. - - If a cooldown is triggered, then :exc:`.CommandOnCooldown` is triggered in - :func:`.on_command_error` and the local error handler. - - A command can only have a single cooldown. - - Parameters - ------------ - rate: :class:`int` - The number of times a command can be used before triggering a cooldown. - per: :class:`float` - The amount of seconds to wait for a cooldown when it's been triggered. - type: Union[:class:`.BucketType`, Callable[[:class:`.Context`], Any]] - The type of cooldown to have. If callable, should return a key for the mapping. - - .. versionchanged:: 1.7 - Callables are now supported for custom bucket types. - """ - - def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]: - if isinstance(func, Command): - func._buckets = CooldownMapping(Cooldown(rate, per), type) - else: - func.__commands_cooldown__ = CooldownMapping(Cooldown(rate, per), type) - return func - - return decorator # type: ignore - - -def dynamic_cooldown( - cooldown: Callable[[Context[Any]], Optional[Cooldown]], - type: Union[BucketType, Callable[[Context[Any]], Any]], -) -> Callable[[T], T]: - """A decorator that adds a dynamic cooldown to a :class:`.Command` - - This differs from :func:`.cooldown` in that it takes a function that - accepts a single parameter of type :class:`.Context` and must - return a :class:`~discord.app_commands.Cooldown` or ``None``. - If ``None`` is returned then that cooldown is effectively bypassed. - - A cooldown allows a command to only be used a specific amount - of times in a specific time frame. These cooldowns can be based - either on a per-guild, per-channel, per-user, per-role or global basis. - Denoted by the third argument of ``type`` which must be of enum - type :class:`.BucketType`. - - If a cooldown is triggered, then :exc:`.CommandOnCooldown` is triggered in - :func:`.on_command_error` and the local error handler. - - A command can only have a single cooldown. - - .. versionadded:: 2.0 - - Parameters - ------------ - cooldown: Callable[[:class:`.Context`], Optional[:class:`~discord.app_commands.Cooldown`]] - A function that takes a message and returns a cooldown that will - apply to this invocation or ``None`` if the cooldown should be bypassed. - type: :class:`.BucketType` - The type of cooldown to have. - """ - if not callable(cooldown): - raise TypeError("A callable must be provided") - - if type is BucketType.default: - raise ValueError('BucketType.default cannot be used in dynamic cooldowns') - - def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]: - if isinstance(func, Command): - func._buckets = DynamicCooldownMapping(cooldown, type) - else: - func.__commands_cooldown__ = DynamicCooldownMapping(cooldown, type) - return func - - return decorator # type: ignore - - -def max_concurrency(number: int, per: BucketType = BucketType.default, *, wait: bool = False) -> Callable[[T], T]: - """A decorator that adds a maximum concurrency to a :class:`.Command` or its subclasses. - - This enables you to only allow a certain number of command invocations at the same time, - for example if a command takes too long or if only one user can use it at a time. This - differs from a cooldown in that there is no set waiting period or token bucket -- only - a set number of people can run the command. - - .. versionadded:: 1.3 - - Parameters - ------------- - number: :class:`int` - The maximum number of invocations of this command that can be running at the same time. - per: :class:`.BucketType` - The bucket that this concurrency is based on, e.g. ``BucketType.guild`` would allow - it to be used up to ``number`` times per guild. - wait: :class:`bool` - Whether the command should wait for the queue to be over. If this is set to ``False`` - then instead of waiting until the command can run again, the command raises - :exc:`.MaxConcurrencyReached` to its error handler. If this is set to ``True`` - then the command waits until it can be executed. - """ - - def decorator(func: Union[Command, CoroFunc]) -> Union[Command, CoroFunc]: - value = MaxConcurrency(number, per=per, wait=wait) - if isinstance(func, Command): - func._max_concurrency = value - else: - func.__commands_max_concurrency__ = value - return func - - return decorator # type: ignore - - -def before_invoke(coro: Hook[CogT, ContextT], /) -> Callable[[T], T]: - """A decorator that registers a coroutine as a pre-invoke hook. - - This allows you to refer to one before invoke hook for several commands that - do not have to be within the same cog. - - .. versionadded:: 1.4 - - .. versionchanged:: 2.0 - - ``coro`` parameter is now positional-only. - - Example - --------- - - .. code-block:: python3 - - async def record_usage(ctx): - print(ctx.author, 'used', ctx.command, 'at', ctx.message.created_at) - - @bot.command() - @commands.before_invoke(record_usage) - async def who(ctx): # Output: used who at