diff -Nru python-aiohttp-3.1.3/aiohttp/abc.py python-aiohttp-3.5.1/aiohttp/abc.py --- python-aiohttp-3.1.3/aiohttp/abc.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/abc.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,14 +1,34 @@ import asyncio +import logging from abc import ABC, abstractmethod -from collections.abc import Iterable, Sized +from collections.abc import Sized +from http.cookies import BaseCookie, Morsel # noqa +from typing import (TYPE_CHECKING, Any, Awaitable, Callable, Dict, Generator, + Iterable, List, Optional, Tuple) + +from multidict import CIMultiDict # noqa +from yarl import URL + +from .helpers import get_running_loop +from .typedefs import LooseCookies + + +if TYPE_CHECKING: # pragma: no cover + from .web_request import BaseRequest, Request + from .web_response import StreamResponse + from .web_app import Application + from .web_exceptions import HTTPException +else: + BaseRequest = Request = Application = StreamResponse = None + HTTPException = None class AbstractRouter(ABC): - def __init__(self): + def __init__(self) -> None: self._frozen = False - def post_init(self, app): + def post_init(self, app: Application) -> None: """Post init stage. Not an abstract method for sake of backward compatibility, @@ -17,40 +37,42 @@ """ @property - def frozen(self): + def frozen(self) -> bool: return self._frozen - def freeze(self): + def freeze(self) -> None: """Freeze router.""" self._frozen = True @abstractmethod - async def resolve(self, request): + async def resolve(self, request: Request) -> 'AbstractMatchInfo': """Return MATCH_INFO for given request""" class AbstractMatchInfo(ABC): + @property # pragma: no branch @abstractmethod - async def handler(self, request): + def handler(self) -> Callable[[Request], Awaitable[StreamResponse]]: """Execute matched request handler""" + @property @abstractmethod - async def expect_handler(self, request): + def expect_handler(self) -> Callable[[Request], Awaitable[None]]: """Expect handler for 100-continue processing""" @property # pragma: no branch @abstractmethod - def http_exception(self): + def http_exception(self) -> Optional[HTTPException]: """HTTPException instance raised on router's resolving, or None""" @abstractmethod # pragma: no branch - def get_info(self): + def get_info(self) -> Dict[str, Any]: """Return a dict with additional info useful for introspection""" @property # pragma: no branch @abstractmethod - def apps(self): + def apps(self) -> Tuple[Application, ...]: """Stack of nested applications. Top level application is left-most element. @@ -58,11 +80,11 @@ """ @abstractmethod - def add_app(self, app): + def add_app(self, app: Application) -> None: """Add application to the nested apps stack.""" @abstractmethod - def freeze(self): + def freeze(self) -> None: """Freeze the match info. The method is called after route resolution. @@ -75,16 +97,16 @@ class AbstractView(ABC): """Abstract class based view.""" - def __init__(self, request): + def __init__(self, request: Request) -> None: self._request = request @property - def request(self): + def request(self) -> Request: """Request instance.""" return self._request @abstractmethod - def __await__(self): + def __await__(self) -> Generator[Any, None, StreamResponse]: """Execute the view handler.""" @@ -92,56 +114,86 @@ """Abstract DNS resolver.""" @abstractmethod - async def resolve(self, hostname): + 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): + async def close(self) -> None: """Release resolver""" -class AbstractCookieJar(Sized, Iterable): +if TYPE_CHECKING: # pragma: no cover + IterableBase = Iterable[Morsel[str]] +else: + IterableBase = Iterable + + +class AbstractCookieJar(Sized, IterableBase): """Abstract Cookie Jar.""" - def __init__(self, *, loop=None): - self._loop = loop or asyncio.get_event_loop() + def __init__(self, *, + loop: Optional[asyncio.AbstractEventLoop]=None) -> None: + self._loop = get_running_loop(loop) @abstractmethod - def clear(self): + def clear(self) -> None: """Clear all cookies.""" @abstractmethod - def update_cookies(self, cookies, response_url=None): + def update_cookies(self, + cookies: LooseCookies, + response_url: URL=URL()) -> None: """Update cookies.""" @abstractmethod - def filter_cookies(self, request_url): + 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): + async def write(self, chunk: bytes) -> None: """Write chunk into stream.""" @abstractmethod - async def write_eof(self, chunk=b''): + async def write_eof(self, chunk: bytes=b'') -> None: """Write last chunk.""" @abstractmethod - async def drain(self): + 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, log_format): + def __init__(self, logger: logging.Logger, log_format: str) -> None: self.logger = logger self.log_format = log_format @abstractmethod - def log(self, request, response, time): + def log(self, + request: BaseRequest, + response: StreamResponse, + time: float) -> None: """Emit log to logger.""" diff -Nru python-aiohttp-3.1.3/aiohttp/base_protocol.py python-aiohttp-3.5.1/aiohttp/base_protocol.py --- python-aiohttp-3.1.3/aiohttp/base_protocol.py 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/base_protocol.py 2018-12-24 20:58:54.000000000 +0000 @@ -0,0 +1,81 @@ +import asyncio +from typing import Optional, cast + +from .tcp_helpers import tcp_nodelay + + +class BaseProtocol(asyncio.Protocol): + __slots__ = ('_loop', '_paused', '_drain_waiter', + '_connection_lost', '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 + assert waiter is None or waiter.cancelled() + waiter = self._loop.create_future() + self._drain_waiter = waiter + await waiter diff -Nru python-aiohttp-3.1.3/aiohttp/client_exceptions.py python-aiohttp-3.5.1/aiohttp/client_exceptions.py --- python-aiohttp-3.1.3/aiohttp/client_exceptions.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/client_exceptions.py 2018-12-24 20:58:54.000000000 +0000 @@ -2,12 +2,23 @@ import asyncio import warnings +from typing import TYPE_CHECKING, Any, Optional, Tuple, Union + +from .typedefs import _CIMultiDict try: import ssl + SSLContext = ssl.SSLContext except ImportError: # pragma: no cover - ssl = None + ssl = SSLContext = None # type: ignore + + +if TYPE_CHECKING: # pragma: no cover + from .client_reqrep import (RequestInfo, ClientResponse, ConnectionKey, # noqa + Fingerprint) +else: + RequestInfo = ClientResponse = ConnectionKey = None __all__ = ( @@ -38,8 +49,12 @@ request_info: instance of RequestInfo """ - def __init__(self, request_info, history, *, - code=None, status=None, message='', headers=None): + def __init__(self, request_info: RequestInfo, + history: Tuple[ClientResponse, ...], *, + code: Optional[int]=None, + status: Optional[int]=None, + message: str='', + headers: Optional[_CIMultiDict]=None) -> None: self.request_info = request_info if code is not None: if status is not None: @@ -62,14 +77,14 @@ super().__init__("%s, message='%s'" % (self.status, message)) @property - def code(self): + 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): + def code(self, value: int) -> None: warnings.warn("code property is deprecated, use status instead", DeprecationWarning, stacklevel=2) @@ -93,6 +108,10 @@ """ +class TooManyRedirects(ClientResponseError): + """Client was redirected too many times.""" + + class ClientConnectionError(ClientError): """Base class for client socket errors.""" @@ -107,28 +126,29 @@ Raised in :class:`aiohttp.connector.TCPConnector` if connection to proxy can not be established. """ - def __init__(self, connection_key, os_error): + 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) @property - def os_error(self): + def os_error(self) -> OSError: return self._os_error @property - def host(self): + def host(self) -> str: return self._conn_key.host @property - def port(self): + def port(self) -> Optional[int]: return self._conn_key.port @property - def ssl(self): + def ssl(self) -> Union[SSLContext, None, bool, 'Fingerprint']: return self._conn_key.ssl - def __str__(self): + def __str__(self) -> str: return ('Cannot connect to host {0.host}:{0.port} ssl:{0.ssl} [{1}]' .format(self, self.strerror)) @@ -148,7 +168,7 @@ class ServerDisconnectedError(ServerConnectionError): """Server disconnected.""" - def __init__(self, message=None): + def __init__(self, message: Optional[str]=None) -> None: self.message = message @@ -159,13 +179,14 @@ class ServerFingerprintMismatch(ServerConnectionError): """SSL certificate does not match expected fingerprint.""" - def __init__(self, expected, got, host, port): + def __init__(self, expected: bytes, got: bytes, + host: str, port: int) -> None: self.expected = expected self.got = got self.host = host self.port = port - def __repr__(self): + def __repr__(self) -> str: return '<{} expected={} got={} host={} port={}>'.format( self.__class__.__name__, self.expected, self.got, self.host, self.port) @@ -183,14 +204,16 @@ # Derive from ValueError for backward compatibility - def __init__(self, url): + 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): + def url(self) -> Any: return self.args[0] - def __repr__(self): + def __repr__(self) -> str: return '<{} {}>'.format(self.__class__.__name__, self.url) @@ -199,47 +222,48 @@ if ssl is not None: - certificate_errors = (ssl.CertificateError,) - certificate_errors_bases = (ClientSSLError, ssl.CertificateError,) + cert_errors = (ssl.CertificateError,) + cert_errors_bases = (ClientSSLError, ssl.CertificateError,) ssl_errors = (ssl.SSLError,) ssl_error_bases = (ClientSSLError, ssl.SSLError) else: # pragma: no cover - certificate_errors = tuple() - certificate_errors_bases = (ClientSSLError, ValueError,) + cert_errors = tuple() + cert_errors_bases = (ClientSSLError, ValueError,) ssl_errors = tuple() ssl_error_bases = (ClientSSLError,) -class ClientConnectorSSLError(*ssl_error_bases): +class ClientConnectorSSLError(*ssl_error_bases): # type: ignore """Response ssl error.""" -class ClientConnectorCertificateError(*certificate_errors_bases): +class ClientConnectorCertificateError(*cert_errors_bases): # type: ignore """Response certificate error.""" - def __init__(self, connection_key, certificate_error): + def __init__(self, connection_key: + ConnectionKey, certificate_error: Exception) -> None: self._conn_key = connection_key self._certificate_error = certificate_error @property - def certificate_error(self): + def certificate_error(self) -> Exception: return self._certificate_error @property - def host(self): + def host(self) -> str: return self._conn_key.host @property - def port(self): + def port(self) -> Optional[int]: return self._conn_key.port @property - def ssl(self): - return self._conn_key.ssl + def ssl(self) -> bool: + return self._conn_key.is_ssl - def __str__(self): + 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 -Nru python-aiohttp-3.1.3/aiohttp/client_proto.py python-aiohttp-3.5.1/aiohttp/client_proto.py --- python-aiohttp-3.1.3/aiohttp/client_proto.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/client_proto.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,41 +1,45 @@ import asyncio -import asyncio.streams from contextlib import suppress +from typing import Any, Optional, Tuple +from .base_protocol import BaseProtocol from .client_exceptions import (ClientOSError, ClientPayloadError, - ServerDisconnectedError) -from .http import HttpResponseParser -from .streams import EMPTY_PAYLOAD, DataQueue + ServerDisconnectedError, ServerTimeoutError) +from .helpers import BaseTimerContext +from .http import HttpResponseParser, RawResponseMessage +from .streams import EMPTY_PAYLOAD, DataQueue, StreamReader -class ResponseHandler(DataQueue, asyncio.streams.FlowControlMixin): +class ResponseHandler(BaseProtocol, + DataQueue[Tuple[RawResponseMessage, StreamReader]]): """Helper class to adapt between Protocol and StreamReader.""" - def __init__(self, *, loop=None): - asyncio.streams.FlowControlMixin.__init__(self, loop=loop) - DataQueue.__init__(self, loop=loop) + def __init__(self, + loop: asyncio.AbstractEventLoop) -> None: + BaseProtocol.__init__(self, loop=loop) + DataQueue.__init__(self, loop) - self.transport = None self._should_close = False - self._message = None self._payload = None self._skip_payload = False self._payload_parser = None - self._reading_paused = False self._timer = None self._tail = b'' self._upgraded = False - self._parser = None + 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): + def upgraded(self) -> bool: return self._upgraded @property - def should_close(self): + def should_close(self) -> bool: if (self._payload is not None and not self._payload.is_eof() or self._upgraded): return True @@ -43,34 +47,38 @@ return (self._should_close or self._upgraded or self.exception() is not None or self._payload_parser is not None or - len(self) or self._tail) + len(self) > 0 or bool(self._tail)) + + def force_close(self) -> None: + self._should_close = True - def close(self): + def close(self) -> None: transport = self.transport if transport is not None: transport.close() self.transport = None self._payload = None - return transport + self._drop_timeout() - def is_connected(self): + def is_connected(self) -> bool: return self.transport is not None - def connection_made(self, transport): - self.transport = transport + def connection_lost(self, exc: Optional[BaseException]) -> None: + self._drop_timeout() - def connection_lost(self, exc): if self._payload_parser is not None: with suppress(Exception): self._payload_parser.feed_eof() - try: - uncompleted = self._parser.feed_eof() - except Exception: - uncompleted = None - if self._payload is not None: - self._payload.set_exception( - ClientPayloadError('Response payload is not completed')) + 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): @@ -81,52 +89,56 @@ # we do it anyway below self.set_exception(exc) - self.transport = None self._should_close = True self._parser = None - self._message = None self._payload = None self._payload_parser = None self._reading_paused = False super().connection_lost(exc) - def eof_received(self): - pass - - def pause_reading(self): - if not self._reading_paused: - try: - self.transport.pause_reading() - except (AttributeError, NotImplementedError, RuntimeError): - pass - self._reading_paused = True + 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 resume_reading(self): - if self._reading_paused: - try: - self.transport.resume_reading() - except (AttributeError, NotImplementedError, RuntimeError): - pass - self._reading_paused = False - - def set_exception(self, exc): + def set_exception(self, exc: BaseException) -> None: self._should_close = True + self._drop_timeout() super().set_exception(exc) - def set_parser(self, parser, payload): + 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=None, - skip_payload=False, - read_until_eof=False, - auto_decompress=True): + def set_response_params(self, *, timer: BaseTimerContext=None, + skip_payload: bool=False, + read_until_eof: bool=False, + auto_decompress: bool=True, + read_timeout: Optional[float]=None) -> None: self._skip_payload = skip_payload + + self._read_timeout = read_timeout + self._reschedule_timeout() + self._parser = HttpResponseParser( self, self._loop, timer=timer, payload_exception=ClientPayloadError, @@ -137,7 +149,29 @@ data, self._tail = self._tail, b'' self.data_received(data) - def data_received(self, 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: if not data: return @@ -160,24 +194,37 @@ try: messages, upgraded, tail = self._parser.feed_data(data) except BaseException as exc: - self.transport.close() + 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 = None for message, payload in messages: if message.should_close: self._should_close = True - self._message = message self._payload = payload if self._skip_payload or message.code in (204, 304): - self.feed_data((message, EMPTY_PAYLOAD), 0) + self.feed_data((message, EMPTY_PAYLOAD), 0) # type: ignore # noqa 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: diff -Nru python-aiohttp-3.1.3/aiohttp/client.py python-aiohttp-3.5.1/aiohttp/client.py --- python-aiohttp-3.1.3/aiohttp/client.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/client.py 2018-12-24 20:58:54.000000000 +0000 @@ -8,40 +8,78 @@ import sys import traceback import warnings -from collections.abc import Coroutine +from types import SimpleNamespace, TracebackType +from typing import (Any, Coroutine, Generator, Generic, Iterable, List, # noqa + Mapping, Optional, Set, Tuple, Type, TypeVar, Union) +import attr from multidict import CIMultiDict, MultiDict, MultiDictProxy, istr from yarl import URL from . import client_exceptions, client_reqrep from . import connector as connector_mod from . import hdrs, http, payload +from .abc import AbstractCookieJar from .client_exceptions import * # noqa from .client_exceptions import (ClientError, ClientOSError, InvalidURL, - ServerTimeoutError, WSServerHandshakeError) + ServerTimeoutError, TooManyRedirects, + WSServerHandshakeError) from .client_reqrep import * # noqa -from .client_reqrep import ClientRequest, ClientResponse, _merge_ssl_params +from .client_reqrep import (ClientRequest, ClientResponse, Fingerprint, + _merge_ssl_params) from .client_ws import ClientWebSocketResponse from .connector import * # noqa -from .connector import TCPConnector +from .connector import BaseConnector, TCPConnector from .cookiejar import CookieJar -from .helpers import (DEBUG, PY_36, CeilTimeout, TimeoutHandle, - proxies_from_env, sentinel, strip_auth_from_url) -from .http import WS_KEY, WebSocketReader, WebSocketWriter -from .http_websocket import WSHandshakeError, ws_ext_gen, ws_ext_parse +from .helpers import (DEBUG, PY_36, BasicAuth, CeilTimeout, TimeoutHandle, + get_running_loop, proxies_from_env, sentinel, + strip_auth_from_url) +from .http import WS_KEY, HttpVersion, WebSocketReader, WebSocketWriter +from .http_websocket import (WSHandshakeError, WSMessage, ws_ext_gen, # noqa + ws_ext_parse) from .streams import FlowControlDataQueue -from .tcp_helpers import tcp_cork, tcp_nodelay -from .tracing import Trace +from .tracing import Trace, TraceConfig +from .typedefs import JSONEncoder, LooseCookies, LooseHeaders, StrOrURL __all__ = (client_exceptions.__all__ + # noqa client_reqrep.__all__ + # noqa connector_mod.__all__ + # noqa - ('ClientSession', 'ClientWebSocketResponse', 'request')) + ('ClientSession', 'ClientTimeout', + 'ClientWebSocketResponse', 'request')) -# 5 Minute default read and connect timeout -DEFAULT_TIMEOUT = 5 * 60 +try: + from ssl import SSLContext +except ImportError: # pragma: no cover + SSLContext = object # type: ignore + + +@attr.s(frozen=True, slots=True) +class ClientTimeout: + total = attr.ib(type=float, default=None) + connect = attr.ib(type=float, default=None) + sock_read = attr.ib(type=float, default=None) + sock_connect = attr.ib(type=float, default=None) + + # pool_queue_timeout = attr.ib(type=float, default=None) + # dns_resolution_timeout = attr.ib(type=float, default=None) + # socket_connect_timeout = attr.ib(type=float, default=None) + # connection_acquiring_timeout = attr.ib(type=float, default=None) + # new_connection_timeout = attr.ib(type=float, default=None) + # http_header_timeout = attr.ib(type=float, default=None) + # response_body_timeout = attr.ib(type=float, default=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 = ClientTimeout(total=5*60) + +_RetType = TypeVar('_RetType') class ClientSession: @@ -51,8 +89,9 @@ '_source_traceback', '_connector', 'requote_redirect_url', '_loop', '_cookie_jar', '_connector_owner', '_default_auth', - '_version', '_json_serialize', '_read_timeout', - '_conn_timeout', '_raise_for_status', '_auto_decompress', + '_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']) @@ -60,26 +99,33 @@ _source_traceback = None _connector = None - requote_redirect_url = True - - def __init__(self, *, connector=None, loop=None, cookies=None, - headers=None, skip_auto_headers=None, - auth=None, json_serialize=json.dumps, - request_class=ClientRequest, response_class=ClientResponse, - ws_response_class=ClientWebSocketResponse, - version=http.HttpVersion11, - cookie_jar=None, connector_owner=True, raise_for_status=False, - read_timeout=sentinel, conn_timeout=None, - auto_decompress=True, trust_env=False, - trace_configs=None): + def __init__(self, *, connector: Optional[BaseConnector]=None, + loop: Optional[asyncio.AbstractEventLoop]=None, + cookies: Optional[LooseCookies]=None, + headers: 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, # noqa + 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) -> None: - implicit_loop = False if loop is None: if connector is not None: loop = connector._loop - else: - implicit_loop = True - loop = asyncio.get_event_loop() + + loop = get_running_loop(loop) if connector is None: connector = TCPConnector(loop=loop) @@ -93,17 +139,6 @@ if loop.get_debug(): self._source_traceback = traceback.extract_stack(sys._getframe(1)) - if implicit_loop and not loop.is_running(): - warnings.warn("Creating a client session outside of coroutine is " - "a very dangerous idea", - stacklevel=2) - context = {'client_session': self, - 'message': 'Creating a client session outside ' - 'of coroutine'} - if self._source_traceback is not None: - context['source_traceback'] = self._source_traceback - loop.call_exception_handler(context) - if cookie_jar is None: cookie_jar = CookieJar(loop=loop) self._cookie_jar = cookie_jar @@ -111,17 +146,40 @@ if cookies is not None: self._cookie_jar.update_cookies(cookies) - self._connector = connector + self._connector = connector # type: BaseConnector self._connector_owner = connector_owner self._default_auth = auth self._version = version self._json_serialize = json_serialize - self._read_timeout = (read_timeout if read_timeout is not sentinel - else DEFAULT_TIMEOUT) - self._conn_timeout = conn_timeout + 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 + 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 # Convert to list of tuples if headers: @@ -143,14 +201,14 @@ for trace_config in self._trace_configs: trace_config.freeze() - def __init_subclass__(cls): + 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, val): + def __setattr__(self, name: str, val: Any) -> None: if name not in self.ATTRS: warnings.warn("Setting custom ClientSession.{} attribute " "is discouraged".format(name), @@ -158,7 +216,7 @@ stacklevel=2) super().__setattr__(name, val) - def __del__(self, _warnings=warnings): + def __del__(self, _warnings: Any=warnings) -> None: if not self.closed: if PY_36: kwargs = {'source': self} @@ -173,32 +231,41 @@ context['source_traceback'] = self._source_traceback self._loop.call_exception_handler(context) - def request(self, method, url, **kwargs): + def request(self, + method: str, + url: StrOrURL, + **kwargs: Any) -> '_RequestContextManager': """Perform HTTP request.""" return _RequestContextManager(self._request(method, url, **kwargs)) - async def _request(self, method, url, *, - params=None, - data=None, - json=None, - headers=None, - skip_auto_headers=None, - auth=None, - allow_redirects=True, - max_redirects=10, - compress=None, - chunked=None, - expect100=False, - read_until_eof=True, - proxy=None, - proxy_auth=None, - timeout=sentinel, - verify_ssl=None, - fingerprint=None, - ssl_context=None, - ssl=None, - proxy_headers=None, - trace_request_ctx=None): + 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: 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 + ) -> 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 @@ -228,9 +295,9 @@ proxy_headers = self._prepare_headers(proxy_headers) try: - url = URL(url) + url = URL(str_or_url) except ValueError: - raise InvalidURL(url) + raise InvalidURL(str_or_url) skip_headers = set(self._skip_auto_headers) if skip_auto_headers is not None: @@ -243,11 +310,16 @@ except ValueError: raise InvalidURL(proxy) + if timeout is sentinel: + real_timeout = self._timeout # type: ClientTimeout + else: + if not isinstance(timeout, ClientTimeout): + real_timeout = ClientTimeout(total=timeout) # type: ignore + else: + real_timeout = timeout # timeout is cumulative for all request operations # (request, redirects, responses, data consuming) - tm = TimeoutHandle( - self._loop, - timeout if timeout is not sentinel else self._read_timeout) + tm = TimeoutHandle(self._loop, real_timeout.total) handle = tm.start() traces = [ @@ -289,8 +361,16 @@ "with AUTH argument or credentials " "encoded in URL") - url = url.with_fragment(None) - cookies = self._cookie_jar.filter_cookies(url) + session_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 session_cookies and req_cookies: + session_cookies.load(req_cookies) + + cookies = session_cookies if proxy is not None: proxy = URL(proxy) @@ -309,28 +389,39 @@ expect100=expect100, loop=self._loop, response_class=self._response_class, proxy=proxy, proxy_auth=proxy_auth, timer=timer, - session=self, auto_decompress=self._auto_decompress, + session=self, ssl=ssl, proxy_headers=proxy_headers, traces=traces) # connection timeout try: - with CeilTimeout(self._conn_timeout, loop=self._loop): + with CeilTimeout(real_timeout.connect, + loop=self._loop): + assert self._connector is not None conn = await self._connector.connect( req, - traces=traces + traces=traces, + timeout=real_timeout ) except asyncio.TimeoutError as exc: raise ServerTimeoutError( 'Connection timeout ' 'to host {0}'.format(url)) from exc - tcp_nodelay(conn.transport, True) - tcp_cork(conn.transport, False) + 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) + try: try: resp = await req.send(conn) try: - await resp.start(conn, read_until_eof) + await resp.start(conn) except BaseException: resp.close() raise @@ -360,9 +451,8 @@ history.append(resp) if max_redirects and redirects >= max_redirects: resp.close() - break - else: - resp.release() + 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 @@ -380,10 +470,14 @@ 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: r_url = URL( - r_url, encoded=not self.requote_redirect_url) + r_url, encoded=not self._requote_redirect_url) except ValueError: raise InvalidURL(r_url) @@ -408,7 +502,9 @@ break # check response status - if self._raise_for_status: + if raise_for_status is None: + raise_for_status = self._raise_for_status + if raise_for_status: resp.raise_for_status() # register connection @@ -445,27 +541,32 @@ ) raise - def ws_connect(self, url, *, - protocols=(), - timeout=10.0, - receive_timeout=None, - autoclose=True, - autoping=True, - heartbeat=None, - auth=None, - origin=None, - headers=None, - proxy=None, - proxy_auth=None, - ssl=None, - verify_ssl=None, - fingerprint=None, - ssl_context=None, - proxy_headers=None, - compress=0): + 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, + 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, @@ -482,29 +583,37 @@ fingerprint=fingerprint, ssl_context=ssl_context, proxy_headers=proxy_headers, - compress=compress)) + compress=compress, + max_msg_size=max_msg_size)) - async def _ws_connect(self, url, *, - protocols=(), - timeout=10.0, - receive_timeout=None, - autoclose=True, - autoping=True, - heartbeat=None, - auth=None, - origin=None, - headers=None, - proxy=None, - proxy_auth=None, - ssl=None, - verify_ssl=None, - fingerprint=None, - ssl_context=None, - proxy_headers=None, - compress=0): + 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, + 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: - headers = CIMultiDict() + real_headers = CIMultiDict() # type: CIMultiDict[str] + else: + real_headers = CIMultiDict(headers) default_headers = { hdrs.UPGRADE: hdrs.WEBSOCKET, @@ -513,30 +622,30 @@ } for key, value in default_headers.items(): - if key not in headers: - headers[key] = value + real_headers.setdefault(key, value) sec_key = base64.b64encode(os.urandom(16)) - headers[hdrs.SEC_WEBSOCKET_KEY] = sec_key.decode() + real_headers[hdrs.SEC_WEBSOCKET_KEY] = sec_key.decode() if protocols: - headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = ','.join(protocols) + real_headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = ','.join(protocols) if origin is not None: - headers[hdrs.ORIGIN] = origin + real_headers[hdrs.ORIGIN] = origin if compress: extstr = ws_ext_gen(compress=compress) - headers[hdrs.SEC_WEBSOCKET_EXTENSIONS] = extstr + real_headers[hdrs.SEC_WEBSOCKET_EXTENSIONS] = extstr ssl = _merge_ssl_params(ssl, verify_ssl, ssl_context, fingerprint) # send request - resp = await self.get(url, headers=headers, - read_until_eof=False, - auth=auth, - proxy=proxy, - proxy_auth=proxy_auth, - ssl=ssl, - proxy_headers=proxy_headers) + resp = await self.request(method, url, + headers=real_headers, + read_until_eof=False, + auth=auth, + proxy=proxy, + proxy_auth=proxy_auth, + ssl=ssl, + proxy_headers=proxy_headers) try: # check handshake @@ -606,12 +715,15 @@ compress = 0 notakeover = False - proto = resp.connection.protocol - transport = resp.connection.transport + conn = resp.connection + assert conn is not None + proto = conn.protocol + assert proto is not None + transport = conn.transport + assert transport is not None reader = FlowControlDataQueue( - proto, limit=2 ** 16, loop=self._loop) - proto.set_parser(WebSocketReader(reader), reader) - tcp_nodelay(transport, True) + proto, limit=2 ** 16, loop=self._loop) # type: FlowControlDataQueue[WSMessage] # noqa + proto.set_parser(WebSocketReader(reader, max_msg_size), reader) writer = WebSocketWriter( proto, transport, use_mask=True, compress=compress, notakeover=notakeover) @@ -632,7 +744,9 @@ compress=compress, client_notakeover=notakeover) - def _prepare_headers(self, headers): + def _prepare_headers( + self, + headers: Optional[LooseHeaders]) -> 'CIMultiDict[str]': """ Add default headers and transform it to CIMultiDict """ # Convert headers to MultiDict @@ -640,7 +754,7 @@ if headers: if not isinstance(headers, (MultiDictProxy, MultiDict)): headers = CIMultiDict(headers) - added_names = set() + added_names = set() # type: Set[str] for key, value in headers.items(): if key in added_names: result.add(key, value) @@ -649,66 +763,72 @@ added_names.add(key) return result - def get(self, url, *, allow_redirects=True, **kwargs): + 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, *, allow_redirects=True, **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, *, allow_redirects=False, **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, *, data=None, **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, *, data=None, **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, *, data=None, **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, **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): + async def close(self) -> None: """Close underlying connector. Release all acquired resources. """ if not self.closed: - if self._connector_owner: - self._connector.close() + if self._connector is not None and self._connector_owner: + await self._connector.close() self._connector = None @property - def closed(self): + def closed(self) -> bool: """Is client session closed. A readonly property. @@ -716,76 +836,108 @@ return self._connector is None or self._connector.closed @property - def connector(self): + def connector(self) -> Optional[BaseConnector]: """Connector instance used for the session.""" return self._connector @property - def cookie_jar(self): + def cookie_jar(self) -> AbstractCookieJar: """The session cookies.""" return self._cookie_jar @property - def version(self): + def version(self) -> Tuple[int, int]: """The session HTTP protocol version.""" return self._version @property - def loop(self): + 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 - def detach(self): + 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): + def __enter__(self) -> None: raise TypeError("Use async with instead") - def __exit__(self, exc_type, exc_val, exc_tb): + 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): + async def __aenter__(self) -> 'ClientSession': return self - async def __aexit__(self, exc_type, exc_val, exc_tb): + async def __aexit__(self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType]) -> None: await self.close() -class _BaseRequestContextManager(Coroutine): +class _BaseRequestContextManager(Coroutine[Any, + Any, + _RetType], + Generic[_RetType]): __slots__ = ('_coro', '_resp') - def __init__(self, coro): + def __init__( + self, + coro: Coroutine['asyncio.Future[Any]', None, _RetType] + ) -> None: self._coro = coro - def send(self, arg): + def send(self, arg: None) -> 'asyncio.Future[Any]': return self._coro.send(arg) - def throw(self, arg): - return self._coro.throw(arg) + def throw(self, arg: BaseException) -> None: # type: ignore + self._coro.throw(arg) # type: ignore - def close(self): + def close(self) -> None: return self._coro.close() - def __await__(self): + def __await__(self) -> Generator[Any, None, _RetType]: ret = self._coro.__await__() return ret - def __iter__(self): + def __iter__(self) -> Generator[Any, None, _RetType]: return self.__await__() - async def __aenter__(self): + async def __aenter__(self) -> _RetType: self._resp = await self._coro return self._resp -class _RequestContextManager(_BaseRequestContextManager): - async def __aexit__(self, exc_type, exc, tb): +class _RequestContextManager(_BaseRequestContextManager[ClientResponse]): + 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 @@ -794,8 +946,12 @@ self._resp.release() -class _WSRequestContextManager(_BaseRequestContextManager): - async def __aexit__(self, exc_type, exc, tb): +class _WSRequestContextManager(_BaseRequestContextManager[ + ClientWebSocketResponse]): + async def __aexit__(self, + exc_type: Optional[Type[BaseException]], + exc: Optional[BaseException], + tb: Optional[TracebackType]) -> None: await self._resp.close() @@ -803,39 +959,50 @@ __slots__ = ('_coro', '_resp', '_session') - def __init__(self, coro, session): + def __init__(self, + coro: Coroutine['asyncio.Future[Any]', None, ClientResponse], + session: ClientSession) -> None: self._coro = coro - self._resp = None + self._resp = None # type: Optional[ClientResponse] self._session = session - async def __aenter__(self): + async def __aenter__(self) -> ClientResponse: self._resp = await self._coro return self._resp - async def __aexit__(self, exc_type, exc_val, exc_tb): + 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, url, *, - params=None, - data=None, - json=None, - headers=None, - skip_auto_headers=None, - cookies=None, - auth=None, - allow_redirects=True, - max_redirects=10, - version=http.HttpVersion11, - compress=None, - chunked=None, - expect100=False, - connector=None, - loop=None, - read_until_eof=True, - proxy=None, - proxy_auth=None): +def request( + method: str, + url: StrOrURL, *, + params: Optional[Mapping[str, str]]=None, + data: Any=None, + json: Any=None, + headers: 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, + loop: Optional[asyncio.AbstractEventLoop]=None +) -> _SessionRequestContextManager: """Constructs and sends a request. Returns response object. method - HTTP method url - request url @@ -843,7 +1010,7 @@ 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 compatibile python object + 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 @@ -861,6 +1028,8 @@ 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/') @@ -874,7 +1043,7 @@ connector = TCPConnector(loop=loop, force_close=True) session = ClientSession( - loop=loop, cookies=cookies, version=version, + loop=loop, cookies=cookies, version=version, timeout=timeout, connector=connector, connector_owner=connector_owner) return _SessionRequestContextManager( @@ -890,6 +1059,7 @@ compress=compress, chunked=chunked, expect100=expect100, + raise_for_status=raise_for_status, read_until_eof=read_until_eof, proxy=proxy, proxy_auth=proxy_auth,), diff -Nru python-aiohttp-3.1.3/aiohttp/client_reqrep.py python-aiohttp-3.5.1/aiohttp/client_reqrep.py --- python-aiohttp-3.1.3/aiohttp/client_reqrep.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/client_reqrep.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,34 +1,41 @@ import asyncio import codecs import io -import json import re import sys import traceback import warnings -from collections import namedtuple from hashlib import md5, sha1, sha256 from http.cookies import CookieError, Morsel, SimpleCookie -from types import MappingProxyType +from types import MappingProxyType, TracebackType +from typing import (TYPE_CHECKING, Any, Dict, Iterable, List, Mapping, # noqa + 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, HeadersMixin, TimerNoop, noop, reify, set_result +from .helpers import (PY_36, BaseTimerContext, BasicAuth, HeadersMixin, # noqa + TimerNoop, noop, reify, set_result) from .http import SERVER_SOFTWARE, HttpVersion10, HttpVersion11, StreamWriter from .log import client_logger +from .streams import StreamReader # noqa +from .typedefs import (DEFAULT_JSON_DECODER, JSONDecoder, LooseCookies, + LooseHeaders, RawHeaders) try: import ssl + from ssl import SSLContext except ImportError: # pragma: no cover - ssl = None + ssl = None # type: ignore + SSLContext = object # type: ignore try: import cchardet as chardet @@ -39,21 +46,32 @@ __all__ = ('ClientRequest', 'ClientResponse', 'RequestInfo', 'Fingerprint') -json_re = re.compile('^application/(?:[\w.+-]+?\+)?json') +if TYPE_CHECKING: # pragma: no cover + from .client import ClientSession # noqa + from .connector import Connection # noqa + from .tracing import Trace # noqa + + +json_re = re.compile(r'^application/(?:[\w.+-]+?\+)?json') @attr.s(frozen=True, slots=True) class ContentDisposition: - type = attr.ib(type=str) - parameters = attr.ib(type=MappingProxyType) - filename = attr.ib(type=str) + type = attr.ib(type=str) # type: Optional[str] + parameters = attr.ib(type=MappingProxyType) # type: MappingProxyType[str, str] # noqa + filename = attr.ib(type=str) # type: Optional[str] @attr.s(frozen=True, slots=True) class RequestInfo: url = attr.ib(type=URL) method = attr.ib(type=str) - headers = attr.ib(type=CIMultiDictProxy) + headers = attr.ib(type=CIMultiDictProxy) # type: CIMultiDictProxy[str] + real_url = attr.ib(type=URL) + + @real_url.default + def real_url_default(self) -> URL: + return self.url class Fingerprint: @@ -63,7 +81,7 @@ 32: sha256, } - def __init__(self, fingerprint): + def __init__(self, fingerprint: bytes) -> None: digestlen = len(fingerprint) hashfunc = self.HASHFUNC_BY_DIGESTLEN.get(digestlen) if not hashfunc: @@ -75,10 +93,10 @@ self._fingerprint = fingerprint @property - def fingerprint(self): + def fingerprint(self) -> bytes: return self._fingerprint - def check(self, transport): + def check(self, transport: asyncio.Transport) -> None: if not transport.get_extra_info('sslcontext'): return sslobj = transport.get_extra_info('ssl_object') @@ -96,7 +114,12 @@ SSL_ALLOWED_TYPES = type(None) -def _merge_ssl_params(ssl, verify_ssl, ssl_context, fingerprint): +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, @@ -131,12 +154,23 @@ return ssl -ConnectionKey = namedtuple('ConnectionKey', ['host', 'port', 'ssl']) +@attr.s(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 = attr.ib(type=str) + port = attr.ib(type=int) # type: Optional[int] + is_ssl = attr.ib(type=bool) + ssl = attr.ib() # type: Union[SSLContext, None, bool, Fingerprint] + proxy = attr.ib() # type: Optional[URL] + proxy_auth = attr.ib() # type: Optional[BasicAuth] + proxy_headers_hash = attr.ib(type=int) # type: Optional[int] # noqa # hash(CIMultiDict) -def _is_expected_content_type(response_content_type, expected_content_type): +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) + return json_re.match(response_content_type) is not None return expected_content_type in response_content_type @@ -168,39 +202,53 @@ # 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, url, *, - params=None, headers=None, skip_auto_headers=frozenset(), - data=None, cookies=None, - auth=None, version=http.HttpVersion11, compress=None, - chunked=None, expect100=False, - loop=None, response_class=None, - proxy=None, proxy_auth=None, - timer=None, session=None, auto_decompress=True, - ssl=None, - proxy_headers=None, - traces=None): + 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 - self._session = session + # 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.url = url.with_fragment(None) 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 - self.response_class = response_class or ClientResponse + 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._auto_decompress = auto_decompress self._ssl = ssl if loop.get_debug(): @@ -223,30 +271,41 @@ traces = [] self._traces = traces - def is_ssl(self): + def is_ssl(self) -> bool: return self.url.scheme in ('https', 'wss') @property - def ssl(self): + def ssl(self) -> Union['SSLContext', None, bool, Fingerprint]: return self._ssl @property - def connection_key(self): - return ConnectionKey(self.host, self.port, self.is_ssl()) + 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] # noqa + else: + h = None + return ConnectionKey(self.host, self.port, self.is_ssl(), + self.ssl, + self.proxy, self.proxy_auth, h) @property - def host(self): - return self.url.host + def host(self) -> str: + ret = self.url.host + assert ret is not None + return ret @property - def port(self): + def port(self) -> Optional[int]: return self.url.port @property - def request_info(self): - return RequestInfo(self.url, self.method, self.headers) + 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): + def update_host(self, url: URL) -> None: """Update destination host, port and connection type (ssl).""" # get host/port if not url.host: @@ -257,7 +316,7 @@ if username: self.auth = helpers.BasicAuth(username, password or '') - def update_version(self, version): + def update_version(self, version: Union[http.HttpVersion, str]) -> None: """Convert request version to two elements tuple. parser HTTP version '1.1' => (1, 1) @@ -265,44 +324,50 @@ if isinstance(version, str): v = [l.strip() for l in version.split('.', 1)] try: - version = int(v[0]), int(v[1]) + version = http.HttpVersion(int(v[0]), int(v[1])) except ValueError: raise ValueError( 'Can not parse http version number: {}' .format(version)) from None self.version = version - def update_headers(self, headers): + def update_headers(self, headers: Optional[LooseHeaders]) -> None: """Update request headers.""" - self.headers = CIMultiDict() + self.headers = CIMultiDict() # type: CIMultiDict[str] + + # add host + netloc = cast(str, self.url.raw_host) + if helpers.is_ipv6_address(netloc): + netloc = '[{}]'.format(netloc) + if 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() + headers = headers.items() # type: ignore for key, value in headers: - self.headers.add(key, value) + # 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): + 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) + used_headers.extend(self.skip_auto_headers) # type: ignore for hdr, val in self.DEFAULT_HEADERS.items(): if hdr not in used_headers: self.headers.add(hdr, val) - # add host - if hdrs.HOST not in used_headers: - netloc = self.url.raw_host - if not self.url.is_default_port(): - netloc += ':' + str(self.url.port) - self.headers[hdrs.HOST] = netloc - if hdrs.USER_AGENT not in used_headers: self.headers[hdrs.USER_AGENT] = SERVER_SOFTWARE - def update_cookies(self, cookies): + def update_cookies(self, cookies: Optional[LooseCookies]) -> None: """Update request cookies header.""" if not cookies: return @@ -312,18 +377,22 @@ c.load(self.headers.get(hdrs.COOKIE, '')) del self.headers[hdrs.COOKIE] - for name, value in cookies.items(): + if isinstance(cookies, Mapping): + iter_cookies = cookies.items() + else: + iter_cookies = cookies # type: ignore + 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) + mrsl_val.set(value.key, value.value, value.coded_value) # type: ignore # noqa c[name] = mrsl_val else: - c[name] = value + c[name] = value # type: ignore self.headers[hdrs.COOKIE] = c.output(header='', sep=';').strip() - def update_content_encoding(self, data): + def update_content_encoding(self, data: Any) -> None: """Set request content encoding.""" if not data: return @@ -340,7 +409,7 @@ self.headers[hdrs.CONTENT_ENCODING] = self.compress self.chunked = True # enable chunked, no need to deal with length - def update_transfer_encoding(self): + def update_transfer_encoding(self) -> None: """Analyze transfer-encoding header.""" te = self.headers.get(hdrs.TRANSFER_ENCODING, '').lower() @@ -361,7 +430,7 @@ if hdrs.CONTENT_LENGTH not in self.headers: self.headers[hdrs.CONTENT_LENGTH] = str(len(self.body)) - def update_auth(self, auth): + def update_auth(self, auth: Optional[BasicAuth]) -> None: """Set basic auth.""" if auth is None: auth = self.auth @@ -373,7 +442,7 @@ self.headers[hdrs.AUTHORIZATION] = auth.encode() - def update_body_from_data(self, body): + def update_body_from_data(self, body: Any) -> None: if not body: return @@ -409,7 +478,7 @@ if key not in self.headers: self.headers[key] = value - def update_expect_continue(self, expect=False): + 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': @@ -418,7 +487,9 @@ if expect: self._continue = self.loop.create_future() - def update_proxy(self, proxy, proxy_auth, proxy_headers): + def update_proxy(self, proxy: Optional[URL], + proxy_auth: Optional[BasicAuth], + proxy_headers: Optional[LooseHeaders]) -> None: if proxy and not proxy.scheme == 'http': raise ValueError("Only http proxies are supported") if proxy_auth and not isinstance(proxy_auth, helpers.BasicAuth): @@ -427,7 +498,7 @@ self.proxy_auth = proxy_auth self.proxy_headers = proxy_headers - def keep_alive(self): + def keep_alive(self) -> bool: if self.version < HttpVersion10: # keep alive not supported at all return False @@ -441,22 +512,25 @@ return True - async def write_bytes(self, writer, conn): + 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,) + self.body = (self.body,) # type: ignore for chunk in self.body: - await writer.write(chunk) + await writer.write(chunk) # type: ignore await writer.write_eof() except OSError as exc: @@ -465,16 +539,16 @@ 'Can not write request body for %s' % self.url) new_exc.__context__ = exc new_exc.__cause__ = exc - conn.protocol.set_exception(new_exc) + protocol.set_exception(new_exc) except asyncio.CancelledError as exc: if not conn.closed: - conn.protocol.set_exception(exc) + protocol.set_exception(exc) except Exception as exc: - conn.protocol.set_exception(exc) + protocol.set_exception(exc) finally: self._writer = None - async def send(self, conn): + 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 @@ -488,8 +562,10 @@ if self.url.raw_query_string: path += '?' + self.url.raw_query_string + protocol = conn.protocol + assert protocol is not None writer = StreamWriter( - conn.protocol, conn.transport, self.loop, + protocol, self.loop, on_chunk_sent=self._on_chunk_request_sent ) @@ -519,37 +595,38 @@ self.headers[hdrs.CONNECTION] = connection # status + headers - status_line = '{0} {1} HTTP/{2[0]}.{2[1]}\r\n'.format( + 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)) - self.response = self.response_class( + 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, - auto_decompress=self._auto_decompress, traces=self._traces, loop=self.loop, session=self._session ) return self.response - async def close(self): + async def close(self) -> None: if self._writer is not None: try: await self._writer finally: self._writer = None - def terminate(self): + 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, chunk): + async def _on_chunk_request_sent(self, chunk: bytes) -> None: for trace in self._traces: await trace.send_request_chunk_sent(chunk) @@ -558,79 +635,92 @@ # from the Status-Line of the response version = None # HTTP-Version - status = None # Status-Code + status = None # type: int # Status-Code reason = None # Reason-Phrase - content = None # Payload stream - headers = None # Response headers, CIMultiDictProxy - raw_headers = None # Response raw headers, a sequence of pairs + 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 - _reader = None # input stream _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, url, *, - writer, continue100, timer, - request_info, auto_decompress, - traces, loop, session): + 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.headers = None self.cookies = SimpleCookie() - self._url = url - self._body = None - self._writer = writer + 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 = () + self._history = () # type: Tuple[ClientResponse, ...] self._request_info = request_info self._timer = timer if timer is not None else TimerNoop() - self._auto_decompress = auto_decompress # True by default - self._cache = {} # required for @reify method decorator + self._cache = {} # type: Dict[str, Any] self._traces = traces self._loop = loop - self._session = session # store a reference to session #1985 + # 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)) - @property - def url(self): + @reify + def url(self) -> URL: return self._url - @property - def url_obj(self): + @reify + def url_obj(self) -> URL: warnings.warn( "Deprecated, use .url #1654", DeprecationWarning, stacklevel=2) return self._url - @property - def host(self): + @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 - @property - def _headers(self): - return self.headers + @reify + def headers(self) -> 'CIMultiDictProxy[str]': + return self._headers - @property - def request_info(self): + @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): + def content_disposition(self) -> Optional[ContentDisposition]: raw = self._headers.get(hdrs.CONTENT_DISPOSITION) if raw is None: return None - disposition_type, params = multipart.parse_content_disposition(raw) - params = MappingProxyType(params) + 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=warnings): + def __del__(self, _warnings: Any=warnings) -> None: if self._closed: return @@ -652,7 +742,7 @@ context['source_traceback'] = self._source_traceback self._loop.call_exception_handler(context) - def __repr__(self): + def __repr__(self) -> str: out = io.StringIO() ascii_encodable_url = str(self.url) if self.reason: @@ -668,31 +758,64 @@ return out.getvalue() @property - def connection(self): + def connection(self) -> Optional['Connection']: return self._connection - @property - def history(self): + @reify + def history(self) -> Tuple['ClientResponse', ...]: """A sequence of of responses, if redirects occurred.""" return self._history - async def start(self, connection, read_until_eof=False): + @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 + + 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 - connection.protocol.set_response_params( - timer=self._timer, - skip_payload=self.method.lower() == 'head', - read_until_eof=read_until_eof, - auto_decompress=self._auto_decompress) - with self._timer: while True: # read response try: - (message, payload) = await self._protocol.read() + message, payload = await self._protocol.read() # type: ignore # noqa except http.HttpProcessingError as exc: raise ClientResponseError( self.request_info, self.history, @@ -716,8 +839,8 @@ self.reason = message.reason # headers - self.headers = CIMultiDictProxy(message.headers) - self.raw_headers = tuple(message.raw_headers) + self._headers = message.headers # type is CIMultiDictProxy + self._raw_headers = message.raw_headers # type is Tuple[bytes, bytes] # payload self.content = payload @@ -731,7 +854,7 @@ 'Can not load response cookies: %s', exc) return self - def _response_eof(self): + def _response_eof(self) -> None: if self._closed: return @@ -749,10 +872,12 @@ self._cleanup_writer() @property - def closed(self): + def closed(self) -> bool: return self._closed - def close(self): + def close(self) -> None: + if not self._released: + self._notify_content() if self._closed: return @@ -764,9 +889,10 @@ self._connection.close() self._connection = None self._cleanup_writer() - self._notify_content() - def release(self): + def release(self) -> Any: + if not self._released: + self._notify_content() if self._closed: return noop() @@ -776,11 +902,12 @@ self._connection = None self._cleanup_writer() - self._notify_content() return noop() - def raise_for_status(self): + def raise_for_status(self) -> None: if 400 <= self.status: + assert self.reason # always not None for started response + self.release() raise ClientResponseError( self.request_info, self.history, @@ -788,19 +915,20 @@ message=self.reason, headers=self.headers) - def _cleanup_writer(self): + def _cleanup_writer(self) -> None: if self._writer is not None: self._writer.cancel() self._writer = None self._session = None - def _notify_content(self): + def _notify_content(self) -> None: content = self.content - if content and content.exception() is None and not content.is_eof(): + if content and content.exception() is None: content.set_exception( ClientConnectionError('Connection closed')) + self._released = True - async def wait_for_close(self): + async def wait_for_close(self) -> None: if self._writer is not None: try: await self._writer @@ -808,7 +936,7 @@ self._writer = None self.release() - async def read(self): + async def read(self) -> bytes: """Read response payload.""" if self._body is None: try: @@ -818,10 +946,12 @@ except BaseException: self.close() raise + elif self._released: + raise ClientConnectionError('Connection closed') return self._body - def get_encoding(self): + def get_encoding(self) -> str: ctype = self.headers.get(hdrs.CONTENT_TYPE, '').lower() mimetype = helpers.parse_mimetype(ctype) @@ -842,7 +972,8 @@ return encoding - async def text(self, encoding=None, errors='strict'): + 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() @@ -850,10 +981,11 @@ if encoding is None: encoding = self.get_encoding() - return self._body.decode(encoding, errors=errors) + return self._body.decode(encoding, errors=errors) # type: ignore - async def json(self, *, encoding=None, loads=json.loads, - content_type='application/json'): + async def json(self, *, encoding: 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() @@ -868,7 +1000,7 @@ 'unexpected mimetype: %s' % ctype), headers=self.headers) - stripped = self._body.strip() + stripped = self._body.strip() # type: ignore if not stripped: return None @@ -877,10 +1009,13 @@ return loads(stripped.decode(encoding)) - async def __aenter__(self): + async def __aenter__(self) -> 'ClientResponse': return self - async def __aexit__(self, exc_type, exc_val, exc_tb): + 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 closes connection # is state is broken diff -Nru python-aiohttp-3.1.3/aiohttp/client_ws.py python-aiohttp-3.5.1/aiohttp/client_ws.py --- python-aiohttp-3.1.3/aiohttp/client_ws.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/client_ws.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,23 +1,37 @@ """WebSocket client for asyncio.""" import asyncio -import json +from typing import Any, Optional 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, WSMessage, WSMsgType) -from .streams import EofStream +from .http_websocket import WebSocketWriter # WSMessage +from .streams import EofStream, FlowControlDataQueue # noqa +from .typedefs import (DEFAULT_JSON_DECODER, DEFAULT_JSON_ENCODER, JSONDecoder, + JSONEncoder) class ClientWebSocketResponse: - def __init__(self, reader, writer, protocol, - response, timeout, autoclose, autoping, loop, *, - receive_timeout=None, heartbeat=None, - compress=0, client_notakeover=False): + 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 @@ -26,7 +40,7 @@ self._protocol = protocol self._closed = False self._closing = False - self._close_code = None + self._close_code = None # type: Optional[int] self._timeout = timeout self._receive_timeout = receive_timeout self._autoclose = autoclose @@ -37,14 +51,14 @@ self._pong_heartbeat = heartbeat / 2.0 self._pong_response_cb = None self._loop = loop - self._waiting = None - self._exception = None + 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): + def _cancel_heartbeat(self) -> None: if self._pong_response_cb is not None: self._pong_response_cb.cancel() self._pong_response_cb = None @@ -53,14 +67,14 @@ self._heartbeat_cb.cancel() self._heartbeat_cb = None - def _reset_heartbeat(self): + 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): + 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 @@ -72,7 +86,7 @@ self._pong_response_cb = call_later( self._pong_not_received, self._pong_heartbeat, self._loop) - def _pong_not_received(self): + def _pong_not_received(self) -> None: if not self._closed: self._closed = True self._close_code = 1006 @@ -80,57 +94,63 @@ self._response.close() @property - def closed(self): + def closed(self) -> bool: return self._closed @property - def close_code(self): + def close_code(self) -> Optional[int]: return self._close_code @property - def protocol(self): + def protocol(self) -> Optional[str]: return self._protocol @property - def compress(self): + def compress(self) -> int: return self._compress @property - def client_notakeover(self): + def client_notakeover(self) -> bool: return self._client_notakeover - def get_extra_info(self, name, default=None): + def get_extra_info(self, name: str, default: Any=None) -> Any: """extra info from connection transport""" - try: - return self._response.connection.transport.get_extra_info( - name, default) - except Exception: + 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): + def exception(self) -> Optional[BaseException]: return self._exception - async def ping(self, message='b'): + async def ping(self, message: bytes=b'') -> None: await self._writer.ping(message) - async def pong(self, message='b'): + async def pong(self, message: bytes=b'') -> None: await self._writer.pong(message) - async def send_str(self, data, compress=None): + 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, compress=None): + 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, compress=None, *, dumps=json.dumps): + 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=1000, message=b''): + async def close(self, *, code: int=1000, 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: @@ -177,7 +197,7 @@ else: return False - async def receive(self, timeout=None): + async def receive(self, timeout: Optional[float]=None) -> WSMessage: while True: if self._waiting is not None: raise RuntimeError( @@ -238,7 +258,7 @@ return msg - async def receive_str(self, *, timeout=None): + async def receive_str(self, *, timeout: Optional[float]=None) -> str: msg = await self.receive(timeout) if msg.type != WSMsgType.TEXT: raise TypeError( @@ -246,7 +266,7 @@ msg.data)) return msg.data - async def receive_bytes(self, *, timeout=None): + async def receive_bytes(self, *, timeout: Optional[float]=None) -> bytes: msg = await self.receive(timeout) if msg.type != WSMsgType.BINARY: raise TypeError( @@ -254,14 +274,16 @@ msg.data)) return msg.data - async def receive_json(self, *, loads=json.loads, timeout=None): + 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): + def __aiter__(self) -> 'ClientWebSocketResponse': return self - async def __anext__(self): + async def __anext__(self) -> WSMessage: msg = await self.receive() if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, diff -Nru python-aiohttp-3.1.3/aiohttp/connector.py python-aiohttp-3.5.1/aiohttp/connector.py --- python-aiohttp-3.1.3/aiohttp/connector.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/connector.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,57 +1,96 @@ import asyncio import functools +import random import sys import traceback import warnings -from collections import defaultdict +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, # noqa + 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, certificate_errors, + ServerFingerprintMismatch, cert_errors, ssl_errors) from .client_proto import ResponseHandler from .client_reqrep import ClientRequest, Fingerprint, _merge_ssl_params -from .helpers import PY_36, is_ip_address, noop, sentinel +from .helpers import (PY_36, CeilTimeout, get_running_loop, is_ip_address, + noop2, 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 + ssl = None # type: ignore + SSLContext = object # type: ignore __all__ = ('BaseConnector', 'TCPConnector', 'UnixConnector') +if TYPE_CHECKING: # pragma: no cover + from .client import ClientTimeout # noqa + from .client_reqrep import ConnectionKey # noqa + from .tracing import Trace # noqa + + +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, key, protocol, loop): + 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 - self._callbacks = [] + 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): + def __repr__(self) -> str: return 'Connection<{}>'.format(self._key) - def __del__(self, _warnings=warnings): + def __del__(self, _warnings: Any=warnings) -> None: if self._protocol is not None: if PY_36: kwargs = {'source': self} @@ -73,33 +112,34 @@ self._loop.call_exception_handler(context) @property - def loop(self): + def loop(self) -> asyncio.AbstractEventLoop: + warnings.warn("connector.loop property is deprecated", + DeprecationWarning, + stacklevel=2) return self._loop @property - def transport(self): + def transport(self) -> Optional[asyncio.Transport]: + if self._protocol is None: + return None return self._protocol.transport @property - def protocol(self): + def protocol(self) -> Optional[ResponseHandler]: return self._protocol - @property - def writer(self): - return self._protocol.writer - - def add_callback(self, callback): + def add_callback(self, callback: Callable[[], None]) -> None: if callback is not None: self._callbacks.append(callback) - def _notify_release(self): + def _notify_release(self) -> None: callbacks, self._callbacks = self._callbacks[:], [] for cb in callbacks: with suppress(Exception): cb() - def close(self): + def close(self) -> None: self._notify_release() if self._protocol is not None: @@ -107,7 +147,7 @@ self._key, self._protocol, should_close=True) self._protocol = None - def release(self): + def release(self) -> None: self._notify_release() if self._protocol is not None: @@ -116,22 +156,15 @@ should_close=self._protocol.should_close) self._protocol = None - def detach(self): - self._notify_release() - - if self._protocol is not None: - self._connector._release_acquired(self._protocol) - self._protocol = None - @property - def closed(self): + 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): + def close(self) -> None: pass @@ -154,9 +187,12 @@ # abort transport after 2 seconds (cleanup broken connections) _cleanup_closed_period = 2.0 - def __init__(self, *, keepalive_timeout=sentinel, - force_close=False, limit=100, limit_per_host=0, - enable_cleanup_closed=False, loop=None): + 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 \ @@ -167,21 +203,22 @@ if keepalive_timeout is sentinel: keepalive_timeout = 15.0 - if loop is None: - loop = asyncio.get_event_loop() + loop = get_running_loop(loop) self._closed = False if loop.get_debug(): self._source_traceback = traceback.extract_stack(sys._getframe(1)) - self._conns = {} + self._conns = {} # type: Dict[ConnectionKey, List[Tuple[ResponseHandler, float]]] # noqa self._limit = limit self._limit_per_host = limit_per_host - self._acquired = set() - self._acquired_per_host = defaultdict(set) - self._keepalive_timeout = keepalive_timeout + self._acquired = set() # type: Set[ResponseHandler] + self._acquired_per_host = defaultdict(set) # type: DefaultDict[ConnectionKey, Set[ResponseHandler]] # noqa + self._keepalive_timeout = cast(float, keepalive_timeout) self._force_close = force_close - self._waiters = defaultdict(list) + + # {host_key: FIFO list of waiters} + self._waiters = defaultdict(deque) # type: ignore self._loop = loop self._factory = functools.partial(ResponseHandler, loop=loop) @@ -194,10 +231,10 @@ # start cleanup closed transports task self._cleanup_closed_handle = None self._cleanup_closed_disabled = not enable_cleanup_closed - self._cleanup_closed_transports = [] + self._cleanup_closed_transports = [] # type: List[Optional[asyncio.Transport]] # noqa self._cleanup_closed() - def __del__(self, _warnings=warnings): + def __del__(self, _warnings: Any=warnings) -> None: if self._closed: return if not self._conns: @@ -205,7 +242,7 @@ conns = [repr(c) for c in self._conns.values()] - self.close() + self._close() if PY_36: kwargs = {'source': self} @@ -221,19 +258,32 @@ context['source_traceback'] = self._source_traceback self._loop.call_exception_handler(context) - def __enter__(self): + def __enter__(self) -> 'BaseConnector': + warnings.warn('"witn Connector():" is deprecated, ' + 'use "async with Connector():" instead', + DeprecationWarning) return self - def __exit__(self, *exc): + 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): + def force_close(self) -> bool: """Ultimately close connection on releasing if True.""" return self._force_close @property - def limit(self): + def limit(self) -> int: """The total number for simultaneous connections. If limit is 0 the connector has no limit. @@ -242,7 +292,7 @@ return self._limit @property - def limit_per_host(self): + def limit_per_host(self) -> int: """The limit_per_host for simultaneous connections to the same endpoint. @@ -252,7 +302,7 @@ """ return self._limit_per_host - def _cleanup(self): + def _cleanup(self) -> None: """Cleanup unused transports.""" if self._cleanup_handle: self._cleanup_handle.cancel() @@ -268,8 +318,10 @@ for proto, use_time in conns: if proto.is_connected(): if use_time - deadline < 0: - transport = proto.close() - if key[-1] and not self._cleanup_closed_disabled: + transport = proto.transport + proto.close() + if (key.is_ssl and + not self._cleanup_closed_disabled): self._cleanup_closed_transports.append( transport) else: @@ -284,7 +336,8 @@ self._cleanup_handle = helpers.weakref_handle( self, '_cleanup', timeout, self._loop) - def _drop_acquired_per_host(self, key, val): + 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 @@ -293,7 +346,7 @@ if not conns: del self._acquired_per_host[key] - def _cleanup_closed(self): + def _cleanup_closed(self) -> None: """Double confirmation for transport close. Some broken ssl servers may leave socket open without proper close. """ @@ -311,8 +364,12 @@ self, '_cleanup_closed', self._cleanup_closed_period, self._loop) - def close(self): + def close(self) -> Awaitable[None]: """Close all opened transports.""" + self._close() + return _DeprecationWaiter(noop2()) + + def _close(self) -> None: if self._closed: return @@ -320,7 +377,7 @@ try: if self._loop.is_closed(): - return noop() + return # cancel cleanup task if self._cleanup_handle: @@ -350,16 +407,21 @@ self._cleanup_closed_handle = None @property - def closed(self): + def closed(self) -> bool: """Is connector closed. A readonly property. """ return self._closed - async def connect(self, req, traces=None): - """Get from pool or create new connection.""" - key = req.connection_key + def _available_connections(self, key: 'ConnectionKey') -> int: + """ + Return number of available connections taking into account + the limit, limit_per_host and the connection key. + + If it returns less than 1 means that there is no connections + availables. + """ if self._limit: # total calc available connections @@ -368,16 +430,27 @@ # check limit per host if (self._limit_per_host and available > 0 and key in self._acquired_per_host): - available = self._limit_per_host - len( - self._acquired_per_host.get(key)) + 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 - available = self._limit_per_host - len( - self._acquired_per_host.get(key)) + 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. if available <= 0: fut = self._loop.create_future() @@ -392,11 +465,22 @@ try: await fut + except BaseException as e: + # remove a waiter even if it was cancelled, normally it's + # removed when it's notified + try: + waiters.remove(fut) + except ValueError: # fut may no longer be in list + pass + + raise e finally: - # remove a waiter even if it was cancelled - waiters.remove(fut) if not waiters: - del self._waiters[key] + try: + del self._waiters[key] + except KeyError: + # the key was evicted before. + pass if traces: for trace in traces: @@ -404,7 +488,7 @@ proto = self._get(key) if proto is None: - placeholder = _TransportPlaceholder() + placeholder = cast(ResponseHandler, _TransportPlaceholder()) self._acquired.add(placeholder) self._acquired_per_host[key].add(placeholder) @@ -413,22 +497,17 @@ await trace.send_connection_create_start() try: - proto = await self._create_connection( - req, - traces=traces - ) + proto = await self._create_connection(req, traces, timeout) if self._closed: proto.close() raise ClientConnectionError("Connector is closed.") except BaseException: - # signal to waiter - if key in self._waiters: - for waiter in self._waiters[key]: - if not waiter.done(): - waiter.set_result(None) - break + if not self._closed: + self._acquired.remove(placeholder) + self._drop_acquired_per_host(key, placeholder) + self._release_waiter() raise - finally: + else: if not self._closed: self._acquired.remove(placeholder) self._drop_acquired_per_host(key, placeholder) @@ -445,7 +524,7 @@ self._acquired_per_host[key].add(proto) return Connection(self, key, proto, self._loop) - def _get(self, key): + def _get(self, key: 'ConnectionKey') -> Optional[ResponseHandler]: try: conns = self._conns[key] except KeyError: @@ -456,9 +535,10 @@ proto, t0 = conns.pop() if proto.is_connected(): if t1 - t0 > self._keepalive_timeout: - transport = proto.close() + transport = proto.transport + proto.close() # only for SSL transports - if key[-1] and not self._cleanup_closed_disabled: + if key.is_ssl and not self._cleanup_closed_disabled: self._cleanup_closed_transports.append(transport) else: if not conns: @@ -470,28 +550,32 @@ del self._conns[key] return None - def _release_waiter(self): - # always release only one waiter + def _release_waiter(self) -> None: + """ + Iterates over all waiters till found one that is not finsihed and + belongs to a host that has available connections. + """ + if not self._waiters: + return - if self._limit: - # if we have limit and we have available - if self._limit - len(self._acquired) > 0: - for key, waiters in self._waiters.items(): - if waiters: - if not waiters[0].done(): - waiters[0].set_result(None) - break - - elif self._limit_per_host: - # if we have dont have limit but have limit per host - # then release first available - for key, waiters in self._waiters.items(): - if waiters: - if not waiters[0].done(): - waiters[0].set_result(None) - break + # Having the dict keys ordered this avoids to iterate + # at the same order at each call. + queues = list(self._waiters.keys()) + random.shuffle(queues) - def _release_acquired(self, key, proto): + 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 @@ -506,7 +590,8 @@ else: self._release_waiter() - def _release(self, key, protocol, *, should_close=False): + def _release(self, key: 'ConnectionKey', protocol: ResponseHandler, + *, should_close: bool=False) -> None: if self._closed: # acquired connection is already released on connector closing return @@ -517,9 +602,10 @@ should_close = True if should_close or protocol.should_close: - transport = protocol.close() + transport = protocol.transport + protocol.close() - if key[-1] and not self._cleanup_closed_disabled: + if key.is_ssl and not self._cleanup_closed_disabled: self._cleanup_closed_transports.append(transport) else: conns = self._conns.get(key) @@ -531,48 +617,50 @@ self._cleanup_handle = helpers.weakref_handle( self, '_cleanup', self._keepalive_timeout, self._loop) - async def _create_connection(self, req, traces=None): + async def _create_connection(self, req: 'ClientRequest', + traces: List['Trace'], + timeout: 'ClientTimeout') -> ResponseHandler: raise NotImplementedError() class _DNSCacheTable: - def __init__(self, ttl=None): - self._addrs_rr = {} - self._timestamps = {} + def __init__(self, ttl: Optional[float]=None) -> None: + self._addrs_rr = {} # type: Dict[Tuple[str, int], Tuple[Iterator[Dict[str, Any]], int]] # noqa + self._timestamps = {} # type: Dict[Tuple[str, int], float] self._ttl = ttl - def __contains__(self, host): + def __contains__(self, host: object) -> bool: return host in self._addrs_rr - def add(self, host, addrs): - self._addrs_rr[host] = (cycle(addrs), len(addrs)) + 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[host] = monotonic() + self._timestamps[key] = monotonic() - def remove(self, host): - self._addrs_rr.pop(host, None) + def remove(self, key: Tuple[str, int]) -> None: + self._addrs_rr.pop(key, None) if self._ttl: - self._timestamps.pop(host, None) + self._timestamps.pop(key, None) - def clear(self): + def clear(self) -> None: self._addrs_rr.clear() self._timestamps.clear() - def next_addrs(self, host): - loop, length = self._addrs_rr[host] + 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, host): + def expired(self, key: Tuple[str, int]) -> bool: if self._ttl is None: return False - return self._timestamps[host] + self._ttl < monotonic() + return self._timestamps[key] + self._ttl < monotonic() class TCPConnector(BaseConnector): @@ -600,12 +688,19 @@ loop - Optional event loop. """ - def __init__(self, *, verify_ssl=True, fingerprint=None, - use_dns_cache=True, ttl_dns_cache=10, - family=0, ssl_context=None, ssl=None, local_addr=None, - resolver=None, keepalive_timeout=sentinel, - force_close=False, limit=100, limit_per_host=0, - enable_cleanup_closed=False, loop=None): + def __init__(self, *, verify_ssl: bool=True, + fingerprint: Optional[bytes]=None, + use_dns_cache: bool=True, ttl_dns_cache: int=10, + family: int=0, + ssl_context: Optional[SSLContext]=None, + ssl: Union[None, bool, Fingerprint, SSLContext]=None, + local_addr: Optional[str]=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, @@ -620,28 +715,30 @@ self._use_dns_cache = use_dns_cache self._cached_hosts = _DNSCacheTable(ttl=ttl_dns_cache) - self._throttle_dns_events = {} + self._throttle_dns_events = {} # type: Dict[Tuple[str, int], EventResultOrError] # noqa self._family = family self._local_addr = local_addr - def close(self): + def close(self) -> Awaitable[None]: """Close all ongoing DNS calls.""" for ev in self._throttle_dns_events.values(): ev.cancel() - super().close() + return super().close() @property - def family(self): + def family(self) -> int: """Socket family like AF_INET.""" return self._family @property - def use_dns_cache(self): + def use_dns_cache(self) -> bool: """True if local DNS caching is enabled.""" return self._use_dns_cache - def clear_dns_cache(self, host=None, port=None): + 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)) @@ -651,7 +748,10 @@ else: self._cached_hosts.clear() - async def _resolve_host(self, host, port, traces=None): + 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}] @@ -717,27 +817,25 @@ return self._cached_hosts.next_addrs(key) - async def _create_connection(self, req, traces=None): + 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=traces - ) + req, traces, timeout) else: _, proto = await self._create_direct_connection( - req, - traces=traces - ) + req, traces, timeout) return proto @staticmethod @functools.lru_cache(None) - def _make_ssl_context(verified): + def _make_ssl_context(verified: bool) -> SSLContext: if verified: return ssl.create_default_context() else: @@ -748,7 +846,7 @@ sslcontext.set_default_verify_paths() return sslcontext - def _get_ssl_context(self, req): + def _get_ssl_context(self, req: 'ClientRequest') -> Optional[SSLContext]: """Logic to get the correct SSL context 0. if req.ssl is false, return None @@ -781,7 +879,8 @@ else: return None - def _get_fingerprint(self, req): + def _get_fingerprint(self, + req: 'ClientRequest') -> Optional['Fingerprint']: ret = req.ssl if isinstance(ret, Fingerprint): return ret @@ -790,12 +889,18 @@ return ret return None - async def _wrap_create_connection(self, *args, - req, client_error=ClientConnectorError, - **kwargs): + async def _wrap_create_connection( + self, *args: Any, + req: 'ClientRequest', + timeout: 'ClientTimeout', + client_error: Type[Exception]=ClientConnectorError, + **kwargs: Any) -> Tuple[asyncio.Transport, ResponseHandler]: try: - return await self._loop.create_connection(*args, **kwargs) - except certificate_errors as exc: + with CeilTimeout(timeout.sock_connect): + return cast( + Tuple[asyncio.Transport, ResponseHandler], + await self._loop.create_connection(*args, **kwargs)) + except cert_errors as exc: raise ClientConnectorCertificateError( req.connection_key, exc) from exc except ssl_errors as exc: @@ -803,9 +908,14 @@ except OSError as exc: raise client_error(req.connection_key, exc) from exc - async def _create_direct_connection(self, req, - *, client_error=ClientConnectorError, - traces=None): + 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) @@ -813,16 +923,20 @@ # Cancelling this lookup should not cancel the underlying lookup # or else the cancel event will get broadcast to all the waiters # across all connections. + host = req.url.raw_host + assert host is not None + port = req.port + assert port is not None hosts = await asyncio.shield(self._resolve_host( - req.url.raw_host, - req.port, + host, + port, traces=traces), loop=self._loop) 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 + last_exc = None # type: Optional[Exception] for hinfo in hosts: host = hinfo['host'] @@ -830,7 +944,7 @@ try: transp, proto = await self._wrap_create_connection( - self._factory, host, port, + 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, @@ -852,16 +966,24 @@ return transp, proto else: + assert last_exc is not None raise last_exc - async def _create_proxy_connection(self, req, traces=None): - headers = {} + async def _create_proxy_connection( + self, + req: 'ClientRequest', + traces: List['Trace'], + timeout: 'ClientTimeout' + ) -> Tuple[asyncio.Transport, ResponseHandler]: + headers = {} # type: Dict[str, str] if req.proxy_headers is not None: - headers = req.proxy_headers + headers = req.proxy_headers # type: ignore headers[hdrs.HOST] = req.headers[hdrs.HOST] + url = req.proxy + assert url is not None proxy_req = ClientRequest( - hdrs.METH_GET, req.proxy, + hdrs.METH_GET, url, headers=headers, auth=req.proxy_auth, loop=self._loop, @@ -869,7 +991,12 @@ # create connection to proxy server transport, proto = await self._create_direct_connection( - proxy_req, client_error=ClientProxyConnectionError) + 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: @@ -891,11 +1018,17 @@ # asyncio handles this perfectly proxy_req.method = hdrs.METH_CONNECT proxy_req.url = req.url - key = (req.host, req.port, req.ssl) + 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: - resp = await proxy_resp.start(conn, True) + protocol = conn._protocol + assert protocol is not None + protocol.set_response_params() + resp = await proxy_resp.start(conn) except BaseException: proxy_resp.close() conn.close() @@ -905,11 +1038,14 @@ 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=resp.reason, + message=message, headers=resp.headers) rawsock = transport.get_extra_info('socket', default=None) if rawsock is None: @@ -921,7 +1057,8 @@ transport.close() transport, proto = await self._wrap_create_connection( - self._factory, ssl=sslcontext, sock=rawsock, + self._factory, timeout=timeout, + ssl=sslcontext, sock=rawsock, server_hostname=req.host, req=req) finally: @@ -942,23 +1079,28 @@ loop - Optional event loop. """ - def __init__(self, path, force_close=False, keepalive_timeout=sentinel, - limit=100, limit_per_host=0, loop=None): + 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): + def path(self) -> str: """Path to unix socket.""" return self._path - async def _create_connection(self, req, traces=None): + async def _create_connection(self, req: 'ClientRequest', + traces: List['Trace'], + timeout: 'ClientTimeout') -> ResponseHandler: try: - _, proto = await self._loop.create_unix_connection( - self._factory, self._path) + with CeilTimeout(timeout.sock_connect): + _, proto = await self._loop.create_unix_connection( + self._factory, self._path) except OSError as exc: raise ClientConnectorError(req.connection_key, exc) from exc - return proto + return cast(ResponseHandler, proto) diff -Nru python-aiohttp-3.1.3/aiohttp/cookiejar.py python-aiohttp-3.5.1/aiohttp/cookiejar.py --- python-aiohttp-3.1.3/aiohttp/cookiejar.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/cookiejar.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,21 +1,28 @@ +import asyncio import datetime +import os # noqa import pathlib import pickle import re from collections import defaultdict -from collections.abc import Mapping -from http.cookies import Morsel, SimpleCookie +from http.cookies import BaseCookie, Morsel, SimpleCookie # noqa from math import ceil +from typing import (DefaultDict, Dict, Iterable, Iterator, Mapping, # noqa + Optional, Set, Tuple, Union, cast) from yarl import URL from .abc import AbstractCookieJar from .helpers import is_ip_address +from .typedefs import LooseCookies, PathLike __all__ = ('CookieJar', 'DummyCookieJar') +CookieItem = Union[str, 'Morsel[str]'] + + class CookieJar(AbstractCookieJar): """Implements cookie storage adhering to RFC 6265.""" @@ -34,39 +41,40 @@ MAX_TIME = 2051215261.0 # so far in future (2035-01-01) - def __init__(self, *, unsafe=False, loop=None): + def __init__(self, *, unsafe: bool=False, + loop: Optional[asyncio.AbstractEventLoop]=None) -> None: super().__init__(loop=loop) - self._cookies = defaultdict(SimpleCookie) - self._host_only_cookies = set() + self._cookies = defaultdict(SimpleCookie) #type: DefaultDict[str, SimpleCookie] # noqa + self._host_only_cookies = set() # type: Set[Tuple[str, str]] self._unsafe = unsafe self._next_expiration = ceil(self._loop.time()) - self._expirations = {} + self._expirations = {} # type: Dict[Tuple[str, str], int] - def save(self, file_path): + 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): + 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): + def clear(self) -> None: self._cookies.clear() self._host_only_cookies.clear() self._next_expiration = ceil(self._loop.time()) self._expirations.clear() - def __iter__(self): + def __iter__(self) -> 'Iterator[Morsel[str]]': self._do_expiration() for val in self._cookies.values(): yield from val.values() - def __len__(self): + def __len__(self) -> int: return sum(1 for i in self) - def _do_expiration(self): + def _do_expiration(self) -> None: now = self._loop.time() if self._next_expiration > now: return @@ -88,11 +96,14 @@ self._next_expiration = ceil(next_expiration) - def _expire_cookie(self, when, domain, name): - self._next_expiration = min(self._next_expiration, when) - self._expirations[(domain, name)] = when - - def update_cookies(self, cookies, response_url=URL()): + def _expire_cookie(self, when: float, domain: str, name: str) -> None: + iwhen = int(when) + self._next_expiration = min(self._next_expiration, iwhen) + self._expirations[(domain, name)] = iwhen + + def update_cookies(self, + cookies: LooseCookies, + response_url: URL=URL()) -> None: """Update cookies.""" hostname = response_url.raw_host @@ -101,12 +112,12 @@ return if isinstance(cookies, Mapping): - cookies = cookies.items() + cookies = cookies.items() # type: ignore for name, cookie in cookies: if not isinstance(cookie, Morsel): tmp = SimpleCookie() - tmp[name] = cookie + tmp[name] = cookie # type: ignore cookie = tmp[name] domain = cookie["domain"] @@ -165,7 +176,7 @@ self._do_expiration() - def filter_cookies(self, request_url=URL()): + def filter_cookies(self, request_url: URL=URL()) -> 'BaseCookie[str]': """Returns this jar's cookies filtered by their attributes.""" self._do_expiration() request_url = URL(request_url) @@ -199,14 +210,14 @@ # It's critical we use the Morsel so the coded_value # (based on cookie version) is preserved - mrsl_val = cookie.get(cookie.key, Morsel()) + 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, hostname): + def _is_domain_match(domain: str, hostname: str) -> bool: """Implements domain matching adhering to RFC 6265.""" if hostname == domain: return True @@ -222,7 +233,7 @@ return not is_ip_address(hostname) @staticmethod - def _is_path_match(req_path, cookie_path): + 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 = "/" @@ -241,10 +252,10 @@ return non_matching.startswith("/") @classmethod - def _parse_date(cls, date_str): + def _parse_date(cls, date_str: str) -> Optional[datetime.datetime]: """Implements date string parsing adhering to RFC 6265.""" if not date_str: - return + return None found_time = False found_day = False @@ -294,13 +305,13 @@ year += 2000 if False in (found_day, found_month, found_year, found_time): - return + return None if not 1 <= day <= 31: - return + return None if year < 1601 or hour > 23 or minute > 59 or second > 59: - return + return None return datetime.datetime(year, month, day, hour, minute, second, @@ -314,21 +325,24 @@ """ - def __init__(self, *, loop=None): + def __init__(self, *, + loop: Optional[asyncio.AbstractEventLoop]=None) -> None: super().__init__(loop=loop) - def __iter__(self): + def __iter__(self) -> 'Iterator[Morsel[str]]': while False: yield None - def __len__(self): + def __len__(self) -> int: return 0 - def clear(self): + def clear(self) -> None: pass - def update_cookies(self, cookies, response_url=None): + def update_cookies(self, + cookies: LooseCookies, + response_url: URL=URL()) -> None: pass - def filter_cookies(self, request_url): - return None + def filter_cookies(self, request_url: URL) -> 'BaseCookie[str]': + return SimpleCookie() diff -Nru python-aiohttp-3.1.3/aiohttp/_find_header.c python-aiohttp-3.5.1/aiohttp/_find_header.c --- python-aiohttp-3.1.3/aiohttp/_find_header.c 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/_find_header.c 2018-12-24 20:58:54.000000000 +0000 @@ -0,0 +1,10000 @@ +/* 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--; + +INITIAL: + 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 'P': + if (last) { + return -1; + } + goto UP; + case 'p': + if (last) { + return -1; + } + goto UP; + case 'R': + if (last) { + return -1; + } + goto UR; + case 'r': + if (last) { + return -1; + } + goto UR; + case 'S': + if (last) { + return -1; + } + goto US; + case 's': + if (last) { + return -1; + } + goto US; + 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 66; + } + goto UPGRADE; + case 'e': + if (last) { + return 66; + } + goto UPGRADE; + default: + return -1; + } + +UR: + NEXT_CHAR(); + switch (ch) { + case 'I': + if (last) { + return 67; + } + goto URI; + case 'i': + if (last) { + return 67; + } + goto URI; + 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 'A': + if (last) { + return -1; + } + goto WA; + case 'a': + if (last) { + return -1; + } + goto WA; + case 'E': + if (last) { + return -1; + } + goto WE; + case 'e': + if (last) { + return -1; + } + goto WE; + case 'W': + if (last) { + return -1; + } + goto WW; + case 'w': + if (last) { + return -1; + } + goto WW; + 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 71; + } + goto WANT_DIGEST; + case 't': + if (last) { + return 71; + } + 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 72; + } + goto WARNING; + case 'g': + if (last) { + return 72; + } + goto WARNING; + default: + return -1; + } + +WE: + NEXT_CHAR(); + switch (ch) { + case 'B': + if (last) { + return -1; + } + goto WEB; + case 'b': + if (last) { + return -1; + } + goto WEB; + default: + return -1; + } + +WEB: + NEXT_CHAR(); + switch (ch) { + case 'S': + if (last) { + return -1; + } + goto WEBS; + case 's': + if (last) { + return -1; + } + goto WEBS; + default: + return -1; + } + +WEBS: + NEXT_CHAR(); + switch (ch) { + case 'O': + if (last) { + return -1; + } + goto WEBSO; + case 'o': + if (last) { + return -1; + } + goto WEBSO; + default: + return -1; + } + +WEBSO: + NEXT_CHAR(); + switch (ch) { + case 'C': + if (last) { + return -1; + } + goto WEBSOC; + case 'c': + if (last) { + return -1; + } + goto WEBSOC; + default: + return -1; + } + +WEBSOC: + NEXT_CHAR(); + switch (ch) { + case 'K': + if (last) { + return -1; + } + goto WEBSOCK; + case 'k': + if (last) { + return -1; + } + goto WEBSOCK; + default: + return -1; + } + +WEBSOCK: + NEXT_CHAR(); + switch (ch) { + case 'E': + if (last) { + return -1; + } + goto WEBSOCKE; + case 'e': + if (last) { + return -1; + } + goto WEBSOCKE; + default: + return -1; + } + +WEBSOCKE: + NEXT_CHAR(); + switch (ch) { + case 'T': + if (last) { + return 73; + } + goto WEBSOCKET; + case 't': + if (last) { + return 73; + } + goto WEBSOCKET; + 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 74; + } + goto WWW_AUTHENTICATE; + case 'e': + if (last) { + return 74; + } + goto WWW_AUTHENTICATE; + 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 75; + } + goto X_FORWARDED_FOR; + case 'r': + if (last) { + return 75; + } + 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 76; + } + goto X_FORWARDED_HOST; + case 't': + if (last) { + return 76; + } + 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 77; + } + goto X_FORWARDED_PROTO; + case 'o': + if (last) { + return 77; + } + 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: +WEBSOCKET: +WWW_AUTHENTICATE: +X_FORWARDED_FOR: +X_FORWARDED_HOST: +X_FORWARDED_PROTO: +missing: + /* nothing found */ + return -1; +} diff -Nru python-aiohttp-3.1.3/aiohttp/_find_header.h python-aiohttp-3.5.1/aiohttp/_find_header.h --- python-aiohttp-3.1.3/aiohttp/_find_header.h 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/_find_header.h 2018-12-24 20:58:54.000000000 +0000 @@ -0,0 +1,14 @@ +#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 -Nru python-aiohttp-3.1.3/aiohttp/_find_header.pxd python-aiohttp-3.5.1/aiohttp/_find_header.pxd --- python-aiohttp-3.1.3/aiohttp/_find_header.pxd 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/_find_header.pxd 2018-12-24 20:58:54.000000000 +0000 @@ -0,0 +1,2 @@ +cdef extern from "_find_header.h": + int find_header(char *, int) diff -Nru python-aiohttp-3.1.3/aiohttp/formdata.py python-aiohttp-3.5.1/aiohttp/formdata.py --- python-aiohttp-3.1.3/aiohttp/formdata.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/formdata.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,10 +1,12 @@ import io +from typing import Any, Iterable, List, Optional # noqa 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',) @@ -14,9 +16,12 @@ """Helper class for multipart/form-data and application/x-www-form-urlencoded body generation.""" - def __init__(self, fields=(), quote_fields=True, charset=None): + def __init__(self, fields: + Iterable[Any]=(), + quote_fields: bool=True, + charset: Optional[str]=None) -> None: self._writer = multipart.MultipartWriter('form-data') - self._fields = [] + self._fields = [] # type: List[Any] self._is_multipart = False self._quote_fields = quote_fields self._charset = charset @@ -28,11 +33,13 @@ self.add_fields(*fields) @property - def is_multipart(self): + def is_multipart(self) -> bool: return self._is_multipart - def add_field(self, name, value, *, content_type=None, filename=None, - content_transfer_encoding=None): + 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 @@ -66,7 +73,7 @@ self._fields.append((type_options, headers, value)) - def add_fields(self, *fields): + def add_fields(self, *fields: Any) -> None: to_add = list(fields) while to_add: @@ -74,14 +81,14 @@ if isinstance(rec, io.IOBase): k = guess_filename(rec, 'unknown') - self.add_field(k, rec) + self.add_field(k, rec) # type: ignore 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) + self.add_field(k, fp) # type: ignore else: raise TypeError('Only io.IOBase, multidict and (name, file) ' @@ -89,7 +96,7 @@ 'more complex parameters, got {!r}' .format(rec)) - def _gen_form_urlencoded(self): + def _gen_form_urlencoded(self) -> payload.BytesPayload: # form data (x-www-form-urlencoded) data = [] for type_options, _, value in self._fields: @@ -107,7 +114,7 @@ urlencode(data, doseq=True, encoding=charset).encode(), content_type=content_type) - def _gen_form_data(self): + def _gen_form_data(self) -> multipart.MultipartWriter: """Encode a list of fields using the multipart/form-data MIME format""" for dispparams, headers, value in self._fields: try: @@ -130,13 +137,14 @@ ) # 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) return self._writer - def __call__(self): + def __call__(self) -> Payload: if self._is_multipart: return self._gen_form_data() else: diff -Nru python-aiohttp-3.1.3/aiohttp/_frozenlist.c python-aiohttp-3.5.1/aiohttp/_frozenlist.c --- python-aiohttp-3.1.3/aiohttp/_frozenlist.c 2018-04-13 10:01:35.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/_frozenlist.c 2018-12-24 20:59:10.000000000 +0000 @@ -1,4 +1,4 @@ -/* Generated by Cython 0.28.1 */ +/* Generated by Cython 0.29.2 */ /* BEGIN: Cython Metadata { @@ -19,7 +19,8 @@ #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_28_1" +#define CYTHON_ABI "0_29_2" +#define CYTHON_HEX_VERSION 0x001D02F0 #define CYTHON_FUTURE_DIVISION 0 #include #ifndef offsetof @@ -90,6 +91,10 @@ #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 @@ -127,6 +132,10 @@ #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 @@ -180,11 +189,17 @@ #define CYTHON_FAST_PYCALL 1 #endif #ifndef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT (0 && PY_VERSION_HEX >= 0x03050000) + #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) @@ -194,6 +209,9 @@ #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 @@ -320,6 +338,9 @@ #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 @@ -333,15 +354,40 @@ #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))))) + ((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_USE_DICT_VERSIONS +#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);\ + }\ + } +#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 #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) @@ -449,8 +495,8 @@ #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)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) -#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#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 @@ -465,6 +511,7 @@ #define PyString_Type PyUnicode_Type #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact + #define PyObject_Unicode PyObject_Str #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) @@ -601,6 +648,9 @@ (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) @@ -657,8 +707,9 @@ #define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) #define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) -#define __Pyx_PyBool_FromLong(b) ((b) ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False)) +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)) @@ -739,7 +790,7 @@ 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)); + __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); @@ -765,7 +816,7 @@ static PyObject *__pyx_m = NULL; static PyObject *__pyx_d; static PyObject *__pyx_b; -static PyObject *__pyx_cython_runtime; +static PyObject *__pyx_cython_runtime = NULL; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; static PyObject *__pyx_empty_unicode; @@ -967,13 +1018,6 @@ #define __Pyx_PyObject_GetItem(obj, key) PyObject_GetItem(obj, key) #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)\ @@ -983,6 +1027,18 @@ #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 /* PyObjectCallMethO.proto */ @@ -990,9 +1046,6 @@ 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); - /* PyObjectCallNoArg.proto */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); @@ -1000,13 +1053,18 @@ #define __Pyx_PyObject_CallNoArg(func) __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL) #endif -/* PyIntBinop.proto */ -#if !CYTHON_COMPILING_IN_PYPY -static PyObject* __Pyx_PyInt_EqObjC(PyObject *op1, PyObject *op2, long intval, int inplace); +/* PyCFunctionFastCall.proto */ +#if CYTHON_FAST_PYCCALL +static CYTHON_INLINE PyObject *__Pyx_PyCFunction_FastCall(PyObject *func, PyObject **args, Py_ssize_t nargs); #else -#define __Pyx_PyInt_EqObjC(op1, op2, intval, inplace)\ - PyObject_RichCompare(op1, op2, Py_EQ) - #endif +#define __Pyx_PyCFunction_FastCall(func, args, nargs) (assert(0), NULL) +#endif + +/* PyObjectCallOneArg.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); + +/* PyIntCompare.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyInt_EqObjC(PyObject *op1, PyObject *op2, long intval, long inplace); /* PySequenceContains.proto */ static CYTHON_INLINE int __Pyx_PySequence_ContainsTF(PyObject* item, PyObject* seq, int eq) { @@ -1014,9 +1072,14 @@ return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); } +/* PyObjectCall2Args.proto */ +static CYTHON_UNUSED PyObject* __Pyx_PyObject_Call2Args(PyObject* function, PyObject* arg1, PyObject* arg2); + +/* 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); -static PyObject* __Pyx__PyObject_CallMethod1(PyObject* method, PyObject* arg); /* pop_index.proto */ static PyObject* __Pyx__PyObject_PopNewIndex(PyObject* L, PyObject* py_ix); @@ -1073,7 +1136,25 @@ static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); /* GetModuleGlobalName.proto */ -static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); +#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); @@ -1199,6 +1280,7 @@ 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_FrozenList[] = "FrozenList"; static const char __pyx_k_pyx_result[] = "__pyx_result"; static const char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; static const char __pyx_k_PickleError[] = "PickleError"; @@ -1217,6 +1299,7 @@ static const char __pyx_k_Cannot_modify_frozen_list[] = "Cannot modify frozen list."; static const char __pyx_k_Incompatible_checksums_s_vs_0x94[] = "Incompatible checksums (%s vs 0x949a143 = (_items, frozen))"; static PyObject *__pyx_kp_s_Cannot_modify_frozen_list; +static PyObject *__pyx_n_s_FrozenList; static PyObject *__pyx_kp_s_FrozenList_frozen_r; static PyObject *__pyx_kp_s_Incompatible_checksums_s_vs_0x94; static PyObject *__pyx_n_s_MutableSequence; @@ -1954,12 +2037,9 @@ __Pyx_DECREF_SET(__pyx_t_2, function); } } - if (__pyx_t_3) { - __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 42, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } else { - __pyx_t_1 = __Pyx_PyObject_CallNoArg(__pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 42, __pyx_L1_error) - } + __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, 42, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = __pyx_t_1; @@ -2036,12 +2116,9 @@ __Pyx_DECREF_SET(__pyx_t_2, function); } } - if (__pyx_t_3) { - __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 45, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } else { - __pyx_t_1 = __Pyx_PyObject_CallNoArg(__pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 45, __pyx_L1_error) - } + __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, 45, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = __pyx_t_1; @@ -2652,7 +2729,6 @@ PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; __Pyx_RefNannySetupContext("index", 0); /* "aiohttp/_frozenlist.pyx":74 @@ -2675,38 +2751,10 @@ __Pyx_DECREF_SET(__pyx_t_2, function); } } - if (!__pyx_t_3) { - __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v_item); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 74, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - } else { - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[2] = {__pyx_t_3, __pyx_v_item}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 74, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[2] = {__pyx_t_3, __pyx_v_item}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 74, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_4 = PyTuple_New(1+1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 74, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __pyx_t_3 = NULL; - __Pyx_INCREF(__pyx_v_item); - __Pyx_GIVEREF(__pyx_v_item); - PyTuple_SET_ITEM(__pyx_t_4, 0+1, __pyx_v_item); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 74, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } - } + __pyx_t_1 = (__pyx_t_3) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_3, __pyx_v_item) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v_item); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 74, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -2725,7 +2773,6 @@ __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("aiohttp._frozenlist.FrozenList.index", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; @@ -2761,7 +2808,6 @@ PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; __Pyx_RefNannySetupContext("remove", 0); /* "aiohttp/_frozenlist.pyx":77 @@ -2794,38 +2840,10 @@ __Pyx_DECREF_SET(__pyx_t_2, function); } } - if (!__pyx_t_3) { - __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v_item); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 78, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - } else { - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[2] = {__pyx_t_3, __pyx_v_item}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 78, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[2] = {__pyx_t_3, __pyx_v_item}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 78, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_4 = PyTuple_New(1+1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 78, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __pyx_t_3 = NULL; - __Pyx_INCREF(__pyx_v_item); - __Pyx_GIVEREF(__pyx_v_item); - PyTuple_SET_ITEM(__pyx_t_4, 0+1, __pyx_v_item); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 78, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } - } + __pyx_t_1 = (__pyx_t_3) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_3, __pyx_v_item) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v_item); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 78, __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; @@ -2844,7 +2862,6 @@ __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("aiohttp._frozenlist.FrozenList.remove", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; @@ -2912,12 +2929,9 @@ __Pyx_DECREF_SET(__pyx_t_2, function); } } - if (__pyx_t_3) { - __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 82, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } else { - __pyx_t_1 = __Pyx_PyObject_CallNoArg(__pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 82, __pyx_L1_error) - } + __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, 82, __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; @@ -3321,7 +3335,6 @@ PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; __Pyx_RefNannySetupContext("count", 0); /* "aiohttp/_frozenlist.pyx":101 @@ -3344,38 +3357,10 @@ __Pyx_DECREF_SET(__pyx_t_2, function); } } - if (!__pyx_t_3) { - __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v_item); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 101, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - } else { - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[2] = {__pyx_t_3, __pyx_v_item}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 101, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[2] = {__pyx_t_3, __pyx_v_item}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 101, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_4 = PyTuple_New(1+1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 101, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __pyx_t_3 = NULL; - __Pyx_INCREF(__pyx_v_item); - __Pyx_GIVEREF(__pyx_v_item); - PyTuple_SET_ITEM(__pyx_t_4, 0+1, __pyx_v_item); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 101, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } - } + __pyx_t_1 = (__pyx_t_3) ? __Pyx_PyObject_Call2Args(__pyx_t_2, __pyx_t_3, __pyx_v_item) : __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v_item); + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 101, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = __pyx_t_1; __pyx_t_1 = 0; @@ -3394,7 +3379,6 @@ __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("aiohttp._frozenlist.FrozenList.count", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; @@ -3575,8 +3559,8 @@ /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * cdef bint use_setstate - * state = (self._items, self.frozen) + * cdef tuple state + * cdef object _dict */ /* Python wrapper */ @@ -3593,9 +3577,9 @@ } static PyObject *__pyx_pf_7aiohttp_11_frozenlist_10FrozenList_42__reduce_cython__(struct __pyx_obj_7aiohttp_11_frozenlist_FrozenList *__pyx_v_self) { + PyObject *__pyx_v_state = 0; + PyObject *__pyx_v__dict = 0; int __pyx_v_use_setstate; - PyObject *__pyx_v_state = NULL; - PyObject *__pyx_v__dict = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; @@ -3605,16 +3589,16 @@ PyObject *__pyx_t_5 = NULL; __Pyx_RefNannySetupContext("__reduce_cython__", 0); - /* "(tree fragment)":3 - * def __reduce_cython__(self): + /* "(tree fragment)":5 + * cdef object _dict * cdef bint use_setstate * state = (self._items, self.frozen) # <<<<<<<<<<<<<< * _dict = getattr(self, '__dict__', None) * if _dict is not None: */ - __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_v_self->frozen); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 3, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_v_self->frozen); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 5, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 3, __pyx_L1_error) + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 5, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(__pyx_v_self->_items); __Pyx_GIVEREF(__pyx_v_self->_items); @@ -3625,19 +3609,19 @@ __pyx_v_state = ((PyObject*)__pyx_t_2); __pyx_t_2 = 0; - /* "(tree fragment)":4 + /* "(tree fragment)":6 * cdef bint use_setstate * state = (self._items, self.frozen) * _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, 4, __pyx_L1_error) + __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)":5 + /* "(tree fragment)":7 * state = (self._items, self.frozen) * _dict = getattr(self, '__dict__', None) * if _dict is not None: # <<<<<<<<<<<<<< @@ -3648,25 +3632,25 @@ __pyx_t_4 = (__pyx_t_3 != 0); if (__pyx_t_4) { - /* "(tree fragment)":6 + /* "(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, 6, __pyx_L1_error) + __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, 6, __pyx_L1_error) + __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)":7 + /* "(tree fragment)":9 * if _dict is not None: * state += (_dict,) * use_setstate = True # <<<<<<<<<<<<<< @@ -3675,7 +3659,7 @@ */ __pyx_v_use_setstate = 1; - /* "(tree fragment)":5 + /* "(tree fragment)":7 * state = (self._items, self.frozen) * _dict = getattr(self, '__dict__', None) * if _dict is not None: # <<<<<<<<<<<<<< @@ -3685,7 +3669,7 @@ goto __pyx_L3; } - /* "(tree fragment)":9 + /* "(tree fragment)":11 * use_setstate = True * else: * use_setstate = self._items is not None # <<<<<<<<<<<<<< @@ -3698,7 +3682,7 @@ } __pyx_L3:; - /* "(tree fragment)":10 + /* "(tree fragment)":12 * else: * use_setstate = self._items is not None * if use_setstate: # <<<<<<<<<<<<<< @@ -3708,7 +3692,7 @@ __pyx_t_4 = (__pyx_v_use_setstate != 0); if (__pyx_t_4) { - /* "(tree fragment)":11 + /* "(tree fragment)":13 * use_setstate = self._items is not None * if use_setstate: * return __pyx_unpickle_FrozenList, (type(self), 0x949a143, None), state # <<<<<<<<<<<<<< @@ -3716,9 +3700,9 @@ * return __pyx_unpickle_FrozenList, (type(self), 0x949a143, state) */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_pyx_unpickle_FrozenList); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 11, __pyx_L1_error) + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_pyx_unpickle_FrozenList); 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, 11, __pyx_L1_error) + __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)))); @@ -3729,7 +3713,7 @@ __Pyx_INCREF(Py_None); __Pyx_GIVEREF(Py_None); PyTuple_SET_ITEM(__pyx_t_2, 2, Py_None); - __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 11, __pyx_L1_error) + __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 13, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_1); @@ -3744,7 +3728,7 @@ __pyx_t_5 = 0; goto __pyx_L0; - /* "(tree fragment)":10 + /* "(tree fragment)":12 * else: * use_setstate = self._items is not None * if use_setstate: # <<<<<<<<<<<<<< @@ -3753,7 +3737,7 @@ */ } - /* "(tree fragment)":13 + /* "(tree fragment)":15 * return __pyx_unpickle_FrozenList, (type(self), 0x949a143, None), state * else: * return __pyx_unpickle_FrozenList, (type(self), 0x949a143, state) # <<<<<<<<<<<<<< @@ -3762,9 +3746,9 @@ */ /*else*/ { __Pyx_XDECREF(__pyx_r); - __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_pyx_unpickle_FrozenList); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 13, __pyx_L1_error) + __Pyx_GetModuleGlobalName(__pyx_t_5, __pyx_n_s_pyx_unpickle_FrozenList); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 15, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); - __pyx_t_2 = PyTuple_New(3); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 13, __pyx_L1_error) + __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)))); @@ -3775,7 +3759,7 @@ __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, 13, __pyx_L1_error) + __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_5); PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_5); @@ -3790,8 +3774,8 @@ /* "(tree fragment)":1 * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * cdef bint use_setstate - * state = (self._items, self.frozen) + * cdef tuple state + * cdef object _dict */ /* function exit code */ @@ -3809,7 +3793,7 @@ return __pyx_r; } -/* "(tree fragment)":14 +/* "(tree fragment)":16 * else: * return __pyx_unpickle_FrozenList, (type(self), 0x949a143, state) * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< @@ -3835,17 +3819,17 @@ PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__setstate_cython__", 0); - /* "(tree fragment)":15 + /* "(tree fragment)":17 * return __pyx_unpickle_FrozenList, (type(self), 0x949a143, state) * def __setstate_cython__(self, __pyx_state): * __pyx_unpickle_FrozenList__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, 15, __pyx_L1_error) - __pyx_t_1 = __pyx_f_7aiohttp_11_frozenlist___pyx_unpickle_FrozenList__set_state(__pyx_v_self, ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 15, __pyx_L1_error) + 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_11_frozenlist___pyx_unpickle_FrozenList__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)":14 + /* "(tree fragment)":16 * else: * return __pyx_unpickle_FrozenList, (type(self), 0x949a143, state) * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< @@ -3867,13 +3851,13 @@ /* "(tree fragment)":1 * def __pyx_unpickle_FrozenList(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * if __pyx_checksum != 0x949a143: - * from pickle import PickleError as __pyx_PickleError + * cdef object __pyx_PickleError + * cdef object __pyx_result */ /* Python wrapper */ static PyObject *__pyx_pw_7aiohttp_11_frozenlist_1__pyx_unpickle_FrozenList(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyMethodDef __pyx_mdef_7aiohttp_11_frozenlist_1__pyx_unpickle_FrozenList = {"__pyx_unpickle_FrozenList", (PyCFunction)__pyx_pw_7aiohttp_11_frozenlist_1__pyx_unpickle_FrozenList, METH_VARARGS|METH_KEYWORDS, 0}; +static PyMethodDef __pyx_mdef_7aiohttp_11_frozenlist_1__pyx_unpickle_FrozenList = {"__pyx_unpickle_FrozenList", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_7aiohttp_11_frozenlist_1__pyx_unpickle_FrozenList, METH_VARARGS|METH_KEYWORDS, 0}; static PyObject *__pyx_pw_7aiohttp_11_frozenlist_1__pyx_unpickle_FrozenList(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v___pyx_type = 0; long __pyx_v___pyx_checksum; @@ -3945,8 +3929,8 @@ } static PyObject *__pyx_pf_7aiohttp_11_frozenlist___pyx_unpickle_FrozenList(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 = NULL; - PyObject *__pyx_v___pyx_result = NULL; + PyObject *__pyx_v___pyx_PickleError = 0; + PyObject *__pyx_v___pyx_result = 0; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; @@ -3954,12 +3938,12 @@ PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - int __pyx_t_7; + int __pyx_t_6; __Pyx_RefNannySetupContext("__pyx_unpickle_FrozenList", 0); - /* "(tree fragment)":2 - * def __pyx_unpickle_FrozenList(__pyx_type, long __pyx_checksum, __pyx_state): + /* "(tree fragment)":4 + * cdef object __pyx_PickleError + * cdef object __pyx_result * if __pyx_checksum != 0x949a143: # <<<<<<<<<<<<<< * from pickle import PickleError as __pyx_PickleError * raise __pyx_PickleError("Incompatible checksums (%s vs 0x949a143 = (_items, frozen))" % __pyx_checksum) @@ -3967,38 +3951,38 @@ __pyx_t_1 = ((__pyx_v___pyx_checksum != 0x949a143) != 0); if (__pyx_t_1) { - /* "(tree fragment)":3 - * def __pyx_unpickle_FrozenList(__pyx_type, long __pyx_checksum, __pyx_state): + /* "(tree fragment)":5 + * cdef object __pyx_result * if __pyx_checksum != 0x949a143: * from pickle import PickleError as __pyx_PickleError # <<<<<<<<<<<<<< * raise __pyx_PickleError("Incompatible checksums (%s vs 0x949a143 = (_items, frozen))" % __pyx_checksum) * __pyx_result = FrozenList.__new__(__pyx_type) */ - __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 3, __pyx_L1_error) + __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, -1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 3, __pyx_L1_error) + __pyx_t_3 = __Pyx_Import(__pyx_n_s_pickle, __pyx_t_2, -1); 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, 3, __pyx_L1_error) + __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)":4 + /* "(tree fragment)":6 * if __pyx_checksum != 0x949a143: * from pickle import PickleError as __pyx_PickleError * raise __pyx_PickleError("Incompatible checksums (%s vs 0x949a143 = (_items, frozen))" % __pyx_checksum) # <<<<<<<<<<<<<< * __pyx_result = FrozenList.__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, 4, __pyx_L1_error) + __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_0x94, __pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 4, __pyx_L1_error) + __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Incompatible_checksums_s_vs_0x94, __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); @@ -4012,110 +3996,53 @@ __Pyx_DECREF_SET(__pyx_t_2, function); } } - if (!__pyx_t_5) { - __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_GOTREF(__pyx_t_3); - } else { - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[2] = {__pyx_t_5, __pyx_t_4}; - __pyx_t_3 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[2] = {__pyx_t_5, __pyx_t_4}; - __pyx_t_3 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } else - #endif - { - __pyx_t_6 = PyTuple_New(1+1); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); __pyx_t_5 = NULL; - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_6, 0+1, __pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_6, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } - } + __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, 4, __pyx_L1_error) + __PYX_ERR(1, 6, __pyx_L1_error) - /* "(tree fragment)":2 - * def __pyx_unpickle_FrozenList(__pyx_type, long __pyx_checksum, __pyx_state): + /* "(tree fragment)":4 + * cdef object __pyx_PickleError + * cdef object __pyx_result * if __pyx_checksum != 0x949a143: # <<<<<<<<<<<<<< * from pickle import PickleError as __pyx_PickleError * raise __pyx_PickleError("Incompatible checksums (%s vs 0x949a143 = (_items, frozen))" % __pyx_checksum) */ } - /* "(tree fragment)":5 + /* "(tree fragment)":7 * from pickle import PickleError as __pyx_PickleError * raise __pyx_PickleError("Incompatible checksums (%s vs 0x949a143 = (_items, frozen))" % __pyx_checksum) * __pyx_result = FrozenList.__new__(__pyx_type) # <<<<<<<<<<<<<< * if __pyx_state is not None: * __pyx_unpickle_FrozenList__set_state( __pyx_result, __pyx_state) */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_ptype_7aiohttp_11_frozenlist_FrozenList), __pyx_n_s_new); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 5, __pyx_L1_error) + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_ptype_7aiohttp_11_frozenlist_FrozenList), __pyx_n_s_new); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 7, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); - __pyx_t_6 = NULL; + __pyx_t_4 = NULL; if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_2))) { - __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_2); - if (likely(__pyx_t_6)) { + __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_6); + __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_2, function); } } - if (!__pyx_t_6) { - __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v___pyx_type); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - } else { - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[2] = {__pyx_t_6, __pyx_v___pyx_type}; - __pyx_t_3 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_GOTREF(__pyx_t_3); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { - PyObject *__pyx_temp[2] = {__pyx_t_6, __pyx_v___pyx_type}; - __pyx_t_3 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_GOTREF(__pyx_t_3); - } else - #endif - { - __pyx_t_4 = PyTuple_New(1+1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_6); __pyx_t_6 = NULL; - __Pyx_INCREF(__pyx_v___pyx_type); - __Pyx_GIVEREF(__pyx_v___pyx_type); - PyTuple_SET_ITEM(__pyx_t_4, 0+1, __pyx_v___pyx_type); - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 5, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } - } + __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)":6 + /* "(tree fragment)":8 * raise __pyx_PickleError("Incompatible checksums (%s vs 0x949a143 = (_items, frozen))" % __pyx_checksum) * __pyx_result = FrozenList.__new__(__pyx_type) * if __pyx_state is not None: # <<<<<<<<<<<<<< @@ -4123,22 +4050,22 @@ * return __pyx_result */ __pyx_t_1 = (__pyx_v___pyx_state != Py_None); - __pyx_t_7 = (__pyx_t_1 != 0); - if (__pyx_t_7) { + __pyx_t_6 = (__pyx_t_1 != 0); + if (__pyx_t_6) { - /* "(tree fragment)":7 + /* "(tree fragment)":9 * __pyx_result = FrozenList.__new__(__pyx_type) * if __pyx_state is not None: * __pyx_unpickle_FrozenList__set_state( __pyx_result, __pyx_state) # <<<<<<<<<<<<<< * return __pyx_result * cdef __pyx_unpickle_FrozenList__set_state(FrozenList __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, 7, __pyx_L1_error) - __pyx_t_3 = __pyx_f_7aiohttp_11_frozenlist___pyx_unpickle_FrozenList__set_state(((struct __pyx_obj_7aiohttp_11_frozenlist_FrozenList *)__pyx_v___pyx_result), ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 7, __pyx_L1_error) + 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_11_frozenlist___pyx_unpickle_FrozenList__set_state(((struct __pyx_obj_7aiohttp_11_frozenlist_FrozenList *)__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)":6 + /* "(tree fragment)":8 * raise __pyx_PickleError("Incompatible checksums (%s vs 0x949a143 = (_items, frozen))" % __pyx_checksum) * __pyx_result = FrozenList.__new__(__pyx_type) * if __pyx_state is not None: # <<<<<<<<<<<<<< @@ -4147,7 +4074,7 @@ */ } - /* "(tree fragment)":8 + /* "(tree fragment)":10 * if __pyx_state is not None: * __pyx_unpickle_FrozenList__set_state( __pyx_result, __pyx_state) * return __pyx_result # <<<<<<<<<<<<<< @@ -4161,8 +4088,8 @@ /* "(tree fragment)":1 * def __pyx_unpickle_FrozenList(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * if __pyx_checksum != 0x949a143: - * from pickle import PickleError as __pyx_PickleError + * cdef object __pyx_PickleError + * cdef object __pyx_result */ /* function exit code */ @@ -4171,7 +4098,6 @@ __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("aiohttp._frozenlist.__pyx_unpickle_FrozenList", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; @@ -4182,7 +4108,7 @@ return __pyx_r; } -/* "(tree fragment)":9 +/* "(tree fragment)":11 * __pyx_unpickle_FrozenList__set_state( __pyx_result, __pyx_state) * return __pyx_result * cdef __pyx_unpickle_FrozenList__set_state(FrozenList __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< @@ -4201,10 +4127,9 @@ PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; __Pyx_RefNannySetupContext("__pyx_unpickle_FrozenList__set_state", 0); - /* "(tree fragment)":10 + /* "(tree fragment)":12 * return __pyx_result * cdef __pyx_unpickle_FrozenList__set_state(FrozenList __pyx_result, tuple __pyx_state): * __pyx_result._items = __pyx_state[0]; __pyx_result.frozen = __pyx_state[1] # <<<<<<<<<<<<<< @@ -4213,11 +4138,11 @@ */ if (unlikely(__pyx_v___pyx_state == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 10, __pyx_L1_error) + __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, 10, __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); - if (!(likely(PyList_CheckExact(__pyx_t_1))||((__pyx_t_1) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "list", Py_TYPE(__pyx_t_1)->tp_name), 0))) __PYX_ERR(1, 10, __pyx_L1_error) + if (!(likely(PyList_CheckExact(__pyx_t_1))||((__pyx_t_1) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "list", 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->_items); __Pyx_DECREF(__pyx_v___pyx_result->_items); @@ -4225,15 +4150,15 @@ __pyx_t_1 = 0; if (unlikely(__pyx_v___pyx_state == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(1, 10, __pyx_L1_error) + __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, 10, __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_PyObject_IsTrue(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 10, __pyx_L1_error) + __pyx_t_2 = __Pyx_PyObject_IsTrue(__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->frozen = __pyx_t_2; - /* "(tree fragment)":11 + /* "(tree fragment)":13 * cdef __pyx_unpickle_FrozenList__set_state(FrozenList __pyx_result, tuple __pyx_state): * __pyx_result._items = __pyx_state[0]; __pyx_result.frozen = __pyx_state[1] * if len(__pyx_state) > 2 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< @@ -4241,36 +4166,36 @@ */ if (unlikely(__pyx_v___pyx_state == Py_None)) { PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - __PYX_ERR(1, 11, __pyx_L1_error) + __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, 11, __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, 11, __pyx_L1_error) + __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)":12 + /* "(tree fragment)":14 * __pyx_result._items = __pyx_state[0]; __pyx_result.frozen = __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, 12, __pyx_L1_error) + __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, 12, __pyx_L1_error) + __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, 12, __pyx_L1_error) + __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, 12, __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))) { @@ -4282,45 +4207,15 @@ __Pyx_DECREF_SET(__pyx_t_7, function); } } - if (!__pyx_t_8) { - __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_7, __pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else { - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[2] = {__pyx_t_8, __pyx_t_6}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_7, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 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_7)) { - PyObject *__pyx_temp[2] = {__pyx_t_8, __pyx_t_6}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_7, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } else - #endif - { - __pyx_t_9 = PyTuple_New(1+1); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __Pyx_GIVEREF(__pyx_t_8); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_8); __pyx_t_8 = NULL; - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_9, 0+1, __pyx_t_6); - __pyx_t_6 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_9, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } - } + __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)":11 + /* "(tree fragment)":13 * cdef __pyx_unpickle_FrozenList__set_state(FrozenList __pyx_result, tuple __pyx_state): * __pyx_result._items = __pyx_state[0]; __pyx_result.frozen = __pyx_state[1] * if len(__pyx_state) > 2 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< @@ -4328,7 +4223,7 @@ */ } - /* "(tree fragment)":9 + /* "(tree fragment)":11 * __pyx_unpickle_FrozenList__set_state( __pyx_result, __pyx_state) * return __pyx_result * cdef __pyx_unpickle_FrozenList__set_state(FrozenList __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< @@ -4344,7 +4239,6 @@ __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_9); __Pyx_AddTraceback("aiohttp._frozenlist.__pyx_unpickle_FrozenList__set_state", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; @@ -4422,13 +4316,13 @@ static PyMethodDef __pyx_methods_7aiohttp_11_frozenlist_FrozenList[] = { {"freeze", (PyCFunction)__pyx_pw_7aiohttp_11_frozenlist_10FrozenList_3freeze, METH_NOARGS, 0}, {"__reversed__", (PyCFunction)__pyx_pw_7aiohttp_11_frozenlist_10FrozenList_15__reversed__, METH_NOARGS, 0}, - {"insert", (PyCFunction)__pyx_pw_7aiohttp_11_frozenlist_10FrozenList_19insert, METH_VARARGS|METH_KEYWORDS, 0}, + {"insert", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_7aiohttp_11_frozenlist_10FrozenList_19insert, METH_VARARGS|METH_KEYWORDS, 0}, {"index", (PyCFunction)__pyx_pw_7aiohttp_11_frozenlist_10FrozenList_25index, METH_O, 0}, {"remove", (PyCFunction)__pyx_pw_7aiohttp_11_frozenlist_10FrozenList_27remove, METH_O, 0}, {"clear", (PyCFunction)__pyx_pw_7aiohttp_11_frozenlist_10FrozenList_29clear, METH_NOARGS, 0}, {"extend", (PyCFunction)__pyx_pw_7aiohttp_11_frozenlist_10FrozenList_31extend, METH_O, 0}, {"reverse", (PyCFunction)__pyx_pw_7aiohttp_11_frozenlist_10FrozenList_33reverse, METH_NOARGS, 0}, - {"pop", (PyCFunction)__pyx_pw_7aiohttp_11_frozenlist_10FrozenList_35pop, METH_VARARGS|METH_KEYWORDS, 0}, + {"pop", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_7aiohttp_11_frozenlist_10FrozenList_35pop, METH_VARARGS|METH_KEYWORDS, 0}, {"append", (PyCFunction)__pyx_pw_7aiohttp_11_frozenlist_10FrozenList_37append, METH_O, 0}, {"count", (PyCFunction)__pyx_pw_7aiohttp_11_frozenlist_10FrozenList_39count, METH_O, 0}, {"__reduce_cython__", (PyCFunction)__pyx_pw_7aiohttp_11_frozenlist_10FrozenList_43__reduce_cython__, METH_NOARGS, 0}, @@ -4615,9 +4509,19 @@ 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_s_Cannot_modify_frozen_list, __pyx_k_Cannot_modify_frozen_list, sizeof(__pyx_k_Cannot_modify_frozen_list), 0, 0, 1, 0}, + {&__pyx_n_s_FrozenList, __pyx_k_FrozenList, sizeof(__pyx_k_FrozenList), 0, 0, 1, 1}, {&__pyx_kp_s_FrozenList_frozen_r, __pyx_k_FrozenList_frozen_r, sizeof(__pyx_k_FrozenList_frozen_r), 0, 0, 1, 0}, {&__pyx_kp_s_Incompatible_checksums_s_vs_0x94, __pyx_k_Incompatible_checksums_s_vs_0x94, sizeof(__pyx_k_Incompatible_checksums_s_vs_0x94), 0, 0, 1, 0}, {&__pyx_n_s_MutableSequence, __pyx_k_MutableSequence, sizeof(__pyx_k_MutableSequence), 0, 0, 1, 1}, @@ -4662,14 +4566,14 @@ {&__pyx_n_s_update, __pyx_k_update, sizeof(__pyx_k_update), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; -static int __Pyx_InitCachedBuiltins(void) { +static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) { __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) __PYX_ERR(0, 19, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; } -static int __Pyx_InitCachedConstants(void) { +static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); @@ -4686,8 +4590,8 @@ /* "(tree fragment)":1 * def __pyx_unpickle_FrozenList(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * if __pyx_checksum != 0x949a143: - * from pickle import PickleError as __pyx_PickleError + * 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); @@ -4700,7 +4604,7 @@ return -1; } -static int __Pyx_InitGlobals(void) { +static CYTHON_SMALL_CODE int __Pyx_InitGlobals(void) { if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error); __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) __PYX_ERR(0, 1, __pyx_L1_error) @@ -4715,13 +4619,13 @@ return -1; } -static int __Pyx_modinit_global_init_code(void); /*proto*/ -static int __Pyx_modinit_variable_export_code(void); /*proto*/ -static int __Pyx_modinit_function_export_code(void); /*proto*/ -static int __Pyx_modinit_type_init_code(void); /*proto*/ -static int __Pyx_modinit_type_import_code(void); /*proto*/ -static int __Pyx_modinit_variable_import_code(void); /*proto*/ -static int __Pyx_modinit_function_import_code(void); /*proto*/ +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 @@ -4760,7 +4664,7 @@ __pyx_type_7aiohttp_11_frozenlist_FrozenList.tp_getattro = __Pyx_PyObject_GenericGetAttr; } if (__Pyx_SetVtable(__pyx_type_7aiohttp_11_frozenlist_FrozenList.tp_dict, __pyx_vtabptr_7aiohttp_11_frozenlist_FrozenList) < 0) __PYX_ERR(0, 4, __pyx_L1_error) - if (PyObject_SetAttrString(__pyx_m, "FrozenList", (PyObject *)&__pyx_type_7aiohttp_11_frozenlist_FrozenList) < 0) __PYX_ERR(0, 4, __pyx_L1_error) + if (PyObject_SetAttr(__pyx_m, __pyx_n_s_FrozenList, (PyObject *)&__pyx_type_7aiohttp_11_frozenlist_FrozenList) < 0) __PYX_ERR(0, 4, __pyx_L1_error) if (__Pyx_setup_reduce((PyObject*)&__pyx_type_7aiohttp_11_frozenlist_FrozenList) < 0) __PYX_ERR(0, 4, __pyx_L1_error) __pyx_ptype_7aiohttp_11_frozenlist_FrozenList = &__pyx_type_7aiohttp_11_frozenlist_FrozenList; __Pyx_RefNannyFinishContext(); @@ -4808,15 +4712,6 @@ #define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC #endif #endif -#ifndef CYTHON_SMALL_CODE -#if defined(__clang__) - #define CYTHON_SMALL_CODE -#elif defined(__GNUC__) - #define CYTHON_SMALL_CODE __attribute__((optimize("Os"))) -#else - #define CYTHON_SMALL_CODE -#endif -#endif #if PY_MAJOR_VERSION < 3 @@ -4829,11 +4724,36 @@ { return PyModuleDef_Init(&__pyx_moduledef); } -static int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name) { +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)) { - result = PyDict_SetItemString(moddict, to_name, 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(); @@ -4842,8 +4762,10 @@ } return result; } -static PyObject* __pyx_pymod_create(PyObject *spec, CYTHON_UNUSED PyModuleDef *def) { +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"); @@ -4853,10 +4775,10 @@ 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__") < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__") < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__") < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__") < 0)) 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); @@ -4864,7 +4786,7 @@ } -static int __pyx_pymod_exec__frozenlist(PyObject *__pyx_pyinit_module) +static CYTHON_SMALL_CODE int __pyx_pymod_exec__frozenlist(PyObject *__pyx_pyinit_module) #endif #endif { @@ -4872,7 +4794,11 @@ PyObject *__pyx_t_2 = NULL; __Pyx_RefNannyDeclarations #if CYTHON_PEP489_MULTI_PHASE_INIT - if (__pyx_m && __pyx_m == __pyx_pyinit_module) return 0; + if (__pyx_m) { + if (__pyx_m == __pyx_pyinit_module) return 0; + PyErr_SetString(PyExc_RuntimeError, "Module '_frozenlist' 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 @@ -4887,6 +4813,9 @@ #endif __Pyx_RefNannySetupContext("__Pyx_PyMODINIT_FUNC PyInit__frozenlist(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) @@ -4941,7 +4870,7 @@ if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif if (__pyx_module_is_main_aiohttp___frozenlist) { - if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + 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 { @@ -4992,7 +4921,7 @@ * * MutableSequence.register(FrozenList) # <<<<<<<<<<<<<< */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_MutableSequence); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 108, __pyx_L1_error) + __Pyx_GetModuleGlobalName(__pyx_t_2, __pyx_n_s_MutableSequence); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 108, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_register); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 108, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); @@ -5004,8 +4933,8 @@ /* "(tree fragment)":1 * def __pyx_unpickle_FrozenList(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< - * if __pyx_checksum != 0x949a143: - * from pickle import PickleError as __pyx_PickleError + * cdef object __pyx_PickleError + * cdef object __pyx_result */ __pyx_t_2 = PyCFunction_NewEx(&__pyx_mdef_7aiohttp_11_frozenlist_1__pyx_unpickle_FrozenList, NULL, __pyx_n_s_aiohttp__frozenlist); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); @@ -5030,9 +4959,9 @@ __Pyx_XDECREF(__pyx_t_2); if (__pyx_m) { if (__pyx_d) { - __Pyx_AddTraceback("init aiohttp._frozenlist", 0, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("init aiohttp._frozenlist", __pyx_clineno, __pyx_lineno, __pyx_filename); } - Py_DECREF(__pyx_m); __pyx_m = 0; + Py_CLEAR(__pyx_m); } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "init aiohttp._frozenlist"); } @@ -5053,9 +4982,9 @@ static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; void *r = NULL; - m = PyImport_ImportModule((char *)modname); + m = PyImport_ImportModule(modname); if (!m) goto end; - p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); + p = PyObject_GetAttrString(m, "RefNannyAPI"); if (!p) goto end; r = PyLong_AsVoidPtr(p); end: @@ -5454,7 +5383,7 @@ if (wraparound & unlikely(i < 0)) { wrapped_i += PyList_GET_SIZE(o); } - if ((!boundscheck) || likely((0 <= wrapped_i) & (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; @@ -5472,7 +5401,7 @@ if (wraparound & unlikely(i < 0)) { wrapped_i += PyTuple_GET_SIZE(o); } - if ((!boundscheck) || likely((0 <= wrapped_i) & (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; @@ -5488,7 +5417,7 @@ #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((n >= 0) & (n < 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; @@ -5496,7 +5425,7 @@ } else if (PyTuple_CheckExact(o)) { Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); - if ((!boundscheck) || likely((n >= 0) & (n < 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; @@ -5554,32 +5483,8 @@ } #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))); - 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)meth)) (self, args, nargs, NULL); - } else { - return (*((__Pyx_PyCFunctionFast)meth)) (self, args, nargs); - } -} -#endif - /* PyFunctionFastCall */ #if CYTHON_FAST_PYCALL -#include "frameobject.h" static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na, PyObject *globals) { PyFrameObject *f; @@ -5597,7 +5502,7 @@ if (f == NULL) { return NULL; } - fastlocals = f->f_localsplus; + fastlocals = __Pyx_PyFrame_GetLocalsplus(f); for (i = 0; i < na; i++) { Py_INCREF(*args); fastlocals[i] = *args++; @@ -5717,6 +5622,51 @@ } #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) { @@ -5757,30 +5707,8 @@ } #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_TypeCheck(func, __pyx_CyFunctionType))) { -#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 - -/* PyIntBinop */ - #if !CYTHON_COMPILING_IN_PYPY -static PyObject* __Pyx_PyInt_EqObjC(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, CYTHON_UNUSED int inplace) { +/* PyIntCompare */ +static CYTHON_INLINE PyObject* __Pyx_PyInt_EqObjC(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, CYTHON_UNUSED long inplace) { if (op1 == op2) { Py_RETURN_TRUE; } @@ -5788,140 +5716,209 @@ if (likely(PyInt_CheckExact(op1))) { const long b = intval; long a = PyInt_AS_LONG(op1); - if (a == b) { - Py_RETURN_TRUE; - } else { - Py_RETURN_FALSE; - } + if (a == b) Py_RETURN_TRUE; else Py_RETURN_FALSE; } #endif #if CYTHON_USE_PYLONG_INTERNALS if (likely(PyLong_CheckExact(op1))) { - const long b = intval; - long a; + int unequal; + unsigned long uintval; + Py_ssize_t size = Py_SIZE(op1); const digit* digits = ((PyLongObject*)op1)->ob_digit; - const Py_ssize_t size = Py_SIZE(op1); - if (likely(__Pyx_sst_abs(size) <= 1)) { - a = likely(size) ? digits[0] : 0; - if (size == -1) a = -a; + if (intval == 0) { + if (size == 0) Py_RETURN_TRUE; else Py_RETURN_FALSE; + } else if (intval < 0) { + if (size >= 0) + Py_RETURN_FALSE; + intval = -intval; + size = -size; } else { - switch (size) { - case -2: - if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - a = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; - } - CYTHON_FALLTHROUGH; - case 2: - if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { - a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; - } - CYTHON_FALLTHROUGH; - case -3: - if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - a = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; - } - CYTHON_FALLTHROUGH; - case 3: - if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { - a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; - } - CYTHON_FALLTHROUGH; - case -4: - if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - a = -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; - } - CYTHON_FALLTHROUGH; - case 4: - if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { - a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); - break; - } - CYTHON_FALLTHROUGH; - #if PyLong_SHIFT < 30 && PyLong_SHIFT != 15 - default: return PyLong_Type.tp_richcompare(op1, op2, Py_EQ); - #else - default: Py_RETURN_FALSE; - #endif - } - } - if (a == b) { - Py_RETURN_TRUE; - } else { + if (size <= 0) Py_RETURN_FALSE; - } + } + uintval = (unsigned long) intval; +#if PyLong_SHIFT * 4 < SIZEOF_LONG*8 + if (uintval >> (PyLong_SHIFT * 4)) { + unequal = (size != 5) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) + | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[2] != ((uintval >> (2 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[3] != ((uintval >> (3 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[4] != ((uintval >> (4 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); + } else +#endif +#if PyLong_SHIFT * 3 < SIZEOF_LONG*8 + if (uintval >> (PyLong_SHIFT * 3)) { + unequal = (size != 4) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) + | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[2] != ((uintval >> (2 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[3] != ((uintval >> (3 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); + } else +#endif +#if PyLong_SHIFT * 2 < SIZEOF_LONG*8 + if (uintval >> (PyLong_SHIFT * 2)) { + unequal = (size != 3) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) + | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)) | (digits[2] != ((uintval >> (2 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); + } else +#endif +#if PyLong_SHIFT * 1 < SIZEOF_LONG*8 + if (uintval >> (PyLong_SHIFT * 1)) { + unequal = (size != 2) || (digits[0] != (uintval & (unsigned long) PyLong_MASK)) + | (digits[1] != ((uintval >> (1 * PyLong_SHIFT)) & (unsigned long) PyLong_MASK)); + } else +#endif + unequal = (size != 1) || (((unsigned long) digits[0]) != (uintval & (unsigned long) PyLong_MASK)); + if (unequal == 0) Py_RETURN_TRUE; else Py_RETURN_FALSE; } #endif if (PyFloat_CheckExact(op1)) { const long b = intval; double a = PyFloat_AS_DOUBLE(op1); - if ((double)a == (double)b) { - Py_RETURN_TRUE; - } else { - Py_RETURN_FALSE; - } + if ((double)a == (double)b) Py_RETURN_TRUE; else Py_RETURN_FALSE; } - return PyObject_RichCompare(op1, op2, Py_EQ); + return ( + PyObject_RichCompare(op1, op2, Py_EQ)); } -#endif -/* PyObjectCallMethod1 */ - static PyObject* __Pyx__PyObject_CallMethod1(PyObject* method, PyObject* arg) { - PyObject *result = NULL; -#if CYTHON_UNPACK_METHODS - if (likely(PyMethod_Check(method))) { - PyObject *self = PyMethod_GET_SELF(method); - if (likely(self)) { - PyObject *args; - PyObject *function = PyMethod_GET_FUNCTION(method); - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(function)) { - PyObject *args[2] = {self, arg}; - result = __Pyx_PyFunction_FastCall(function, args, 2); - goto done; - } - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(function)) { - PyObject *args[2] = {self, arg}; - result = __Pyx_PyCFunction_FastCall(function, args, 2); - goto done; +/* 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; +} + +/* 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; } - #endif - args = PyTuple_New(2); - if (unlikely(!args)) goto done; - Py_INCREF(self); - PyTuple_SET_ITEM(args, 0, self); - Py_INCREF(arg); - PyTuple_SET_ITEM(args, 1, arg); - Py_INCREF(function); - result = __Pyx_PyObject_Call(function, args, NULL); - Py_DECREF(args); - Py_DECREF(function); - return result; } } + 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 - result = __Pyx_PyObject_CallOneArg(method, arg); - goto done; -done: + 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, *result; - method = __Pyx_PyObject_GetAttrStr(obj, method_name); + 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; - result = __Pyx__PyObject_CallMethod1(method, arg); - Py_DECREF(method); - return result; + return __Pyx__PyObject_CallMethod1(method, arg); } /* pop_index */ - static PyObject* __Pyx__PyObject_PopNewIndex(PyObject* L, PyObject* py_ix) { +static PyObject* __Pyx__PyObject_PopNewIndex(PyObject* L, PyObject* py_ix) { PyObject *r; if (unlikely(!py_ix)) return NULL; r = __Pyx__PyObject_PopIndex(L, py_ix); @@ -5939,7 +5936,7 @@ if (cix < 0) { cix += size; } - if (likely(0 <= cix && cix < size)) { + if (likely(__Pyx_is_valid_index(cix, size))) { PyObject* v = PyList_GET_ITEM(L, cix); Py_SIZE(L) -= 1; size -= 1; @@ -5956,7 +5953,7 @@ #endif /* PyErrExceptionMatches */ - #if CYTHON_FAST_THREAD_STATE +#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); @@ -5981,7 +5978,7 @@ #endif /* GetAttr */ - static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { +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))) @@ -5994,7 +5991,7 @@ } /* GetAttr3 */ - static PyObject *__Pyx_GetAttr3Default(PyObject *d) { +static PyObject *__Pyx_GetAttr3Default(PyObject *d) { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign if (unlikely(!__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) @@ -6009,34 +6006,42 @@ } /* GetModuleGlobalName */ - static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { +#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)) { - Py_INCREF(result); + return __Pyx_NewRef(result); } else if (unlikely(PyErr_Occurred())) { - result = NULL; - } else { + return NULL; + } #else result = PyDict_GetItem(__pyx_d, name); + __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) if (likely(result)) { - Py_INCREF(result); - } else { + return __Pyx_NewRef(result); + } #endif #else result = PyObject_GetItem(__pyx_d, name); - if (!result) { - PyErr_Clear(); -#endif - result = __Pyx_GetBuiltinName(name); + __PYX_UPDATE_DICT_CACHE(__pyx_d, result, *dict_cached_value, *dict_version) + if (likely(result)) { + return __Pyx_NewRef(result); } - return result; + PyErr_Clear(); +#endif + return __Pyx_GetBuiltinName(name); } /* Import */ - static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { PyObject *empty_list = 0; PyObject *module = 0; PyObject *global_dict = 0; @@ -6083,7 +6088,7 @@ if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, NULL); + name, global_dict, empty_dict, list, py_level, (PyObject *)NULL); Py_DECREF(py_level); #else module = PyImport_ImportModuleLevelObject( @@ -6101,7 +6106,7 @@ } /* ImportFrom */ - static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { +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, @@ -6115,7 +6120,7 @@ } /* HasAttr */ - static CYTHON_INLINE int __Pyx_HasAttr(PyObject *o, PyObject *n) { +static CYTHON_INLINE int __Pyx_HasAttr(PyObject *o, PyObject *n) { PyObject *r; if (unlikely(!__Pyx_PyBaseString_Check(n))) { PyErr_SetString(PyExc_TypeError, @@ -6133,7 +6138,7 @@ } /* PyObject_GenericGetAttrNoDict */ - #if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 +#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 @@ -6173,7 +6178,7 @@ #endif /* PyObject_GenericGetAttr */ - #if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 +#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); @@ -6183,7 +6188,7 @@ #endif /* SetVTable */ - static int __Pyx_SetVtable(PyObject *dict, void *vtable) { +static int __Pyx_SetVtable(PyObject *dict, void *vtable) { #if PY_VERSION_HEX >= 0x02070000 PyObject *ob = PyCapsule_New(vtable, 0, 0); #else @@ -6201,7 +6206,7 @@ } /* SetupReduce */ - static int __Pyx_setup_reduce_is_named(PyObject* meth, PyObject* name) { +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); @@ -6277,18 +6282,23 @@ } /* CLineInTraceback */ - #ifndef CYTHON_CLINE_IN_TRACEBACK -static int __Pyx_CLineForTraceback(CYTHON_UNUSED PyThreadState *tstate, int c_line) { +#ifndef CYTHON_CLINE_IN_TRACEBACK +static int __Pyx_CLineForTraceback(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)) { - use_cline = __Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_n_s_cline_in_traceback); + __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 { @@ -6305,7 +6315,7 @@ c_line = 0; PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False); } - else if (PyObject_Not(use_cline) != 0) { + else if (use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { c_line = 0; } __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); @@ -6314,7 +6324,7 @@ #endif /* CodeObjectCache */ - static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { +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; @@ -6394,7 +6404,7 @@ } /* AddTraceback */ - #include "compile.h" +#include "compile.h" #include "frameobject.h" #include "traceback.h" static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( @@ -6479,8 +6489,8 @@ } /* CIntToPy */ - static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { - const int neg_one = (int) -1, const_zero = (int) 0; +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { + const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(int) < sizeof(long)) { @@ -6510,7 +6520,7 @@ } /* CIntFromPyVerify */ - #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ +#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) @@ -6532,8 +6542,8 @@ } /* CIntToPy */ - static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { - const long neg_one = (long) -1, const_zero = (long) 0; +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { + const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(long) < sizeof(long)) { @@ -6563,8 +6573,8 @@ } /* CIntFromPy */ - static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { - const long neg_one = (long) -1, const_zero = (long) 0; +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { + const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { @@ -6752,8 +6762,8 @@ } /* CIntFromPy */ - static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { - const int neg_one = (int) -1, const_zero = (int) 0; +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { + const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { @@ -6941,7 +6951,7 @@ } /* FastTypeChecks */ - #if CYTHON_COMPILING_IN_CPYTHON +#if CYTHON_COMPILING_IN_CPYTHON static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { while (a) { a = a->tp_base; @@ -6996,14 +7006,42 @@ 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) { @@ -7138,6 +7176,13 @@ 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)) { @@ -7215,7 +7260,7 @@ if (sizeof(Py_ssize_t) >= sizeof(long)) return PyInt_AS_LONG(b); else - return PyInt_AsSsize_t(x); + return PyInt_AsSsize_t(b); } #endif if (likely(PyLong_CheckExact(b))) { @@ -7269,6 +7314,9 @@ 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); } diff -Nru python-aiohttp-3.1.3/aiohttp/frozenlist.py python-aiohttp-3.5.1/aiohttp/frozenlist.py --- python-aiohttp-3.1.3/aiohttp/frozenlist.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/frozenlist.py 2018-12-24 20:58:54.000000000 +0000 @@ -4,15 +4,8 @@ from .helpers import NO_EXTENSIONS -if not NO_EXTENSIONS: - try: - from aiohttp._frozenlist import FrozenList - except ImportError: # pragma: no cover - FrozenList = None - - @total_ordering -class PyFrozenList(MutableSequence): +class FrozenList(MutableSequence): __slots__ = ('_frozen', '_items') @@ -69,5 +62,11 @@ self._items) -if NO_EXTENSIONS or FrozenList is None: - FrozenList = PyFrozenList +PyFrozenList = FrozenList + +try: + from aiohttp._frozenlist import FrozenList as CFrozenList # type: ignore + if not NO_EXTENSIONS: + FrozenList = CFrozenList # type: ignore +except ImportError: # pragma: no cover + pass diff -Nru python-aiohttp-3.1.3/aiohttp/frozenlist.pyi python-aiohttp-3.5.1/aiohttp/frozenlist.pyi --- python-aiohttp-3.1.3/aiohttp/frozenlist.pyi 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/frozenlist.pyi 2018-12-24 20:58:54.000000000 +0000 @@ -0,0 +1,54 @@ +from typing import (Generic, Iterable, Iterator, List, MutableSequence, + Optional, TypeVar, Union, overload) + +_T = TypeVar('_T') +_Arg = Union[List[_T], Iterable[_T]] + + +class FrozenList(MutableSequence[_T], Generic[_T]): + + def __init__(self, items: Optional[_Arg[_T]]=None) -> None: ... + + @property + def frozen(self) -> bool: ... + + def freeze(self) -> None: ... + + @overload + def __getitem__(self, i: int) -> _T: ... + + @overload + def __getitem__(self, s: slice) -> FrozenList[_T]: ... + + @overload + def __setitem__(self, i: int, o: _T) -> None: ... + + @overload + def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... + + @overload + def __delitem__(self, i: int) -> None: ... + + @overload + def __delitem__(self, i: slice) -> None: ... + + def __len__(self) -> int: ... + + def __iter__(self) -> Iterator[_T]: ... + + def __reversed__(self) -> Iterator[_T]: ... + + def __eq__(self, other: object) -> bool: ... + def __le__(self, other: FrozenList[_T]) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __lt__(self, other: FrozenList[_T]) -> bool: ... + def __ge__(self, other: FrozenList[_T]) -> bool: ... + def __gt__(self, other: FrozenList[_T]) -> bool: ... + + def insert(self, pos: int, item: _T) -> None: ... + + def __repr__(self) -> str: ... + + +# types for C accelerators are the same +CFrozenList = PyFrozenList = FrozenList diff -Nru python-aiohttp-3.1.3/aiohttp/hdrs.py python-aiohttp-3.5.1/aiohttp/hdrs.py --- python-aiohttp-3.1.3/aiohttp/hdrs.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/hdrs.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,4 +1,8 @@ """HTTP Headers constants.""" + +# After changing the file content call ./tools/gen.py +# to regenerate the headers parser + from multidict import istr @@ -17,81 +21,81 @@ METH_OPTIONS, METH_PATCH, METH_POST, METH_PUT, METH_TRACE} -ACCEPT = istr('ACCEPT') -ACCEPT_CHARSET = istr('ACCEPT-CHARSET') -ACCEPT_ENCODING = istr('ACCEPT-ENCODING') -ACCEPT_LANGUAGE = istr('ACCEPT-LANGUAGE') -ACCEPT_RANGES = istr('ACCEPT-RANGES') -ACCESS_CONTROL_MAX_AGE = istr('ACCESS-CONTROL-MAX-AGE') -ACCESS_CONTROL_ALLOW_CREDENTIALS = istr('ACCESS-CONTROL-ALLOW-CREDENTIALS') -ACCESS_CONTROL_ALLOW_HEADERS = istr('ACCESS-CONTROL-ALLOW-HEADERS') -ACCESS_CONTROL_ALLOW_METHODS = istr('ACCESS-CONTROL-ALLOW-METHODS') -ACCESS_CONTROL_ALLOW_ORIGIN = istr('ACCESS-CONTROL-ALLOW-ORIGIN') -ACCESS_CONTROL_EXPOSE_HEADERS = istr('ACCESS-CONTROL-EXPOSE-HEADERS') -ACCESS_CONTROL_REQUEST_HEADERS = istr('ACCESS-CONTROL-REQUEST-HEADERS') -ACCESS_CONTROL_REQUEST_METHOD = istr('ACCESS-CONTROL-REQUEST-METHOD') -AGE = istr('AGE') -ALLOW = istr('ALLOW') -AUTHORIZATION = istr('AUTHORIZATION') -CACHE_CONTROL = istr('CACHE-CONTROL') -CONNECTION = istr('CONNECTION') -CONTENT_DISPOSITION = istr('CONTENT-DISPOSITION') -CONTENT_ENCODING = istr('CONTENT-ENCODING') -CONTENT_LANGUAGE = istr('CONTENT-LANGUAGE') -CONTENT_LENGTH = istr('CONTENT-LENGTH') -CONTENT_LOCATION = istr('CONTENT-LOCATION') -CONTENT_MD5 = istr('CONTENT-MD5') -CONTENT_RANGE = istr('CONTENT-RANGE') -CONTENT_TRANSFER_ENCODING = istr('CONTENT-TRANSFER-ENCODING') -CONTENT_TYPE = istr('CONTENT-TYPE') -COOKIE = istr('COOKIE') -DATE = istr('DATE') -DESTINATION = istr('DESTINATION') -DIGEST = istr('DIGEST') -ETAG = istr('ETAG') -EXPECT = istr('EXPECT') -EXPIRES = istr('EXPIRES') -FORWARDED = istr('FORWARDED') -FROM = istr('FROM') -HOST = istr('HOST') -IF_MATCH = istr('IF-MATCH') -IF_MODIFIED_SINCE = istr('IF-MODIFIED-SINCE') -IF_NONE_MATCH = istr('IF-NONE-MATCH') -IF_RANGE = istr('IF-RANGE') -IF_UNMODIFIED_SINCE = istr('IF-UNMODIFIED-SINCE') -KEEP_ALIVE = istr('KEEP-ALIVE') -LAST_EVENT_ID = istr('LAST-EVENT-ID') -LAST_MODIFIED = istr('LAST-MODIFIED') -LINK = istr('LINK') -LOCATION = istr('LOCATION') -MAX_FORWARDS = istr('MAX-FORWARDS') -ORIGIN = istr('ORIGIN') -PRAGMA = istr('PRAGMA') -PROXY_AUTHENTICATE = istr('PROXY_AUTHENTICATE') -PROXY_AUTHORIZATION = istr('PROXY-AUTHORIZATION') -RANGE = istr('RANGE') -REFERER = istr('REFERER') -RETRY_AFTER = istr('RETRY-AFTER') -SEC_WEBSOCKET_ACCEPT = istr('SEC-WEBSOCKET-ACCEPT') -SEC_WEBSOCKET_VERSION = istr('SEC-WEBSOCKET-VERSION') -SEC_WEBSOCKET_PROTOCOL = istr('SEC-WEBSOCKET-PROTOCOL') -SEC_WEBSOCKET_EXTENSIONS = istr('SEC-WEBSOCKET-EXTENSIONS') -SEC_WEBSOCKET_KEY = istr('SEC-WEBSOCKET-KEY') -SEC_WEBSOCKET_KEY1 = istr('SEC-WEBSOCKET-KEY1') -SERVER = istr('SERVER') -SET_COOKIE = istr('SET-COOKIE') +ACCEPT = istr('Accept') +ACCEPT_CHARSET = istr('Accept-Charset') +ACCEPT_ENCODING = istr('Accept-Encoding') +ACCEPT_LANGUAGE = istr('Accept-Language') +ACCEPT_RANGES = istr('Accept-Ranges') +ACCESS_CONTROL_MAX_AGE = istr('Access-Control-Max-Age') +ACCESS_CONTROL_ALLOW_CREDENTIALS = istr('Access-Control-Allow-Credentials') +ACCESS_CONTROL_ALLOW_HEADERS = istr('Access-Control-Allow-Headers') +ACCESS_CONTROL_ALLOW_METHODS = istr('Access-Control-Allow-Methods') +ACCESS_CONTROL_ALLOW_ORIGIN = istr('Access-Control-Allow-Origin') +ACCESS_CONTROL_EXPOSE_HEADERS = istr('Access-Control-Expose-Headers') +ACCESS_CONTROL_REQUEST_HEADERS = istr('Access-Control-Request-Headers') +ACCESS_CONTROL_REQUEST_METHOD = istr('Access-Control-Request-Method') +AGE = istr('Age') +ALLOW = istr('Allow') +AUTHORIZATION = istr('Authorization') +CACHE_CONTROL = istr('Cache-Control') +CONNECTION = istr('Connection') +CONTENT_DISPOSITION = istr('Content-Disposition') +CONTENT_ENCODING = istr('Content-Encoding') +CONTENT_LANGUAGE = istr('Content-Language') +CONTENT_LENGTH = istr('Content-Length') +CONTENT_LOCATION = istr('Content-Location') +CONTENT_MD5 = istr('Content-MD5') +CONTENT_RANGE = istr('Content-Range') +CONTENT_TRANSFER_ENCODING = istr('Content-Transfer-Encoding') +CONTENT_TYPE = istr('Content-Type') +COOKIE = istr('Cookie') +DATE = istr('Date') +DESTINATION = istr('Destination') +DIGEST = istr('Digest') +ETAG = istr('Etag') +EXPECT = istr('Expect') +EXPIRES = istr('Expires') +FORWARDED = istr('Forwarded') +FROM = istr('From') +HOST = istr('Host') +IF_MATCH = istr('If-Match') +IF_MODIFIED_SINCE = istr('If-Modified-Since') +IF_NONE_MATCH = istr('If-None-Match') +IF_RANGE = istr('If-Range') +IF_UNMODIFIED_SINCE = istr('If-Unmodified-Since') +KEEP_ALIVE = istr('Keep-Alive') +LAST_EVENT_ID = istr('Last-Event-ID') +LAST_MODIFIED = istr('Last-Modified') +LINK = istr('Link') +LOCATION = istr('Location') +MAX_FORWARDS = istr('Max-Forwards') +ORIGIN = istr('Origin') +PRAGMA = istr('Pragma') +PROXY_AUTHENTICATE = istr('Proxy-Authenticate') +PROXY_AUTHORIZATION = istr('Proxy-Authorization') +RANGE = istr('Range') +REFERER = istr('Referer') +RETRY_AFTER = istr('Retry-After') +SEC_WEBSOCKET_ACCEPT = istr('Sec-WebSocket-Accept') +SEC_WEBSOCKET_VERSION = istr('Sec-WebSocket-Version') +SEC_WEBSOCKET_PROTOCOL = istr('Sec-WebSocket-Protocol') +SEC_WEBSOCKET_EXTENSIONS = istr('Sec-WebSocket-Extensions') +SEC_WEBSOCKET_KEY = istr('Sec-WebSocket-Key') +SEC_WEBSOCKET_KEY1 = istr('Sec-WebSocket-Key1') +SERVER = istr('Server') +SET_COOKIE = istr('Set-Cookie') TE = istr('TE') -TRAILER = istr('TRAILER') -TRANSFER_ENCODING = istr('TRANSFER-ENCODING') -UPGRADE = istr('UPGRADE') -WEBSOCKET = istr('WEBSOCKET') +TRAILER = istr('Trailer') +TRANSFER_ENCODING = istr('Transfer-Encoding') +UPGRADE = istr('Upgrade') +WEBSOCKET = istr('WebSocket') URI = istr('URI') -USER_AGENT = istr('USER-AGENT') -VARY = istr('VARY') -VIA = istr('VIA') -WANT_DIGEST = istr('WANT-DIGEST') -WARNING = istr('WARNING') -WWW_AUTHENTICATE = istr('WWW-AUTHENTICATE') -X_FORWARDED_FOR = istr('X-FORWARDED-FOR') -X_FORWARDED_HOST = istr('X-FORWARDED-HOST') -X_FORWARDED_PROTO = istr('X-FORWARDED-PROTO') +USER_AGENT = istr('User-Agent') +VARY = istr('Vary') +VIA = istr('Via') +WANT_DIGEST = istr('Want-Digest') +WARNING = istr('Warning') +WWW_AUTHENTICATE = istr('WWW-Authenticate') +X_FORWARDED_FOR = istr('X-Forwarded-For') +X_FORWARDED_HOST = istr('X-Forwarded-Host') +X_FORWARDED_PROTO = istr('X-Forwarded-Proto') diff -Nru python-aiohttp-3.1.3/aiohttp/_headers.pxi python-aiohttp-3.5.1/aiohttp/_headers.pxi --- python-aiohttp-3.1.3/aiohttp/_headers.pxi 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/_headers.pxi 2018-12-24 20:58:54.000000000 +0000 @@ -0,0 +1,84 @@ +# 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.UPGRADE, + hdrs.URI, + hdrs.USER_AGENT, + hdrs.VARY, + hdrs.VIA, + hdrs.WANT_DIGEST, + hdrs.WARNING, + hdrs.WEBSOCKET, + hdrs.WWW_AUTHENTICATE, + hdrs.X_FORWARDED_FOR, + hdrs.X_FORWARDED_HOST, + hdrs.X_FORWARDED_PROTO, +) diff -Nru python-aiohttp-3.1.3/aiohttp/_helpers.c python-aiohttp-3.5.1/aiohttp/_helpers.c --- python-aiohttp-3.1.3/aiohttp/_helpers.c 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/_helpers.c 2018-12-24 20:59:10.000000000 +0000 @@ -0,0 +1,5312 @@ +/* Generated by Cython 0.29.2 */ + +/* BEGIN: Cython Metadata +{ + "distutils": { + "name": "aiohttp._helpers", + "sources": [ + "aiohttp/_helpers.pyx" + ] + }, + "module_name": "aiohttp._helpers" +} +END: Cython Metadata */ + +#define 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_2" +#define CYTHON_HEX_VERSION 0x001D02F0 +#define CYTHON_FUTURE_DIVISION 0 +#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" + #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 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_USE_DICT_VERSIONS +#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);\ + }\ + } +#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 +#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; // PyThread_create_key reports success always +} +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 // TSS (Thread Specific Storage) API +#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 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #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) + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) +#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 + #define PyObject_Unicode PyObject_Str +#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 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) ? PyMethod_New(func, self) : (Py_INCREF(func), 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_ERR(f_index, lineno, Ln_error) \ +{ \ + __pyx_filename = __pyx_f[f_index]; __pyx_lineno = lineno; __pyx_clineno = __LINE__; 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_DEFAULT 0 +#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, int 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 *); + +/* 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 + +/* 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); + +/* 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 '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_s_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_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; + __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; + __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; + __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_13); __pyx_t_13 = 0; + __Pyx_XDECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 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; + __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; + __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; + __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; + 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; + __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, -1); 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; + __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*/ + 0, /*tp_print*/ + 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 +}; + +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_s_reified_property_is_read_only, __pyx_k_reified_property_is_read_only, sizeof(__pyx_k_reified_property_is_read_only), 0, 0, 1, 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_s_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 + __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) + __pyx_type_7aiohttp_8_helpers_reify.tp_print = 0; + 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; +} + + +#if PY_MAJOR_VERSION < 3 +#ifdef CYTHON_NO_PYINIT_EXPORT +#define __Pyx_PyMODINIT_FUNC void +#else +#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC +#endif +#else +#ifdef CYTHON_NO_PYINIT_EXPORT +#define __Pyx_PyMODINIT_FUNC PyObject * +#else +#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC +#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; + __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(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + #ifdef WITH_THREAD /* Python build with threading support? */ + PyEval_InitThreads(); + #endif + #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) + __pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); + #endif + 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)) goto __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_CheckExact(key)) || 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 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(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 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(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, int 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, nargs, + k, (int)nk, + d, (int)nd, kwdefs, closure); +#else + result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL, + args, 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 = func->ob_type->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 (PyCFunction_GET_FLAGS(func) & METH_FASTCALL) { + 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); +} + +/* 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 (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 + +/* 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 GOOD; +#else + if (PyObject_HasAttr(type_obj, __pyx_n_s_getstate)) goto GOOD; +#endif +#if CYTHON_USE_PYTYPE_LOOKUP + object_reduce_ex = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto BAD; +#else + object_reduce_ex = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto BAD; +#endif + reduce_ex = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce_ex); if (unlikely(!reduce_ex)) goto 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 BAD; +#else + object_reduce = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce); if (!object_reduce) goto BAD; +#endif + reduce = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce); if (unlikely(!reduce)) goto BAD; + if (reduce == object_reduce || __Pyx_setup_reduce_is_named(reduce, __pyx_n_s_reduce_cython)) { + reduce_cython = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce_cython); if (unlikely(!reduce_cython)) goto BAD; + ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce, reduce_cython); if (unlikely(ret < 0)) goto BAD; + ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce_cython); if (unlikely(ret < 0)) goto 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_GetAttrStr(type_obj, __pyx_n_s_setstate_cython); if (unlikely(!setstate_cython)) goto BAD; + ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate, setstate_cython); if (unlikely(ret < 0)) goto BAD; + ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate_cython); if (unlikely(ret < 0)) goto BAD; + } + PyType_Modified((PyTypeObject*)type_obj); + } + } + goto GOOD; +BAD: + if (!PyErr_Occurred()) + PyErr_Format(PyExc_RuntimeError, "Unable to initialize pickling for %s", ((PyTypeObject*)type_obj)->tp_name); + ret = -1; +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(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_long(long value) { + const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0; + 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 long __Pyx_PyInt_As_long(PyObject *x) { + const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0; + 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) { + const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 0; + 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 -Nru python-aiohttp-3.1.3/aiohttp/helpers.py python-aiohttp-3.5.1/aiohttp/helpers.py --- python-aiohttp-3.1.3/aiohttp/helpers.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/helpers.py 2018-12-24 20:58:54.000000000 +0000 @@ -4,33 +4,38 @@ 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 math import ceil from pathlib import Path +from types import TracebackType +from typing import (Any, Callable, Dict, Iterable, Iterator, List, # noqa + Mapping, Optional, Pattern, Set, Tuple, Type, TypeVar, + Union, cast) from urllib.parse import quote from urllib.request import getproxies import async_timeout import attr -from multidict import MultiDict +from multidict import MultiDict, MultiDictProxy from yarl import URL from . import hdrs -from .abc import AbstractAccessLogger -from .log import client_logger +from .log import client_logger, internal_logger +from .typedefs import PathLike # noqa -__all__ = ('BasicAuth',) +__all__ = ('BasicAuth', 'ChainMapProxy') PY_36 = sys.version_info >= (3, 6) PY_37 = sys.version_info >= (3, 7) @@ -39,15 +44,29 @@ import idna_ssl idna_ssl.patch_match_hostname() +try: + from typing import ContextManager +except ImportError: + from typing_extensions import ContextManager -sentinel = object() -NO_EXTENSIONS = bool(os.environ.get('AIOHTTP_NO_EXTENSIONS')) + +all_tasks = asyncio.Task.all_tasks + +if PY_37: + all_tasks = getattr(asyncio, 'all_tasks') # use the trick to cheat mypy + + +_T = TypeVar('_T') + + +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')))) + bool(os.environ.get('PYTHONASYNCIODEBUG')))) # type: bool CHAR = set(chr(i) for i in range(0, 128)) @@ -58,24 +77,30 @@ coroutines = asyncio.coroutines -old_debug = coroutines._DEBUG +old_debug = coroutines._DEBUG # type: ignore # prevent "coroutine noop was never awaited" warning. -coroutines._DEBUG = False +coroutines._DEBUG = False # type: ignore @asyncio.coroutine -def noop(*args, **kwargs): +def noop(*args, **kwargs): # type: ignore + return # type: ignore + + +async def noop2(*args: Any, **kwargs: Any) -> None: return -coroutines._DEBUG = old_debug +coroutines._DEBUG = old_debug # type: ignore class BasicAuth(namedtuple('BasicAuth', ['login', 'password', 'encoding'])): """Http basic authentication helper.""" - def __new__(cls, login, password='', encoding='latin1'): + def __new__(cls, login: str, + password: str='', + encoding: str='latin1') -> 'BasicAuth': if login is None: raise ValueError('None is not allowed as login value') @@ -89,27 +114,37 @@ return super().__new__(cls, login, password, encoding) @classmethod - def decode(cls, auth_header, encoding='latin1'): + def decode(cls, auth_header: str, encoding: str='latin1') -> 'BasicAuth': """Create a BasicAuth object from an Authorization HTTP header.""" - split = auth_header.strip().split(' ') - if len(split) == 2: - if split[0].strip().lower() != 'basic': - raise ValueError('Unknown authorization method %s' % split[0]) - to_decode = split[1] - else: + 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: - username, _, password = base64.b64decode( - to_decode.encode('ascii') - ).decode(encoding).partition(':') + 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, *, encoding='latin1'): + 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") @@ -117,13 +152,13 @@ return None return cls(url.user, url.password or '', encoding=encoding) - def encode(self): + def encode(self) -> str: """Encode credentials.""" creds = ('%s:%s' % (self.login, self.password)).encode(self.encoding) return 'Basic %s' % base64.b64encode(creds).decode(self.encoding) -def strip_auth_from_url(url): +def strip_auth_from_url(url: URL) -> Tuple[URL, Optional[BasicAuth]]: auth = BasicAuth.from_url(url) if auth is None: return url, None @@ -131,40 +166,49 @@ return url.with_user(None), auth -def netrc_from_env(): - netrc_obj = None - netrc_path = os.environ.get('NETRC') - try: - if netrc_path is not None: - netrc_path = Path(netrc_path) - else: +def netrc_from_env() -> Optional[netrc.netrc]: + """Attempt to load the netrc file 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() - if os.name == 'nt': # pragma: no cover - netrc_path = home_dir.joinpath('_netrc') - else: - netrc_path = home_dir.joinpath('.netrc') + 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 - if netrc_path and netrc_path.is_file(): - try: - netrc_obj = netrc.netrc(str(netrc_path)) - except (netrc.NetrcParseError, OSError) as e: - client_logger.warning(".netrc file parses fail: %s", e) - - if netrc_obj is None: - client_logger.warning("could't find .netrc file") - except RuntimeError as e: # pragma: no cover - """ handle error raised by pathlib """ - client_logger.warning("could't find .netrc file: %s", e) - return netrc_obj + netrc_path = home_dir / ( + '_netrc' if platform.system() == '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(frozen=True, slots=True) class ProxyInfo: - proxy = attr.ib(type=str) - proxy_auth = attr.ib(type=BasicAuth) + proxy = attr.ib(type=URL) + proxy_auth = attr.ib(type=Optional[BasicAuth]) -def proxies_from_env(): +def proxies_from_env() -> Dict[str, ProxyInfo]: proxy_urls = {k: URL(v) for k, v in getproxies().items() if k in ('http', 'https')} netrc_obj = netrc_from_env() @@ -177,38 +221,48 @@ "HTTPS proxies %s are not supported, ignoring", proxy) continue if netrc_obj and auth is None: - auth_from_netrc = netrc_obj.authenticators(proxy.host) + 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 - auth = BasicAuth(logins[0] if logins[0] else logins[-1], - password) + 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=None): - if loop is None: - loop = asyncio.get_event_loop() - +def current_task(loop: Optional[asyncio.AbstractEventLoop]=None) -> asyncio.Task: # type: ignore # noqa # Return type is intentionally Generic here if PY_37: - task = asyncio.current_task(loop=loop) + return asyncio.current_task(loop=loop) # type: ignore else: - task = asyncio.Task.current_task(loop=loop) - if task is None: - # this should be removed, tokio must use register_task and family API - if hasattr(loop, 'current_task'): - task = loop.current_task() - - return task + return asyncio.Task.current_task(loop=loop) # type: ignore + +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 from async function", + DeprecationWarning, stacklevel=3) + if loop.get_debug(): + internal_logger.warning( + "The object should be created from async function", + stack_info=True) + return loop -def isasyncgenfunction(obj): - if hasattr(inspect, 'isasyncgenfunction'): - return inspect.isasyncgenfunction(obj) - return False + +def isasyncgenfunction(obj: Any) -> bool: + func = getattr(inspect, 'isasyncgenfunction', None) + if func is not None: + return func(obj) + else: + return False @attr.s(frozen=True, slots=True) @@ -216,10 +270,11 @@ type = attr.ib(type=str) subtype = attr.ib(type=str) suffix = attr.ib(type=str) - parameters = attr.ib(type=MultiDict) + parameters = attr.ib(type=MultiDictProxy) # type: MultiDictProxy[str] -def parse_mimetype(mimetype): +@functools.lru_cache(maxsize=56) +def parse_mimetype(mimetype: str) -> MimeType: """Parses a MIME type into its components. mimetype is a MIME type string. @@ -234,37 +289,41 @@ """ if not mimetype: - return MimeType(type='', subtype='', suffix='', parameters={}) + return MimeType(type='', subtype='', suffix='', + parameters=MultiDictProxy(MultiDict())) parts = mimetype.split(';') - params = [] + params = MultiDict() # type: MultiDict[str] for item in parts[1:]: if not item: continue - key, value = item.split('=', 1) if '=' in item else (item, '') - params.append((key.lower().strip(), value.strip(' "'))) - params = MultiDict(params) + 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 = fulltype.split('/', 1) \ - if '/' in fulltype else (fulltype, '') - stype, suffix = stype.split('+', 1) if '+' in stype else (stype, '') + 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=params) + parameters=MultiDictProxy(params)) -def guess_filename(obj, default=None): +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 -def content_disposition_header(disptype, quote_fields=True, **params): +def content_disposition_header(disptype: str, + quote_fields: bool=True, + **params: str) -> str: """Sets ``Content-Disposition`` header. disptype is a disposition type: inline, attachment, form-data. @@ -292,192 +351,6 @@ return value -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 = {} - - KeyMethod = namedtuple('KeyMethod', 'key method') - - def __init__(self, logger, log_format=LOG_FORMAT): - """Initialise the logger. - - logger is a logger object to be used for logging. - log_format is an 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): - """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_key = self.LOG_FORMAT_MAP[atom[0]] - m = getattr(AccessLogger, '_format_%s' % atom[0]) - else: - format_key = (self.LOG_FORMAT_MAP[atom[2]], atom[1]) - m = getattr(AccessLogger, '_format_%s' % atom[2]) - m = functools.partial(m, atom[1]) - - methods.append(self.KeyMethod(format_key, m)) - - 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, request, response, time): - if request is None: - return '(no headers)' - - # suboptimal, make istr(key) once - return request.headers.get(key, '-') - - @staticmethod - def _format_o(key, request, response, time): - # suboptimal, make istr(key) once - return response.headers.get(key, '-') - - @staticmethod - def _format_a(request, response, time): - if request is None: - return '-' - ip = request.remote - return ip if ip is not None else '-' - - @staticmethod - def _format_t(request, response, time): - 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, response, time): - return "<%s>" % os.getpid() - - @staticmethod - def _format_r(request, response, time): - if request is None: - return '-' - return '%s %s HTTP/%s.%s' % tuple((request.method, - request.path_qs) + request.version) - - @staticmethod - def _format_s(request, response, time): - return response.status - - @staticmethod - def _format_b(request, response, time): - return response.body_length - - @staticmethod - def _format_T(request, response, time): - return round(time) - - @staticmethod - def _format_Tf(request, response, time): - return '%06f' % time - - @staticmethod - def _format_D(request, response, time): - return round(time * 1000000) - - def _format_line(self, request, response, time): - return ((key, method(request, response, time)) - for key, method in self._methods) - - def log(self, request, response, time): - 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 - dct = extra.get(k1, {}) - dct[k2] = value - extra[k1] = dct - - self.logger.info(self._log_format % tuple(values), extra=extra) - except Exception: - self.logger.exception("Error in logging") - - class reify: """Use as a class method decorator. It operates almost exactly like the Python `@property` decorator, but it puts the result of the @@ -487,15 +360,12 @@ """ - def __init__(self, wrapped): + def __init__(self, wrapped: Callable[..., Any]) -> None: self.wrapped = wrapped - try: - self.__doc__ = wrapped.__doc__ - except Exception: # pragma: no cover - self.__doc__ = "" + self.__doc__ = wrapped.__doc__ self.name = wrapped.__name__ - def __get__(self, inst, owner, _sentinel=sentinel): + def __get__(self, inst: Any, owner: Any) -> Any: try: try: return inst._cache[self.name] @@ -508,10 +378,19 @@ return self raise - def __set__(self, inst, value): + def __set__(self, inst: Any, value: Any) -> 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 +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 = ( @@ -529,29 +408,34 @@ _ipv6_regexb = re.compile(_ipv6_pattern.encode('ascii'), flags=re.IGNORECASE) -def is_ip_address(host): +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): - if _ipv4_regex.match(host) or _ipv6_regex.match(host): - return True - else: - return False + return bool(regex.match(host)) elif isinstance(host, (bytes, bytearray, memoryview)): - if _ipv4_regexb.match(host) or _ipv6_regexb.match(host): - return True - else: - return False + return bool(regexb.match(host)) else: raise TypeError("{} [{}] is not a str or bytes" .format(host, type(host))) +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) + + _cached_current_datetime = None _cached_formatted_datetime = None -def rfc822_formatted_time(): +def rfc822_formatted_time() -> str: global _cached_current_datetime global _cached_formatted_datetime @@ -565,15 +449,15 @@ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") - year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now) + year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now) # type: ignore # noqa _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 + return _cached_formatted_datetime # type: ignore -def _weakref_handle(info): +def _weakref_handle(info): # type: ignore ref, name = info ob = ref() if ob is not None: @@ -581,7 +465,7 @@ getattr(ob, name)() -def weakref_handle(ob, name, timeout, loop, ceil_timeout=True): +def weakref_handle(ob, name, timeout, loop, ceil_timeout=True): # type: ignore if timeout is not None and timeout > 0: when = loop.time() + timeout if ceil_timeout: @@ -590,7 +474,7 @@ return loop.call_at(when, _weakref_handle, (weakref.ref(ob), name)) -def call_later(cb, timeout, loop): +def call_later(cb, timeout, loop): # type: ignore if timeout is not None and timeout > 0: when = ceil(loop.time() + timeout) return loop.call_at(when, cb) @@ -599,31 +483,36 @@ class TimeoutHandle: """ Timeout handle """ - def __init__(self, loop, timeout): + def __init__(self, + loop: asyncio.AbstractEventLoop, + timeout: Optional[float]) -> None: self._timeout = timeout self._loop = loop - self._callbacks = [] + self._callbacks = [] # type: List[Tuple[Callable[..., None], Tuple[Any, ...], Dict[str, Any]]] # noqa - def register(self, callback, *args, **kwargs): + def register(self, callback: Callable[..., None], + *args: Any, **kwargs: Any) -> None: self._callbacks.append((callback, args, kwargs)) - def close(self): + def close(self) -> None: self._callbacks.clear() - def start(self): + def start(self) -> Optional[asyncio.Handle]: if self._timeout is not None and self._timeout > 0: at = ceil(self._loop.time() + self._timeout) return self._loop.call_at(at, self.__call__) + else: + return None - def timer(self): + 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: - timer = TimerNoop() - return timer + return TimerNoop() - def __call__(self): + def __call__(self) -> None: for cb, args, kwargs in self._callbacks: with suppress(Exception): cb(*args, **kwargs) @@ -631,24 +520,30 @@ self._callbacks.clear() -class TimerNoop: +class BaseTimerContext(ContextManager['BaseTimerContext']): + pass + - def __enter__(self): +class TimerNoop(BaseTimerContext): + + def __enter__(self) -> BaseTimerContext: return self - def __exit__(self, exc_type, exc_val, exc_tb): + def __exit__(self, exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType]) -> Optional[bool]: return False -class TimerContext: +class TimerContext(BaseTimerContext): """ Low resolution timeout context manager """ - def __init__(self, loop): + def __init__(self, loop: asyncio.AbstractEventLoop) -> None: self._loop = loop - self._tasks = [] + self._tasks = [] # type: List[asyncio.Task[Any]] self._cancelled = False - def __enter__(self): + def __enter__(self) -> BaseTimerContext: task = current_task(loop=self._loop) if task is None: @@ -662,14 +557,17 @@ self._tasks.append(task) return self - def __exit__(self, exc_type, exc_val, exc_tb): + 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): + def timeout(self) -> None: if not self._cancelled: for task in set(self._tasks): task.cancel() @@ -679,7 +577,7 @@ class CeilTimeout(async_timeout.timeout): - def __enter__(self): + def __enter__(self) -> async_timeout.timeout: if self._timeout is not None: self._task = current_task(loop=self._loop) if self._task is None: @@ -695,11 +593,11 @@ ATTRS = frozenset([ '_content_type', '_content_dict', '_stored_content_type']) - _content_type = None - _content_dict = None + _content_type = None # type: Optional[str] + _content_dict = None # type: Optional[Dict[str, str]] _stored_content_type = sentinel - def _parse_content_type(self, raw): + def _parse_content_type(self, raw: str) -> None: self._stored_content_type = raw if raw is None: # default value according to RFC 2616 @@ -709,35 +607,80 @@ self._content_type, self._content_dict = cgi.parse_header(raw) @property - def content_type(self, *, _CONTENT_TYPE=hdrs.CONTENT_TYPE): + def content_type(self) -> str: """The value of content part for Content-Type HTTP header.""" - raw = self._headers.get(_CONTENT_TYPE) + raw = self._headers.get(hdrs.CONTENT_TYPE) # type: ignore if self._stored_content_type != raw: self._parse_content_type(raw) - return self._content_type + return self._content_type # type: ignore @property - def charset(self, *, _CONTENT_TYPE=hdrs.CONTENT_TYPE): + def charset(self) -> Optional[str]: """The value of charset part for Content-Type HTTP header.""" - raw = self._headers.get(_CONTENT_TYPE) + raw = self._headers.get(hdrs.CONTENT_TYPE) # type: ignore if self._stored_content_type != raw: self._parse_content_type(raw) - return self._content_dict.get('charset') + return self._content_dict.get('charset') # type: ignore @property - def content_length(self, *, _CONTENT_LENGTH=hdrs.CONTENT_LENGTH): + def content_length(self) -> Optional[int]: """The value of Content-Length HTTP header.""" - content_length = self._headers.get(_CONTENT_LENGTH) + content_length = self._headers.get(hdrs.CONTENT_LENGTH) # type: ignore - if content_length: + if content_length is not None: return int(content_length) + else: + return None -def set_result(fut, result): +def set_result(fut: 'asyncio.Future[_T]', result: _T) -> None: if not fut.done(): fut.set_result(result) -def set_exception(fut, exc): +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 + + 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 'ChainMapProxy({})'.format(content) diff -Nru python-aiohttp-3.1.3/aiohttp/_helpers.pyi python-aiohttp-3.5.1/aiohttp/_helpers.pyi --- python-aiohttp-3.1.3/aiohttp/_helpers.pyi 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/_helpers.pyi 2018-12-24 20:58:54.000000000 +0000 @@ -0,0 +1,8 @@ +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 -Nru python-aiohttp-3.1.3/aiohttp/_helpers.pyx python-aiohttp-3.5.1/aiohttp/_helpers.pyx --- python-aiohttp-3.1.3/aiohttp/_helpers.pyx 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/_helpers.pyx 2018-12-24 20:58:54.000000000 +0000 @@ -0,0 +1,35 @@ +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 -Nru python-aiohttp-3.1.3/aiohttp/http_exceptions.py python-aiohttp-3.5.1/aiohttp/http_exceptions.py --- python-aiohttp-3.1.3/aiohttp/http_exceptions.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/http_exceptions.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,5 +1,11 @@ """Low-level http related exceptions.""" + +from typing import Optional, Union + +from .typedefs import _CIMultiDict + + __all__ = ('HttpProcessingError',) @@ -17,7 +23,10 @@ message = '' headers = None - def __init__(self, *, code=None, 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 @@ -31,7 +40,8 @@ code = 400 message = 'Bad Request' - def __init__(self, message, *, headers=None): + def __init__(self, message: str, *, + headers: Optional[_CIMultiDict]=None) -> None: super().__init__(message=message, headers=headers) @@ -59,7 +69,9 @@ class LineTooLong(BadHttpMessage): - def __init__(self, line, limit='Unknown', actual_size='Unknown'): + def __init__(self, line: str, + limit: str='Unknown', + actual_size: str='Unknown') -> None: super().__init__( "Got more than %s bytes (%s) when reading %s." % ( limit, actual_size, line)) @@ -67,7 +79,7 @@ class InvalidHeader(BadHttpMessage): - def __init__(self, hdr): + def __init__(self, hdr: Union[bytes, str]) -> None: if isinstance(hdr, bytes): hdr = hdr.decode('utf-8', 'surrogateescape') super().__init__('Invalid HTTP Header: {}'.format(hdr)) @@ -76,7 +88,7 @@ class BadStatusLine(BadHttpMessage): - def __init__(self, line=''): + def __init__(self, line: str='') -> None: if not line: line = repr(line) self.args = line, diff -Nru python-aiohttp-3.1.3/aiohttp/_http_parser.c python-aiohttp-3.5.1/aiohttp/_http_parser.c --- python-aiohttp-3.1.3/aiohttp/_http_parser.c 2018-04-13 10:01:36.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/_http_parser.c 2018-12-24 20:59:11.000000000 +0000 @@ -1,4 +1,4 @@ -/* Generated by Cython 0.28.1 */ +/* Generated by Cython 0.29.2 */ /* BEGIN: Cython Metadata { @@ -13,7 +13,8 @@ "name": "aiohttp._http_parser", "sources": [ "aiohttp/_http_parser.pyx", - "vendor/http-parser/http_parser.c" + "vendor/http-parser/http_parser.c", + "aiohttp/_find_header.c" ] }, "module_name": "aiohttp._http_parser" @@ -27,7 +28,8 @@ #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_28_1" +#define CYTHON_ABI "0_29_2" +#define CYTHON_HEX_VERSION 0x001D02F0 #define CYTHON_FUTURE_DIVISION 1 #include #ifndef offsetof @@ -98,6 +100,10 @@ #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 @@ -135,6 +141,10 @@ #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 @@ -188,11 +198,17 @@ #define CYTHON_FAST_PYCALL 1 #endif #ifndef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT (0 && PY_VERSION_HEX >= 0x03050000) + #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) @@ -202,6 +218,9 @@ #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 @@ -328,6 +347,9 @@ #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 @@ -341,15 +363,40 @@ #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))))) + ((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_USE_DICT_VERSIONS +#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);\ + }\ + } +#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 #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) @@ -457,8 +504,8 @@ #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)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) -#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#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 @@ -473,6 +520,7 @@ #define PyString_Type PyUnicode_Type #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact + #define PyObject_Unicode PyObject_Str #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) @@ -586,6 +634,7 @@ #include "pythread.h" #include #include "../vendor/http-parser/http_parser.h" +#include "_find_header.h" #ifdef _OPENMP #include #endif /* _OPENMP */ @@ -614,6 +663,9 @@ (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) @@ -670,8 +722,9 @@ #define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) #define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) -#define __Pyx_PyBool_FromLong(b) ((b) ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False)) +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)) @@ -752,7 +805,7 @@ 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)); + __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); @@ -778,7 +831,7 @@ static PyObject *__pyx_m = NULL; static PyObject *__pyx_d; static PyObject *__pyx_b; -static PyObject *__pyx_cython_runtime; +static PyObject *__pyx_cython_runtime = NULL; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; static PyObject *__pyx_empty_unicode; @@ -794,16 +847,22 @@ "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_HttpRequestParserC; -struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParserC; +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; -struct __pyx_opt_args_7aiohttp_12_http_parser_10HttpParser__on_headers_complete; -/* "aiohttp/_http_parser.pyx":83 +/* "aiohttp/_http_parser.pyx":308 * PyMem_Free(self._csettings) * * cdef _init(self, cparser.http_parser_type mode, # <<<<<<<<<<<<<< @@ -817,27 +876,54 @@ size_t max_headers; size_t max_field_size; PyObject *payload_exception; - PyObject *response_with_body; - PyObject *auto_decompress; + int response_with_body; + int auto_decompress; }; -/* "aiohttp/_http_parser.pyx":163 - * self._raw_header_value += raw_val +/* "aiohttp/_http_parser.pyx":93 * - * cdef _on_headers_complete(self, # <<<<<<<<<<<<<< - * ENCODING='utf-8', - * ENCODING_ERR='surrogateescape', + * @cython.freelist(DEFAULT_FREELIST_SIZE) + * cdef class RawRequestMessage: # <<<<<<<<<<<<<< + * cdef readonly str method + * cdef readonly str path */ -struct __pyx_opt_args_7aiohttp_12_http_parser_10HttpParser__on_headers_complete { - int __pyx_n; - PyObject *ENCODING; - PyObject *ENCODING_ERR; - PyObject *CONTENT_ENCODING; - PyObject *SEC_WEBSOCKET_KEY1; - PyObject *SUPPORTED; +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":193 + * + * @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":31 + +/* "aiohttp/_http_parser.pyx":255 * * @cython.internal * cdef class HttpParser: # <<<<<<<<<<<<<< @@ -849,10 +935,9 @@ struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser *__pyx_vtab; struct http_parser *_cparser; struct http_parser_settings *_csettings; - PyObject *_header_name; - PyObject *_header_value; - PyObject *_raw_header_name; - PyObject *_raw_header_value; + PyObject *_raw_name; + PyObject *_raw_value; + int _has_value; PyObject *_protocol; PyObject *_loop; PyObject *_timer; @@ -874,36 +959,93 @@ PyObject *_payload_exception; PyObject *_last_error; int _auto_decompress; + PyObject *_content_encoding; Py_buffer py_buf; }; -/* "aiohttp/_http_parser.pyx":311 +/* "aiohttp/_http_parser.pyx":537 * * - * cdef class HttpRequestParserC(HttpParser): # <<<<<<<<<<<<<< + * cdef class HttpRequestParser(HttpParser): # <<<<<<<<<<<<<< * * def __init__(self, protocol, loop, timer=None, */ -struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParserC { +struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParser { struct __pyx_obj_7aiohttp_12_http_parser_HttpParser __pyx_base; }; -/* "aiohttp/_http_parser.pyx":338 +/* "aiohttp/_http_parser.pyx":564 * * - * cdef class HttpResponseParserC(HttpParser): # <<<<<<<<<<<<<< + * cdef class HttpResponseParser(HttpParser): # <<<<<<<<<<<<<< * * def __init__(self, protocol, loop, timer=None, */ -struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParserC { +struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParser { struct __pyx_obj_7aiohttp_12_http_parser_HttpParser __pyx_base; }; +/* "aiohttp/_http_parser.pyx":118 + * 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":130 + * 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":216 + * 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":227 + * 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":31 +/* "aiohttp/_http_parser.pyx":255 * * @cython.internal * cdef class HttpParser: # <<<<<<<<<<<<<< @@ -914,43 +1056,45 @@ struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser { PyObject *(*_init)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *, enum http_parser_type, PyObject *, PyObject *, 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 *, PyObject *, PyObject *); - PyObject *(*_on_header_value)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *, PyObject *, PyObject *); - PyObject *(*_on_headers_complete)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *, struct __pyx_opt_args_7aiohttp_12_http_parser_10HttpParser__on_headers_complete *__pyx_optional_args); + 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":311 +/* "aiohttp/_http_parser.pyx":537 * * - * cdef class HttpRequestParserC(HttpParser): # <<<<<<<<<<<<<< + * cdef class HttpRequestParser(HttpParser): # <<<<<<<<<<<<<< * * def __init__(self, protocol, loop, timer=None, */ -struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpRequestParserC { +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_HttpRequestParserC *__pyx_vtabptr_7aiohttp_12_http_parser_HttpRequestParserC; +static struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpRequestParser *__pyx_vtabptr_7aiohttp_12_http_parser_HttpRequestParser; -/* "aiohttp/_http_parser.pyx":338 +/* "aiohttp/_http_parser.pyx":564 * * - * cdef class HttpResponseParserC(HttpParser): # <<<<<<<<<<<<<< + * cdef class HttpResponseParser(HttpParser): # <<<<<<<<<<<<<< * * def __init__(self, protocol, loop, timer=None, */ -struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpResponseParserC { +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_HttpResponseParserC *__pyx_vtabptr_7aiohttp_12_http_parser_HttpResponseParserC; +static struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpResponseParser *__pyx_vtabptr_7aiohttp_12_http_parser_HttpResponseParser; /* --- Runtime support code (head) --- */ /* Refnanny.proto */ @@ -1026,41 +1170,100 @@ /* 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); -/* KeywordStringCheck.proto */ -static int __Pyx_CheckKeywordStrings(PyObject *kwdict, const char* function_name, int kw_allowed); +/* RaiseDoubleKeywords.proto */ +static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); -/* 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, int nargs, PyObject *kwargs); -#else -#define __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs) _PyFunction_FastCallDict(func, args, nargs, kwargs) -#endif -#endif +/* ParseKeywords.proto */ +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\ + const char* function_name); -/* 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 +/* None.proto */ +static CYTHON_INLINE void __Pyx_RaiseClosureNameError(const char *varname); -/* PyObjectCallMethO.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); -#endif +/* RaiseTooManyValuesToUnpack.proto */ +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); -/* PyObjectCallNoArg.proto */ -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); +/* 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); + Py_SIZE(list) = len+1; + return 0; + } + return PyList_Append(list, x); +} #else -#define __Pyx_PyObject_CallNoArg(func) __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL) +#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) #endif /* ListAppend.proto */ @@ -1080,25 +1283,37 @@ #define __Pyx_PyList_Append(L,x) PyList_Append(L,x) #endif -/* GetModuleGlobalName.proto */ -static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *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 +/* KeywordStringCheck.proto */ +static int __Pyx_CheckKeywordStrings(PyObject *kwdict, const char* function_name, int kw_allowed); -/* PyObjectCallOneArg.proto */ -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); +/* ExtTypeTest.proto */ +static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); -/* PySequenceContains.proto */ -static CYTHON_INLINE int __Pyx_PySequence_ContainsTF(PyObject* item, PyObject* seq, int eq) { - int result = PySequence_Contains(seq, item); +/* 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; @@ -1135,74 +1350,111 @@ #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); - -/* 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); -} +/* GetAttr.proto */ +static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); -/* 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)); +/* GetAttr3.proto */ +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); -/* 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); -} +/* 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 -/* 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); +/* 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, int 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 -/* 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); +/* 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 -/* RaiseDoubleKeywords.proto */ -static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); +/* PyObjectCallMethO.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); +#endif -/* ParseKeywords.proto */ -static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\ - PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\ - const char* function_name); +/* 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( @@ -1230,6 +1482,11 @@ 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) @@ -1241,17 +1498,6 @@ #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 - -/* IncludeStringH.proto */ -#include - /* decode_c_string.proto */ static CYTHON_INLINE PyObject* __Pyx_decode_c_string( const char* cstring, Py_ssize_t start, Py_ssize_t stop, @@ -1275,17 +1521,14 @@ #define __Pyx_CallUnboundCMethod1(cfunc, self, arg) __Pyx__CallUnboundCMethod1(cfunc, self, arg) #endif -/* RaiseTooManyValuesToUnpack.proto */ -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); - -/* RaiseNeedMoreValuesToUnpack.proto */ -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); +/* Import.proto */ +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); -/* IterFinish.proto */ -static CYTHON_INLINE int __Pyx_IterFinish(void); +/* ImportFrom.proto */ +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); -/* UnpackItemEndCheck.proto */ -static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); +/* 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 @@ -1301,17 +1544,22 @@ #define __Pyx_PyObject_GenericGetAttr PyObject_GenericGetAttr #endif -/* SetVTable.proto */ -static int __Pyx_SetVtable(PyObject *dict, void *vtable); - /* SetupReduce.proto */ static int __Pyx_setup_reduce(PyObject* type_obj); -/* Import.proto */ -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); +/* SetVTable.proto */ +static int __Pyx_SetVtable(PyObject *dict, void *vtable); -/* ImportFrom.proto */ -static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); +/* 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 /* CLineInTraceback.proto */ #ifdef CYTHON_CLINE_IN_TRACEBACK @@ -1355,13 +1603,16 @@ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_uint16_t(uint16_t value); /* CIntFromPy.proto */ -static CYTHON_INLINE size_t __Pyx_PyInt_As_size_t(PyObject *); +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); /* CIntFromPy.proto */ -static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); +static CYTHON_INLINE enum http_method __Pyx_PyInt_As_enum__http_method(PyObject *); /* CIntFromPy.proto */ -static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); +static CYTHON_INLINE size_t __Pyx_PyInt_As_size_t(PyObject *); + +/* CIntFromPy.proto */ +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); /* FastTypeChecks.proto */ #if CYTHON_COMPILING_IN_CPYTHON @@ -1376,41 +1627,113 @@ #endif #define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) -/* CheckBinaryVersion.proto */ -static int __Pyx_check_binary_version(void); +/* FetchCommonType.proto */ +static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type); -/* PyIdentifierFromString.proto */ -#if !defined(__Pyx_PyIdentifier_FromString) -#if PY_MAJOR_VERSION < 3 - #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) +/* 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 - #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) +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; + 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); -/* ModuleImport.proto */ -static PyObject *__Pyx_ImportModule(const char *name); +/* 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); -/* TypeImport.proto */ -static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); +/* 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 http_parser_type __pyx_v_mode, PyObject *__pyx_v_protocol, PyObject *__pyx_v_loop, 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, PyObject *__pyx_v_field, PyObject *__pyx_v_raw_field); /* proto*/ -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_header_value(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self, PyObject *__pyx_v_val, PyObject *__pyx_v_raw_val); /* proto*/ -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_headers_complete(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self, struct __pyx_opt_args_7aiohttp_12_http_parser_10HttpParser__on_headers_complete *__pyx_optional_args); /* 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 PyObject *__pyx_f_7aiohttp_12_http_parser_18HttpRequestParserC__on_status_complete(struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParserC *__pyx_v_self); /* proto*/ -static PyObject *__pyx_f_7aiohttp_12_http_parser_19HttpResponseParserC__on_status_complete(struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParserC *__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.mem' */ +/* Module declarations from 'libc.string' */ + /* Module declarations from 'cpython.version' */ /* Module declarations from '__builtin__' */ @@ -1418,8 +1741,6 @@ /* 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' */ @@ -1500,11 +1821,37 @@ /* 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_HttpRequestParserC = 0; -static PyTypeObject *__pyx_ptype_7aiohttp_12_http_parser_HttpResponseParserC = 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(struct http_parser *); /*proto*/ static int __pyx_f_7aiohttp_12_http_parser_cb_on_url(struct http_parser *, char const *, size_t); /*proto*/ static int __pyx_f_7aiohttp_12_http_parser_cb_on_status(struct http_parser *, char const *, size_t); /*proto*/ @@ -1516,25 +1863,43 @@ static int __pyx_f_7aiohttp_12_http_parser_cb_on_chunk_header(struct http_parser *); /*proto*/ static int __pyx_f_7aiohttp_12_http_parser_cb_on_chunk_complete(struct http_parser *); /*proto*/ static PyObject *__pyx_f_7aiohttp_12_http_parser_parser_error_from_errno(enum http_errno); /*proto*/ +static PyObject *__pyx_f_7aiohttp_12_http_parser__parse_url(char *, size_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__6[] = ""; +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_br[] = "br"; -static const char __pyx_k_ln[] = "ln"; +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__13[] = ":"; +static const char __pyx_k_VIA[] = "VIA"; +static const char __pyx_k__11[] = ":"; +static const char __pyx_k_add[] = "add"; static const char __pyx_k_all[] = "__all__"; -static const char __pyx_k_get[] = "get"; -static const char __pyx_k_off[] = "off"; -static const char __pyx_k_res[] = "res"; -static const char __pyx_k_sep[] = "sep"; +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_host[] = "host"; @@ -1543,4798 +1908,5656 @@ static const char __pyx_k_name[] = "__name__"; static const char __pyx_k_path[] = "path"; static const char __pyx_k_port[] = "port"; +static const char __pyx_k_send[] = "send"; static const char __pyx_k_test[] = "__test__"; static const char __pyx_k_user[] = "user"; 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_clear[] = "clear"; +static const char __pyx_k_close[] = "close"; static const char __pyx_k_lower[] = "lower"; static const char __pyx_k_query[] = "query"; +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_utf_8[] = "utf-8"; -static const char __pyx_k_decode[] = "decode"; -static const char __pyx_k_extend[] = "extend"; +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_format[] = "format"; static const char __pyx_k_import[] = "__import__"; -static const char __pyx_k_length[] = "length"; -static const char __pyx_k_parsed[] = "parsed"; +static const char __pyx_k_method[] = "method"; +static const char __pyx_k_pickle[] = "pickle"; static const char __pyx_k_py_buf[] = "py_buf"; +static const char __pyx_k_reason[] = "reason"; static const char __pyx_k_reduce[] = "__reduce__"; -static const char __pyx_k_result[] = "result"; -static const char __pyx_k_schema[] = "schema"; static const char __pyx_k_scheme[] = "scheme"; +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_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_buf_data[] = "buf_data"; 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_password[] = "password"; 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_userinfo[] = "userinfo"; +static const char __pyx_k_FORWARDED[] = "FORWARDED"; static const char __pyx_k_TypeError[] = "TypeError"; +static const char __pyx_k_WEBSOCKET[] = "WEBSOCKET"; static const char __pyx_k_feed_data[] = "feed_data"; static const char __pyx_k_multidict[] = "multidict"; -static const char __pyx_k_parse_url[] = "_parse_url"; +static const char __pyx_k_parse_url[] = "parse_url"; static const char __pyx_k_partition[] = "partition"; +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_parse_url_2[] = "parse_url"; +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_http_version[] = "http_version"; +static const char __pyx_k_pyx_checksum[] = "__pyx_checksum"; +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_invalid_url_r[] = "invalid url {!r}"; 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_surrogateescape[] = "surrogateescape"; +static const char __pyx_k_CIMultiDictProxy[] = "CIMultiDictProxy"; static const char __pyx_k_CONTENT_ENCODING[] = "CONTENT_ENCODING"; -static const char __pyx_k_RawRequestMessage[] = "RawRequestMessage"; +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[] = " \ - * PyMem_Malloc(sizeof(cparser.http_parser)) + * + * cdef inline object extend(object buf, const char* at, size_t length): # <<<<<<<<<<<<<< + * cdef Py_ssize_t s + * cdef char* ptr */ -/* 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; +static CYTHON_INLINE PyObject *__pyx_f_7aiohttp_12_http_parser_extend(PyObject *__pyx_v_buf, char const *__pyx_v_at, size_t __pyx_v_length) { + Py_ssize_t __pyx_v_s; + char *__pyx_v_ptr; + PyObject *__pyx_r = NULL; __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; -} + Py_ssize_t __pyx_t_1; + int __pyx_t_2; + __Pyx_RefNannySetupContext("extend", 0); -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; - __Pyx_RefNannySetupContext("__cinit__", 0); + /* "aiohttp/_http_parser.pyx":60 + * cdef Py_ssize_t s + * cdef char* ptr + * s = PyByteArray_Size(buf) # <<<<<<<<<<<<<< + * PyByteArray_Resize(buf, s + length) + * ptr = PyByteArray_AsString(buf) + */ + __pyx_t_1 = PyByteArray_Size(__pyx_v_buf); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1L))) __PYX_ERR(0, 60, __pyx_L1_error) + __pyx_v_s = __pyx_t_1; - /* "aiohttp/_http_parser.pyx":69 - * - * def __cinit__(self): - * self._cparser = \ # <<<<<<<<<<<<<< - * PyMem_Malloc(sizeof(cparser.http_parser)) - * if self._cparser is NULL: + /* "aiohttp/_http_parser.pyx":61 + * cdef char* ptr + * s = PyByteArray_Size(buf) + * PyByteArray_Resize(buf, s + length) # <<<<<<<<<<<<<< + * ptr = PyByteArray_AsString(buf) + * memcpy(ptr + s, at, length) */ - __pyx_v_self->_cparser = ((struct http_parser *)PyMem_Malloc((sizeof(struct http_parser)))); + __pyx_t_2 = PyByteArray_Resize(__pyx_v_buf, (__pyx_v_s + __pyx_v_length)); if (unlikely(__pyx_t_2 == ((int)-1))) __PYX_ERR(0, 61, __pyx_L1_error) - /* "aiohttp/_http_parser.pyx":71 - * self._cparser = \ - * PyMem_Malloc(sizeof(cparser.http_parser)) - * if self._cparser is NULL: # <<<<<<<<<<<<<< - * raise MemoryError() + /* "aiohttp/_http_parser.pyx":62 + * s = PyByteArray_Size(buf) + * PyByteArray_Resize(buf, s + length) + * ptr = PyByteArray_AsString(buf) # <<<<<<<<<<<<<< + * memcpy(ptr + s, at, length) * */ - __pyx_t_1 = ((__pyx_v_self->_cparser == NULL) != 0); - if (unlikely(__pyx_t_1)) { + __pyx_v_ptr = PyByteArray_AsString(__pyx_v_buf); - /* "aiohttp/_http_parser.pyx":72 - * PyMem_Malloc(sizeof(cparser.http_parser)) - * if self._cparser is NULL: - * raise MemoryError() # <<<<<<<<<<<<<< + /* "aiohttp/_http_parser.pyx":63 + * PyByteArray_Resize(buf, s + length) + * ptr = PyByteArray_AsString(buf) + * memcpy(ptr + s, at, length) # <<<<<<<<<<<<<< + * * - * self._csettings = \ */ - PyErr_NoMemory(); __PYX_ERR(0, 72, __pyx_L1_error) + (void)(memcpy((__pyx_v_ptr + __pyx_v_s), __pyx_v_at, __pyx_v_length)); - /* "aiohttp/_http_parser.pyx":71 - * self._cparser = \ - * PyMem_Malloc(sizeof(cparser.http_parser)) - * if self._cparser is NULL: # <<<<<<<<<<<<<< - * raise MemoryError() + /* "aiohttp/_http_parser.pyx":57 * + * + * cdef inline object extend(object buf, const char* at, size_t length): # <<<<<<<<<<<<<< + * cdef Py_ssize_t s + * cdef char* ptr */ - } - /* "aiohttp/_http_parser.pyx":74 - * raise MemoryError() + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_AddTraceback("aiohttp._http_parser.extend", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "aiohttp/_http_parser.pyx":75 * - * self._csettings = \ # <<<<<<<<<<<<<< - * PyMem_Malloc(sizeof(cparser.http_parser_settings)) - * if self._csettings is NULL: + * + * cdef inline str http_method_str(int i): # <<<<<<<<<<<<<< + * if i < METHODS_COUNT: + * return _http_method[i] */ - __pyx_v_self->_csettings = ((struct http_parser_settings *)PyMem_Malloc((sizeof(struct http_parser_settings)))); + +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; + __Pyx_RefNannySetupContext("http_method_str", 0); /* "aiohttp/_http_parser.pyx":76 - * self._csettings = \ - * PyMem_Malloc(sizeof(cparser.http_parser_settings)) - * if self._csettings is NULL: # <<<<<<<<<<<<<< - * raise MemoryError() * + * cdef inline str http_method_str(int i): + * if i < METHODS_COUNT: # <<<<<<<<<<<<<< + * return _http_method[i] + * else: */ - __pyx_t_1 = ((__pyx_v_self->_csettings == NULL) != 0); - if (unlikely(__pyx_t_1)) { + __pyx_t_1 = ((__pyx_v_i < 34) != 0); + if (__pyx_t_1) { /* "aiohttp/_http_parser.pyx":77 - * PyMem_Malloc(sizeof(cparser.http_parser_settings)) - * if self._csettings is NULL: - * raise MemoryError() # <<<<<<<<<<<<<< - * - * def __dealloc__(self): + * cdef inline str http_method_str(int i): + * if i < METHODS_COUNT: + * return _http_method[i] # <<<<<<<<<<<<<< + * else: + * return "" */ - PyErr_NoMemory(); __PYX_ERR(0, 77, __pyx_L1_error) + __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, 77, __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, 77, __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":76 - * self._csettings = \ - * PyMem_Malloc(sizeof(cparser.http_parser_settings)) - * if self._csettings is NULL: # <<<<<<<<<<<<<< - * raise MemoryError() * + * cdef inline str http_method_str(int i): + * if i < METHODS_COUNT: # <<<<<<<<<<<<<< + * return _http_method[i] + * else: */ } - /* "aiohttp/_http_parser.pyx":68 - * Py_buffer py_buf + /* "aiohttp/_http_parser.pyx":79 + * return _http_method[i] + * else: + * return "" # <<<<<<<<<<<<<< * - * def __cinit__(self): # <<<<<<<<<<<<<< - * self._cparser = \ - * PyMem_Malloc(sizeof(cparser.http_parser)) + * 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":75 + * + * + * cdef inline str http_method_str(int i): # <<<<<<<<<<<<<< + * if i < METHODS_COUNT: + * return _http_method[i] */ /* 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_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":79 - * raise MemoryError() +/* "aiohttp/_http_parser.pyx":81 + * return "" * - * def __dealloc__(self): # <<<<<<<<<<<<<< - * PyMem_Free(self._cparser) - * PyMem_Free(self._csettings) + * cdef inline object find_header(bytes raw_header): # <<<<<<<<<<<<<< + * cdef Py_ssize_t size + * cdef char *buf */ -/* 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) { +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 - __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)); + int __pyx_t_1; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + __Pyx_RefNannySetupContext("find_header", 0); - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} + /* "aiohttp/_http_parser.pyx":85 + * 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, 85, __pyx_L1_error) -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":86 + * 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":80 - * - * def __dealloc__(self): - * PyMem_Free(self._cparser) # <<<<<<<<<<<<<< - * PyMem_Free(self._csettings) - * + /* "aiohttp/_http_parser.pyx":87 + * 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] */ - PyMem_Free(__pyx_v_self->_cparser); + __pyx_t_2 = ((__pyx_v_idx == -1L) != 0); + if (__pyx_t_2) { - /* "aiohttp/_http_parser.pyx":81 - * def __dealloc__(self): - * PyMem_Free(self._cparser) - * PyMem_Free(self._csettings) # <<<<<<<<<<<<<< + /* "aiohttp/_http_parser.pyx":88 + * idx = _find_header.find_header(buf, size) + * if idx == -1: + * return raw_header.decode('utf-8', 'surrogateescape') # <<<<<<<<<<<<<< + * return headers[idx] * - * cdef _init(self, cparser.http_parser_type mode, */ - PyMem_Free(__pyx_v_self->_csettings); + __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, 88, __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, 88, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; - /* "aiohttp/_http_parser.pyx":79 - * raise MemoryError() - * - * def __dealloc__(self): # <<<<<<<<<<<<<< - * PyMem_Free(self._cparser) - * PyMem_Free(self._csettings) + /* "aiohttp/_http_parser.pyx":87 + * 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] */ + } - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} - -/* "aiohttp/_http_parser.pyx":83 - * PyMem_Free(self._csettings) + /* "aiohttp/_http_parser.pyx":89 + * if idx == -1: + * return raw_header.decode('utf-8', 'surrogateescape') + * return headers[idx] # <<<<<<<<<<<<<< + * * - * cdef _init(self, cparser.http_parser_type mode, # <<<<<<<<<<<<<< - * object protocol, object loop, object timer=None, - * size_t max_line_size=8190, size_t max_headers=32768, */ + __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, 89, __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, 89, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L0; -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__init(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self, enum http_parser_type __pyx_v_mode, PyObject *__pyx_v_protocol, PyObject *__pyx_v_loop, struct __pyx_opt_args_7aiohttp_12_http_parser_10HttpParser__init *__pyx_optional_args) { - - /* "aiohttp/_http_parser.pyx":84 + /* "aiohttp/_http_parser.pyx":81 + * return "" * - * cdef _init(self, cparser.http_parser_type mode, - * object protocol, object loop, object timer=None, # <<<<<<<<<<<<<< - * size_t max_line_size=8190, size_t max_headers=32768, - * size_t max_field_size=8190, payload_exception=None, + * cdef inline object find_header(bytes raw_header): # <<<<<<<<<<<<<< + * cdef Py_ssize_t size + * cdef char *buf */ - 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":86 - * object protocol, object loop, object timer=None, - * size_t max_line_size=8190, size_t max_headers=32768, - * size_t max_field_size=8190, payload_exception=None, # <<<<<<<<<<<<<< - * response_with_body=True, auto_decompress=True): - * cparser.http_parser_init(self._cparser, mode) - */ - PyObject *__pyx_v_payload_exception = ((PyObject *)Py_None); + /* 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":87 - * size_t max_line_size=8190, size_t max_headers=32768, - * size_t max_field_size=8190, payload_exception=None, - * response_with_body=True, auto_decompress=True): # <<<<<<<<<<<<<< - * cparser.http_parser_init(self._cparser, mode) - * self._cparser.data = self +/* "aiohttp/_http_parser.pyx":105 + * cdef readonly object url # yarl.URL + * + * def __init__(self, method, path, version, headers, raw_headers, # <<<<<<<<<<<<<< + * should_close, compression, upgrade, chunked, url): + * self.method = method */ - PyObject *__pyx_v_response_with_body = ((PyObject *)Py_True); - PyObject *__pyx_v_auto_decompress = ((PyObject *)Py_True); - PyObject *__pyx_r = NULL; + +/* 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_r; __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - __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_auto_decompress = __pyx_optional_args->auto_decompress; - } - } - } - } + __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, 105, __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, 105, __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, 105, __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, 105, __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, 105, __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, 105, __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, 105, __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, 105, __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, 105, __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, 105, __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, 105, __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); - /* "aiohttp/_http_parser.pyx":88 - * size_t max_field_size=8190, payload_exception=None, - * response_with_body=True, auto_decompress=True): - * cparser.http_parser_init(self._cparser, mode) # <<<<<<<<<<<<<< - * self._cparser.data = self - * self._cparser.content_length = 0 + /* 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; + __Pyx_RefNannySetupContext("__init__", 0); + + /* "aiohttp/_http_parser.pyx":107 + * def __init__(self, method, path, version, headers, raw_headers, + * should_close, compression, upgrade, chunked, url): + * self.method = method # <<<<<<<<<<<<<< + * self.path = path + * self.version = version */ - http_parser_init(__pyx_v_self->_cparser, __pyx_v_mode); + 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, 107, __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":89 - * response_with_body=True, auto_decompress=True): - * cparser.http_parser_init(self._cparser, mode) - * self._cparser.data = self # <<<<<<<<<<<<<< - * self._cparser.content_length = 0 - * + /* "aiohttp/_http_parser.pyx":108 + * should_close, compression, upgrade, chunked, url): + * self.method = method + * self.path = path # <<<<<<<<<<<<<< + * self.version = version + * self.headers = headers */ - __pyx_v_self->_cparser->data = ((void *)__pyx_v_self); + 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, 108, __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":90 - * cparser.http_parser_init(self._cparser, mode) - * self._cparser.data = self - * self._cparser.content_length = 0 # <<<<<<<<<<<<<< + /* "aiohttp/_http_parser.pyx":109 + * 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":110 + * 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":111 + * 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":112 + * 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":113 + * 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":114 + * 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":115 + * 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":116 + * 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":105 + * cdef readonly object url # yarl.URL * - * cparser.http_parser_settings_init(self._csettings) + * def __init__(self, method, path, version, headers, raw_headers, # <<<<<<<<<<<<<< + * should_close, compression, upgrade, chunked, url): + * self.method = method */ - __pyx_v_self->_cparser->content_length = 0; - /* "aiohttp/_http_parser.pyx":92 - * self._cparser.content_length = 0 - * - * cparser.http_parser_settings_init(self._csettings) # <<<<<<<<<<<<<< + /* 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":118 + * self.url = url * - * self._protocol = protocol + * def __repr__(self): # <<<<<<<<<<<<<< + * info = [] + * info.append(("method", self.method)) */ - http_parser_settings_init(__pyx_v_self->_csettings); - /* "aiohttp/_http_parser.pyx":94 - * cparser.http_parser_settings_init(self._csettings) +/* 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":130 + * info.append(("chunked", self.chunked)) + * info.append(("url", self.url)) + * sinfo = ', '.join(name + '=' + repr(val) for name, val in info) # <<<<<<<<<<<<<< + * return '' * - * 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":95 - * - * 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; +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 + __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, 130, __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, 130, __pyx_L1_error) + __Pyx_DECREF(__pyx_cur_scope); + __Pyx_RefNannyFinishContext(); + return (PyObject *) gen; + } - /* "aiohttp/_http_parser.pyx":96 - * self._protocol = protocol - * self._loop = loop - * self._timer = timer # <<<<<<<<<<<<<< + /* 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 *); + __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, 130, __pyx_L1_error) + __pyx_r = PyList_New(0); if (unlikely(!__pyx_r)) __PYX_ERR(0, 130, __pyx_L1_error) + __Pyx_GOTREF(__pyx_r); + if (unlikely(!__pyx_cur_scope->__pyx_outer_scope->__pyx_v_info)) { __Pyx_RaiseClosureNameError("info"); __PYX_ERR(0, 130, __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, 130, __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, 130, __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, 130, __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, 130, __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, 130, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 130, __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, 130, __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, 130, __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, 130, __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, 130, __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, 130, __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, 130, __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, 130, __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":118 + * self.url = url * - * self._buf = bytearray() + * def __repr__(self): # <<<<<<<<<<<<<< + * info = [] + * info.append(("method", self.method)) */ - __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":98 - * self._timer = timer +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_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + PyObject *__pyx_t_3 = NULL; + __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, 118, __pyx_L1_error) + } else { + __Pyx_GOTREF(__pyx_cur_scope); + } + + /* "aiohttp/_http_parser.pyx":119 * - * self._buf = bytearray() # <<<<<<<<<<<<<< - * self._payload = None - * self._payload_error = 0 + * def __repr__(self): + * info = [] # <<<<<<<<<<<<<< + * info.append(("method", self.method)) + * info.append(("path", self.path)) */ - __pyx_t_1 = __Pyx_PyObject_CallNoArg(((PyObject *)(&PyByteArray_Type))); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 98, __pyx_L1_error) + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 119, __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_cur_scope->__pyx_v_info = ((PyObject*)__pyx_t_1); __pyx_t_1 = 0; - /* "aiohttp/_http_parser.pyx":99 - * - * 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":100 - * self._buf = bytearray() - * self._payload = None - * self._payload_error = 0 # <<<<<<<<<<<<<< - * self._payload_exception = payload_exception - * self._messages = [] + /* "aiohttp/_http_parser.pyx":120 + * def __repr__(self): + * info = [] + * info.append(("method", self.method)) # <<<<<<<<<<<<<< + * info.append(("path", self.path)) + * info.append(("version", self.version)) */ - __pyx_v_self->_payload_error = 0; + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 120, __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, 120, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "aiohttp/_http_parser.pyx":101 - * self._payload = None - * self._payload_error = 0 - * self._payload_exception = payload_exception # <<<<<<<<<<<<<< - * self._messages = [] - * + /* "aiohttp/_http_parser.pyx":121 + * info = [] + * info.append(("method", self.method)) + * info.append(("path", self.path)) # <<<<<<<<<<<<<< + * info.append(("version", self.version)) + * info.append(("headers", self.headers)) */ - __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; + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 121, __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, 121, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "aiohttp/_http_parser.pyx":102 - * self._payload_error = 0 - * self._payload_exception = payload_exception - * self._messages = [] # <<<<<<<<<<<<<< - * - * self._header_name = None + /* "aiohttp/_http_parser.pyx":122 + * 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 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 102, __pyx_L1_error) + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 122, __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; + __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, 122, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "aiohttp/_http_parser.pyx":104 - * self._messages = [] - * - * self._header_name = None # <<<<<<<<<<<<<< - * self._header_value = None - * self._raw_header_name = None + /* "aiohttp/_http_parser.pyx":123 + * 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_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - __Pyx_GOTREF(__pyx_v_self->_header_name); - __Pyx_DECREF(__pyx_v_self->_header_name); - __pyx_v_self->_header_name = ((PyObject*)Py_None); + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 123, __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, 123, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "aiohttp/_http_parser.pyx":105 - * - * self._header_name = None - * self._header_value = None # <<<<<<<<<<<<<< - * self._raw_header_name = None - * self._raw_header_value = None - */ - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - __Pyx_GOTREF(__pyx_v_self->_header_value); - __Pyx_DECREF(__pyx_v_self->_header_value); - __pyx_v_self->_header_value = ((PyObject*)Py_None); - - /* "aiohttp/_http_parser.pyx":106 - * self._header_name = None - * self._header_value = None - * self._raw_header_name = None # <<<<<<<<<<<<<< - * self._raw_header_value = None - * + /* "aiohttp/_http_parser.pyx":124 + * 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_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - __Pyx_GOTREF(__pyx_v_self->_raw_header_name); - __Pyx_DECREF(__pyx_v_self->_raw_header_name); - __pyx_v_self->_raw_header_name = ((PyObject*)Py_None); + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 124, __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, 124, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "aiohttp/_http_parser.pyx":107 - * self._header_value = None - * self._raw_header_name = None - * self._raw_header_value = None # <<<<<<<<<<<<<< - * - * self._max_line_size = max_line_size + /* "aiohttp/_http_parser.pyx":125 + * 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_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - __Pyx_GOTREF(__pyx_v_self->_raw_header_value); - __Pyx_DECREF(__pyx_v_self->_raw_header_value); - __pyx_v_self->_raw_header_value = ((PyObject*)Py_None); + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 125, __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, 125, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "aiohttp/_http_parser.pyx":109 - * self._raw_header_value = None - * - * self._max_line_size = max_line_size # <<<<<<<<<<<<<< - * self._max_headers = max_headers - * self._max_field_size = max_field_size + /* "aiohttp/_http_parser.pyx":126 + * 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_v_self->_max_line_size = __pyx_v_max_line_size; + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 126, __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, 126, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "aiohttp/_http_parser.pyx":110 - * - * 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 + /* "aiohttp/_http_parser.pyx":127 + * 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_v_self->_max_headers = __pyx_v_max_headers; + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 127, __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, 127, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "aiohttp/_http_parser.pyx":111 - * 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._upgraded = False + /* "aiohttp/_http_parser.pyx":128 + * 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_v_self->_max_field_size = __pyx_v_max_field_size; + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 128, __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, 128, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "aiohttp/_http_parser.pyx":112 - * self._max_headers = max_headers - * self._max_field_size = max_field_size - * self._response_with_body = response_with_body # <<<<<<<<<<<<<< - * self._upgraded = False - * self._auto_decompress = auto_decompress + /* "aiohttp/_http_parser.pyx":129 + * 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_2 = __Pyx_PyObject_IsTrue(__pyx_v_response_with_body); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 112, __pyx_L1_error) - __pyx_v_self->_response_with_body = __pyx_t_2; + __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 129, __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, 129, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "aiohttp/_http_parser.pyx":113 - * self._max_field_size = max_field_size - * self._response_with_body = response_with_body - * self._upgraded = False # <<<<<<<<<<<<<< - * self._auto_decompress = auto_decompress + /* "aiohttp/_http_parser.pyx":130 + * info.append(("chunked", self.chunked)) + * info.append(("url", self.url)) + * sinfo = ', '.join(name + '=' + repr(val) for name, val in info) # <<<<<<<<<<<<<< + * return '' * */ - __pyx_v_self->_upgraded = 0; + __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, 130, __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, 130, __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, 130, __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":114 - * self._response_with_body = response_with_body - * self._upgraded = False - * self._auto_decompress = auto_decompress # <<<<<<<<<<<<<< + /* "aiohttp/_http_parser.pyx":131 + * info.append(("url", self.url)) + * sinfo = ', '.join(name + '=' + repr(val) for name, val in info) + * return '' # <<<<<<<<<<<<<< * - * self._csettings.on_url = cb_on_url + * def _replace(self, **dct): */ - __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_auto_decompress); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 114, __pyx_L1_error) - __pyx_v_self->_auto_decompress = __pyx_t_2; + __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, 131, __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, 131, __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":116 - * self._auto_decompress = auto_decompress + /* "aiohttp/_http_parser.pyx":118 + * self.url = url * - * self._csettings.on_url = cb_on_url # <<<<<<<<<<<<<< - * self._csettings.on_status = cb_on_status - * self._csettings.on_header_field = cb_on_header_field + * def __repr__(self): # <<<<<<<<<<<<<< + * info = [] + * info.append(("method", self.method)) */ - __pyx_v_self->_csettings->on_url = __pyx_f_7aiohttp_12_http_parser_cb_on_url; - /* "aiohttp/_http_parser.pyx":117 - * - * 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; + /* 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_DECREF(((PyObject *)__pyx_cur_scope)); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "aiohttp/_http_parser.pyx":118 - * 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 +/* "aiohttp/_http_parser.pyx":133 + * return '' + * + * def _replace(self, **dct): # <<<<<<<<<<<<<< + * cdef RawRequestMessage ret + * ret = _new_request_message(self.method, */ - __pyx_v_self->_csettings->on_header_field = __pyx_f_7aiohttp_12_http_parser_cb_on_header_field; - /* "aiohttp/_http_parser.pyx":119 - * 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; +/* 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); - /* "aiohttp/_http_parser.pyx":120 - * 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 + /* 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; + __Pyx_RefNannySetupContext("_replace", 0); + + /* "aiohttp/_http_parser.pyx":135 + * def _replace(self, **dct): + * cdef RawRequestMessage ret + * ret = _new_request_message(self.method, # <<<<<<<<<<<<<< + * self.path, + * self.version, */ - __pyx_v_self->_csettings->on_headers_complete = __pyx_f_7aiohttp_12_http_parser_cb_on_headers_complete; + __pyx_t_1 = __pyx_v_self->method; + __Pyx_INCREF(__pyx_t_1); - /* "aiohttp/_http_parser.pyx":121 - * 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 + /* "aiohttp/_http_parser.pyx":136 + * 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":137 + * 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":138 + * 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":139 + * 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":140 + * 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, 140, __pyx_L1_error) + + /* "aiohttp/_http_parser.pyx":141 + * 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":142 + * self.should_close, + * self.compression, + * self.upgrade, # <<<<<<<<<<<<<< + * self.chunked, + * self.url) */ - __pyx_v_self->_csettings->on_body = __pyx_f_7aiohttp_12_http_parser_cb_on_body; + __pyx_t_8 = __Pyx_PyObject_IsTrue(__pyx_v_self->upgrade); if (unlikely((__pyx_t_8 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 142, __pyx_L1_error) - /* "aiohttp/_http_parser.pyx":122 - * 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 + /* "aiohttp/_http_parser.pyx":143 + * self.compression, + * self.upgrade, + * self.chunked, # <<<<<<<<<<<<<< + * self.url) + * if "method" in dct: */ - __pyx_v_self->_csettings->on_message_begin = __pyx_f_7aiohttp_12_http_parser_cb_on_message_begin; + __pyx_t_9 = __Pyx_PyObject_IsTrue(__pyx_v_self->chunked); if (unlikely((__pyx_t_9 == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 143, __pyx_L1_error) - /* "aiohttp/_http_parser.pyx":123 - * 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 + /* "aiohttp/_http_parser.pyx":144 + * 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":135 + * def _replace(self, **dct): + * cdef RawRequestMessage ret + * ret = _new_request_message(self.method, # <<<<<<<<<<<<<< + * self.path, + * self.version, */ - __pyx_v_self->_csettings->on_message_complete = __pyx_f_7aiohttp_12_http_parser_cb_on_message_complete; + __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, 135, __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, 135, __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":145 + * 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, 145, __pyx_L1_error) + __pyx_t_8 = (__pyx_t_9 != 0); + if (__pyx_t_8) { - /* "aiohttp/_http_parser.pyx":124 - * 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 - * + /* "aiohttp/_http_parser.pyx":146 + * 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, 146, __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, 146, __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":145 + * self.chunked, + * self.url) + * if "method" in dct: # <<<<<<<<<<<<<< + * ret.method = dct["method"] + * if "path" in dct: */ - __pyx_v_self->_csettings->on_chunk_header = __pyx_f_7aiohttp_12_http_parser_cb_on_chunk_header; + } - /* "aiohttp/_http_parser.pyx":125 - * 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 + /* "aiohttp/_http_parser.pyx":147 + * if "method" in dct: + * ret.method = dct["method"] + * if "path" in dct: # <<<<<<<<<<<<<< + * ret.path = dct["path"] + * if "version" in dct: */ - __pyx_v_self->_csettings->on_chunk_complete = __pyx_f_7aiohttp_12_http_parser_cb_on_chunk_complete; + __pyx_t_8 = (__Pyx_PyDict_ContainsTF(__pyx_n_u_path, __pyx_v_dct, Py_EQ)); if (unlikely(__pyx_t_8 < 0)) __PYX_ERR(0, 147, __pyx_L1_error) + __pyx_t_9 = (__pyx_t_8 != 0); + if (__pyx_t_9) { - /* "aiohttp/_http_parser.pyx":127 - * self._csettings.on_chunk_complete = cb_on_chunk_complete - * - * self._last_error = None # <<<<<<<<<<<<<< - * - * cdef _process_header(self): + /* "aiohttp/_http_parser.pyx":148 + * 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, 148, __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, 148, __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":147 + * if "method" in dct: + * ret.method = dct["method"] + * if "path" in dct: # <<<<<<<<<<<<<< + * ret.path = dct["path"] + * if "version" in dct: */ - __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":83 - * PyMem_Free(self._csettings) - * - * cdef _init(self, cparser.http_parser_type mode, # <<<<<<<<<<<<<< - * object protocol, object loop, object timer=None, - * size_t max_line_size=8190, size_t max_headers=32768, + /* "aiohttp/_http_parser.pyx":149 + * 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, 149, __pyx_L1_error) + __pyx_t_8 = (__pyx_t_9 != 0); + if (__pyx_t_8) { + + /* "aiohttp/_http_parser.pyx":150 + * 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, 150, __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":149 + * if "path" in dct: + * ret.path = dct["path"] + * if "version" in dct: # <<<<<<<<<<<<<< + * ret.version = dct["version"] + * if "headers" in dct: */ + } - /* 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":151 + * 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, 151, __pyx_L1_error) + __pyx_t_9 = (__pyx_t_8 != 0); + if (__pyx_t_9) { -/* "aiohttp/_http_parser.pyx":129 - * self._last_error = None - * - * cdef _process_header(self): # <<<<<<<<<<<<<< - * if self._header_name is not None: - * name = self._header_name + /* "aiohttp/_http_parser.pyx":152 + * 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, 152, __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":151 + * if "version" in dct: + * ret.version = dct["version"] + * if "headers" in dct: # <<<<<<<<<<<<<< + * ret.headers = dct["headers"] + * if "raw_headers" in dct: */ + } -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_name = NULL; - PyObject *__pyx_v_value = NULL; - PyObject *__pyx_v_raw_name = NULL; - PyObject *__pyx_v_raw_value = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - int __pyx_t_4; - __Pyx_RefNannySetupContext("_process_header", 0); + /* "aiohttp/_http_parser.pyx":153 + * 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, 153, __pyx_L1_error) + __pyx_t_8 = (__pyx_t_9 != 0); + if (__pyx_t_8) { + + /* "aiohttp/_http_parser.pyx":154 + * 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, 154, __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":130 - * - * cdef _process_header(self): - * if self._header_name is not None: # <<<<<<<<<<<<<< - * name = self._header_name - * value = self._header_value + /* "aiohttp/_http_parser.pyx":153 + * 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_1 = (__pyx_v_self->_header_name != ((PyObject*)Py_None)); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { + } - /* "aiohttp/_http_parser.pyx":131 - * cdef _process_header(self): - * if self._header_name is not None: - * name = self._header_name # <<<<<<<<<<<<<< - * value = self._header_value - * + /* "aiohttp/_http_parser.pyx":155 + * 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_3 = __pyx_v_self->_header_name; - __Pyx_INCREF(__pyx_t_3); - __pyx_v_name = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; + __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, 155, __pyx_L1_error) + __pyx_t_9 = (__pyx_t_8 != 0); + if (__pyx_t_9) { - /* "aiohttp/_http_parser.pyx":132 - * if self._header_name is not None: - * name = self._header_name - * value = self._header_value # <<<<<<<<<<<<<< - * - * self._header_name = self._header_value = None + /* "aiohttp/_http_parser.pyx":156 + * 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, 156, __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":155 + * 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_3 = __pyx_v_self->_header_value; - __Pyx_INCREF(__pyx_t_3); - __pyx_v_value = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; + } - /* "aiohttp/_http_parser.pyx":134 - * value = self._header_value - * - * self._header_name = self._header_value = None # <<<<<<<<<<<<<< - * self._headers.append((name, value)) - * + /* "aiohttp/_http_parser.pyx":157 + * 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, 157, __pyx_L1_error) + __pyx_t_8 = (__pyx_t_9 != 0); + if (__pyx_t_8) { + + /* "aiohttp/_http_parser.pyx":158 + * 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, 158, __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":157 + * if "should_close" in dct: + * ret.should_close = dct["should_close"] + * if "compression" in dct: # <<<<<<<<<<<<<< + * ret.compression = dct["compression"] + * if "upgrade" in dct: */ - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - __Pyx_GOTREF(__pyx_v_self->_header_name); - __Pyx_DECREF(__pyx_v_self->_header_name); - __pyx_v_self->_header_name = ((PyObject*)Py_None); - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - __Pyx_GOTREF(__pyx_v_self->_header_value); - __Pyx_DECREF(__pyx_v_self->_header_value); - __pyx_v_self->_header_value = ((PyObject*)Py_None); + } - /* "aiohttp/_http_parser.pyx":135 - * - * self._header_name = self._header_value = None - * self._headers.append((name, value)) # <<<<<<<<<<<<<< - * - * raw_name = self._raw_header_name + /* "aiohttp/_http_parser.pyx":159 + * if "compression" in dct: + * ret.compression = dct["compression"] + * if "upgrade" in dct: # <<<<<<<<<<<<<< + * ret.upgrade = dct["upgrade"] + * if "chunked" in dct: */ - if (unlikely(__pyx_v_self->_headers == Py_None)) { - PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "append"); - __PYX_ERR(0, 135, __pyx_L1_error) - } - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 135, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_name); - __Pyx_GIVEREF(__pyx_v_name); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_name); - __Pyx_INCREF(__pyx_v_value); - __Pyx_GIVEREF(__pyx_v_value); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_value); - __pyx_t_4 = __Pyx_PyList_Append(__pyx_v_self->_headers, __pyx_t_3); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(0, 135, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_8 = (__Pyx_PyDict_ContainsTF(__pyx_n_u_upgrade, __pyx_v_dct, Py_EQ)); if (unlikely(__pyx_t_8 < 0)) __PYX_ERR(0, 159, __pyx_L1_error) + __pyx_t_9 = (__pyx_t_8 != 0); + if (__pyx_t_9) { - /* "aiohttp/_http_parser.pyx":137 - * self._headers.append((name, value)) - * - * raw_name = self._raw_header_name # <<<<<<<<<<<<<< - * raw_value = self._raw_header_value - * + /* "aiohttp/_http_parser.pyx":160 + * 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, 160, __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":159 + * if "compression" in dct: + * ret.compression = dct["compression"] + * if "upgrade" in dct: # <<<<<<<<<<<<<< + * ret.upgrade = dct["upgrade"] + * if "chunked" in dct: */ - __pyx_t_3 = __pyx_v_self->_raw_header_name; - __Pyx_INCREF(__pyx_t_3); - __pyx_v_raw_name = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; + } - /* "aiohttp/_http_parser.pyx":138 - * - * raw_name = self._raw_header_name - * raw_value = self._raw_header_value # <<<<<<<<<<<<<< - * - * self._raw_header_name = self._raw_header_value = None + /* "aiohttp/_http_parser.pyx":161 + * 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, 161, __pyx_L1_error) + __pyx_t_8 = (__pyx_t_9 != 0); + if (__pyx_t_8) { + + /* "aiohttp/_http_parser.pyx":162 + * 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, 162, __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":161 + * if "upgrade" in dct: + * ret.upgrade = dct["upgrade"] + * if "chunked" in dct: # <<<<<<<<<<<<<< + * ret.chunked = dct["chunked"] + * if "url" in dct: */ - __pyx_t_3 = __pyx_v_self->_raw_header_value; - __Pyx_INCREF(__pyx_t_3); - __pyx_v_raw_value = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; + } - /* "aiohttp/_http_parser.pyx":140 - * raw_value = self._raw_header_value - * - * self._raw_header_name = self._raw_header_value = None # <<<<<<<<<<<<<< - * self._raw_headers.append((raw_name, raw_value)) - * + /* "aiohttp/_http_parser.pyx":163 + * if "chunked" in dct: + * ret.chunked = dct["chunked"] + * if "url" in dct: # <<<<<<<<<<<<<< + * ret.url = dct["url"] + * return ret */ - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - __Pyx_GOTREF(__pyx_v_self->_raw_header_name); - __Pyx_DECREF(__pyx_v_self->_raw_header_name); - __pyx_v_self->_raw_header_name = ((PyObject*)Py_None); - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - __Pyx_GOTREF(__pyx_v_self->_raw_header_value); - __Pyx_DECREF(__pyx_v_self->_raw_header_value); - __pyx_v_self->_raw_header_value = ((PyObject*)Py_None); + __pyx_t_8 = (__Pyx_PyDict_ContainsTF(__pyx_n_u_url, __pyx_v_dct, Py_EQ)); if (unlikely(__pyx_t_8 < 0)) __PYX_ERR(0, 163, __pyx_L1_error) + __pyx_t_9 = (__pyx_t_8 != 0); + if (__pyx_t_9) { - /* "aiohttp/_http_parser.pyx":141 - * - * self._raw_header_name = self._raw_header_value = None - * self._raw_headers.append((raw_name, raw_value)) # <<<<<<<<<<<<<< - * - * cdef _on_header_field(self, str field, bytes raw_field): + /* "aiohttp/_http_parser.pyx":164 + * 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, 164, __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":163 + * if "chunked" in dct: + * ret.chunked = dct["chunked"] + * if "url" in dct: # <<<<<<<<<<<<<< + * ret.url = dct["url"] + * return ret */ - if (unlikely(__pyx_v_self->_raw_headers == Py_None)) { - PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "append"); - __PYX_ERR(0, 141, __pyx_L1_error) - } - __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 141, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_INCREF(__pyx_v_raw_name); - __Pyx_GIVEREF(__pyx_v_raw_name); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_raw_name); - __Pyx_INCREF(__pyx_v_raw_value); - __Pyx_GIVEREF(__pyx_v_raw_value); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_v_raw_value); - __pyx_t_4 = __Pyx_PyList_Append(__pyx_v_self->_raw_headers, __pyx_t_3); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(0, 141, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } - /* "aiohttp/_http_parser.pyx":130 + /* "aiohttp/_http_parser.pyx":165 + * if "url" in dct: + * ret.url = dct["url"] + * return ret # <<<<<<<<<<<<<< * - * cdef _process_header(self): - * if self._header_name is not None: # <<<<<<<<<<<<<< - * name = self._header_name - * value = self._header_value + * 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":129 - * self._last_error = None + /* "aiohttp/_http_parser.pyx":133 + * return '' * - * cdef _process_header(self): # <<<<<<<<<<<<<< - * if self._header_name is not None: - * name = self._header_name + * def _replace(self, **dct): # <<<<<<<<<<<<<< + * cdef RawRequestMessage ret + * ret = _new_request_message(self.method, */ /* 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._process_header", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; + __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(__pyx_v_name); - __Pyx_XDECREF(__pyx_v_value); - __Pyx_XDECREF(__pyx_v_raw_name); - __Pyx_XDECREF(__pyx_v_raw_value); + __Pyx_XDECREF((PyObject *)__pyx_v_ret); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "aiohttp/_http_parser.pyx":143 - * self._raw_headers.append((raw_name, raw_value)) - * - * cdef _on_header_field(self, str field, bytes raw_field): # <<<<<<<<<<<<<< - * if self._header_value is not None: - * self._process_header() +/* "aiohttp/_http_parser.pyx":94 + * @cython.freelist(DEFAULT_FREELIST_SIZE) + * cdef class RawRequestMessage: + * cdef readonly str method # <<<<<<<<<<<<<< + * cdef readonly str path + * cdef readonly object version # HttpVersion */ -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_header_field(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self, PyObject *__pyx_v_field, PyObject *__pyx_v_raw_field) { +/* 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 - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - __Pyx_RefNannySetupContext("_on_header_field", 0); + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->method); + __pyx_r = __pyx_v_self->method; + goto __pyx_L0; - /* "aiohttp/_http_parser.pyx":144 - * - * cdef _on_header_field(self, str field, bytes raw_field): - * if self._header_value is not None: # <<<<<<<<<<<<<< - * self._process_header() - * self._header_value = None - */ - __pyx_t_1 = (__pyx_v_self->_header_value != ((PyObject*)Py_None)); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "aiohttp/_http_parser.pyx":145 - * cdef _on_header_field(self, str field, bytes raw_field): - * if self._header_value is not None: - * self._process_header() # <<<<<<<<<<<<<< - * self._header_value = None - * +/* "aiohttp/_http_parser.pyx":95 + * cdef class RawRequestMessage: + * cdef readonly str method + * cdef readonly str path # <<<<<<<<<<<<<< + * cdef readonly object version # HttpVersion + * cdef readonly object headers # CIMultiDict */ - __pyx_t_3 = ((struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser *)__pyx_v_self->__pyx_vtab)->_process_header(__pyx_v_self); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 145, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - /* "aiohttp/_http_parser.pyx":146 - * if self._header_value is not None: - * self._process_header() - * self._header_value = None # <<<<<<<<<<<<<< - * - * if self._header_name is None: - */ - __Pyx_INCREF(Py_None); - __Pyx_GIVEREF(Py_None); - __Pyx_GOTREF(__pyx_v_self->_header_value); - __Pyx_DECREF(__pyx_v_self->_header_value); - __pyx_v_self->_header_value = ((PyObject*)Py_None); +/* 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)); - /* "aiohttp/_http_parser.pyx":144 - * - * cdef _on_header_field(self, str field, bytes raw_field): - * if self._header_value is not None: # <<<<<<<<<<<<<< - * self._process_header() - * self._header_value = None - */ - } + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "aiohttp/_http_parser.pyx":148 - * self._header_value = None - * - * if self._header_name is None: # <<<<<<<<<<<<<< - * self._header_name = field - * self._raw_header_name = raw_field - */ - __pyx_t_2 = (__pyx_v_self->_header_name == ((PyObject*)Py_None)); - __pyx_t_1 = (__pyx_t_2 != 0); - if (__pyx_t_1) { +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; - /* "aiohttp/_http_parser.pyx":149 - * - * if self._header_name is None: - * self._header_name = field # <<<<<<<<<<<<<< - * self._raw_header_name = raw_field - * else: - */ - __Pyx_INCREF(__pyx_v_field); - __Pyx_GIVEREF(__pyx_v_field); - __Pyx_GOTREF(__pyx_v_self->_header_name); - __Pyx_DECREF(__pyx_v_self->_header_name); - __pyx_v_self->_header_name = __pyx_v_field; + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "aiohttp/_http_parser.pyx":150 - * if self._header_name is None: - * self._header_name = field - * self._raw_header_name = raw_field # <<<<<<<<<<<<<< - * else: - * self._header_name += field +/* "aiohttp/_http_parser.pyx":96 + * cdef readonly str method + * cdef readonly str path + * cdef readonly object version # HttpVersion # <<<<<<<<<<<<<< + * cdef readonly object headers # CIMultiDict + * cdef readonly object raw_headers # tuple */ - __Pyx_INCREF(__pyx_v_raw_field); - __Pyx_GIVEREF(__pyx_v_raw_field); - __Pyx_GOTREF(__pyx_v_self->_raw_header_name); - __Pyx_DECREF(__pyx_v_self->_raw_header_name); - __pyx_v_self->_raw_header_name = __pyx_v_raw_field; - /* "aiohttp/_http_parser.pyx":148 - * self._header_value = None - * - * if self._header_name is None: # <<<<<<<<<<<<<< - * self._header_name = field - * self._raw_header_name = raw_field - */ - goto __pyx_L4; - } +/* 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)); - /* "aiohttp/_http_parser.pyx":152 - * self._raw_header_name = raw_field - * else: - * self._header_name += field # <<<<<<<<<<<<<< - * self._raw_header_name += raw_field - * - */ - /*else*/ { - __pyx_t_3 = __Pyx_PyUnicode_ConcatSafe(__pyx_v_self->_header_name, __pyx_v_field); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 152, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __Pyx_GOTREF(__pyx_v_self->_header_name); - __Pyx_DECREF(__pyx_v_self->_header_name); - __pyx_v_self->_header_name = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "aiohttp/_http_parser.pyx":153 - * else: - * self._header_name += field - * self._raw_header_name += raw_field # <<<<<<<<<<<<<< - * - * cdef _on_header_value(self, str val, bytes raw_val): - */ - __pyx_t_3 = PyNumber_InPlaceAdd(__pyx_v_self->_raw_header_name, __pyx_v_raw_field); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 153, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __Pyx_GOTREF(__pyx_v_self->_raw_header_name); - __Pyx_DECREF(__pyx_v_self->_raw_header_name); - __pyx_v_self->_raw_header_name = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - } - __pyx_L4:; +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; - /* "aiohttp/_http_parser.pyx":143 - * self._raw_headers.append((raw_name, raw_value)) - * - * cdef _on_header_field(self, str field, bytes raw_field): # <<<<<<<<<<<<<< - * if self._header_value is not None: - * self._process_header() + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "aiohttp/_http_parser.pyx":97 + * 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_r = Py_None; __Pyx_INCREF(Py_None); + __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; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("aiohttp._http_parser.HttpParser._on_header_field", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; + + /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "aiohttp/_http_parser.pyx":155 - * self._raw_header_name += raw_field - * - * cdef _on_header_value(self, str val, bytes raw_val): # <<<<<<<<<<<<<< - * if self._header_value is None: - * self._header_value = val +/* "aiohttp/_http_parser.pyx":98 + * 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 */ -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_header_value(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self, PyObject *__pyx_v_val, PyObject *__pyx_v_raw_val) { +/* 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 - int __pyx_t_1; - int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - __Pyx_RefNannySetupContext("_on_header_value", 0); + __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; - /* "aiohttp/_http_parser.pyx":156 - * - * cdef _on_header_value(self, str val, bytes raw_val): - * if self._header_value is None: # <<<<<<<<<<<<<< - * self._header_value = val - * self._raw_header_value = raw_val - */ - __pyx_t_1 = (__pyx_v_self->_header_value == ((PyObject*)Py_None)); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "aiohttp/_http_parser.pyx":157 - * cdef _on_header_value(self, str val, bytes raw_val): - * if self._header_value is None: - * self._header_value = val # <<<<<<<<<<<<<< - * self._raw_header_value = raw_val - * else: +/* "aiohttp/_http_parser.pyx":99 + * cdef readonly object headers # CIMultiDict + * cdef readonly object raw_headers # tuple + * cdef readonly object should_close # <<<<<<<<<<<<<< + * cdef readonly object compression + * cdef readonly object upgrade */ - __Pyx_INCREF(__pyx_v_val); - __Pyx_GIVEREF(__pyx_v_val); - __Pyx_GOTREF(__pyx_v_self->_header_value); - __Pyx_DECREF(__pyx_v_self->_header_value); - __pyx_v_self->_header_value = __pyx_v_val; - /* "aiohttp/_http_parser.pyx":158 - * if self._header_value is None: - * self._header_value = val - * self._raw_header_value = raw_val # <<<<<<<<<<<<<< - * else: - * self._header_value += val - */ - __Pyx_INCREF(__pyx_v_raw_val); - __Pyx_GIVEREF(__pyx_v_raw_val); - __Pyx_GOTREF(__pyx_v_self->_raw_header_value); - __Pyx_DECREF(__pyx_v_self->_raw_header_value); - __pyx_v_self->_raw_header_value = __pyx_v_raw_val; +/* 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)); - /* "aiohttp/_http_parser.pyx":156 - * - * cdef _on_header_value(self, str val, bytes raw_val): - * if self._header_value is None: # <<<<<<<<<<<<<< - * self._header_value = val - * self._raw_header_value = raw_val - */ - goto __pyx_L3; - } + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "aiohttp/_http_parser.pyx":160 - * self._raw_header_value = raw_val - * else: - * self._header_value += val # <<<<<<<<<<<<<< - * self._raw_header_value += raw_val - * - */ - /*else*/ { - __pyx_t_3 = __Pyx_PyUnicode_ConcatSafe(__pyx_v_self->_header_value, __pyx_v_val); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 160, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __Pyx_GOTREF(__pyx_v_self->_header_value); - __Pyx_DECREF(__pyx_v_self->_header_value); - __pyx_v_self->_header_value = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; +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; - /* "aiohttp/_http_parser.pyx":161 - * else: - * self._header_value += val - * self._raw_header_value += raw_val # <<<<<<<<<<<<<< - * - * cdef _on_headers_complete(self, + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "aiohttp/_http_parser.pyx":100 + * cdef readonly object raw_headers # tuple + * cdef readonly object should_close + * cdef readonly object compression # <<<<<<<<<<<<<< + * cdef readonly object upgrade + * cdef readonly object chunked */ - __pyx_t_3 = PyNumber_InPlaceAdd(__pyx_v_self->_raw_header_value, __pyx_v_raw_val); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 161, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __Pyx_GOTREF(__pyx_v_self->_raw_header_value); - __Pyx_DECREF(__pyx_v_self->_raw_header_value); - __pyx_v_self->_raw_header_value = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - } - __pyx_L3:; - /* "aiohttp/_http_parser.pyx":155 - * self._raw_header_name += raw_field - * - * cdef _on_header_value(self, str val, bytes raw_val): # <<<<<<<<<<<<<< - * if self._header_value is None: - * self._header_value = val +/* 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":101 + * 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_r = Py_None; __Pyx_INCREF(Py_None); + __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; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("aiohttp._http_parser.HttpParser._on_header_value", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; + + /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "aiohttp/_http_parser.pyx":163 - * self._raw_header_value += raw_val - * - * cdef _on_headers_complete(self, # <<<<<<<<<<<<<< - * ENCODING='utf-8', - * ENCODING_ERR='surrogateescape', - */ - -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_headers_complete(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self, struct __pyx_opt_args_7aiohttp_12_http_parser_10HttpParser__on_headers_complete *__pyx_optional_args) { - PyObject *__pyx_v_ENCODING = ((PyObject *)__pyx_kp_u_utf_8); - PyObject *__pyx_v_ENCODING_ERR = ((PyObject *)__pyx_n_u_surrogateescape); - PyObject *__pyx_v_CONTENT_ENCODING = __pyx_k_; - PyObject *__pyx_v_SEC_WEBSOCKET_KEY1 = __pyx_k__2; - - /* "aiohttp/_http_parser.pyx":168 - * CONTENT_ENCODING=hdrs.CONTENT_ENCODING, - * SEC_WEBSOCKET_KEY1=hdrs.SEC_WEBSOCKET_KEY1, - * SUPPORTED=('gzip', 'deflate', 'br')): # <<<<<<<<<<<<<< - * self._process_header() +/* "aiohttp/_http_parser.pyx":102 + * cdef readonly object compression + * cdef readonly object upgrade + * cdef readonly object chunked # <<<<<<<<<<<<<< + * cdef readonly object url # yarl.URL * */ - PyObject *__pyx_v_SUPPORTED = ((PyObject *)__pyx_tuple__3); - char const *__pyx_v_method; - int __pyx_v_should_close; - PyObject *__pyx_v_upgrade = NULL; - PyObject *__pyx_v_chunked = NULL; - 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; + +/* 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 - PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - 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; - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; - int __pyx_t_11; - int __pyx_t_12; - __Pyx_RefNannySetupContext("_on_headers_complete", 0); - if (__pyx_optional_args) { - if (__pyx_optional_args->__pyx_n > 0) { - __pyx_v_ENCODING = __pyx_optional_args->ENCODING; - if (__pyx_optional_args->__pyx_n > 1) { - __pyx_v_ENCODING_ERR = __pyx_optional_args->ENCODING_ERR; - if (__pyx_optional_args->__pyx_n > 2) { - __pyx_v_CONTENT_ENCODING = __pyx_optional_args->CONTENT_ENCODING; - if (__pyx_optional_args->__pyx_n > 3) { - __pyx_v_SEC_WEBSOCKET_KEY1 = __pyx_optional_args->SEC_WEBSOCKET_KEY1; - if (__pyx_optional_args->__pyx_n > 4) { - __pyx_v_SUPPORTED = __pyx_optional_args->SUPPORTED; - } - } - } - } - } - } + __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)); - /* "aiohttp/_http_parser.pyx":169 - * SEC_WEBSOCKET_KEY1=hdrs.SEC_WEBSOCKET_KEY1, - * SUPPORTED=('gzip', 'deflate', 'br')): - * self._process_header() # <<<<<<<<<<<<<< - * - * method = cparser.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, 169, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "aiohttp/_http_parser.pyx":171 - * self._process_header() - * - * method = cparser.http_method_str( self._cparser.method) # <<<<<<<<<<<<<< - * should_close = not bool(cparser.http_should_keep_alive(self._cparser)) - * upgrade = bool(self._cparser.upgrade) - */ - __pyx_v_method = http_method_str(((enum http_method)__pyx_v_self->_cparser->method)); +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":172 +/* "aiohttp/_http_parser.pyx":103 + * cdef readonly object upgrade + * cdef readonly object chunked + * cdef readonly object url # yarl.URL # <<<<<<<<<<<<<< * - * method = cparser.http_method_str( self._cparser.method) - * should_close = not bool(cparser.http_should_keep_alive(self._cparser)) # <<<<<<<<<<<<<< - * upgrade = bool(self._cparser.upgrade) - * chunked = bool(self._cparser.flags & cparser.F_CHUNKED) + * def __init__(self, method, path, version, headers, raw_headers, */ - __pyx_t_1 = __Pyx_PyInt_From_int(http_should_keep_alive(__pyx_v_self->_cparser)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 172, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(0, 172, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_v_should_close = (!((!(!__pyx_t_2)) != 0)); - /* "aiohttp/_http_parser.pyx":173 - * method = cparser.http_method_str( self._cparser.method) - * should_close = not bool(cparser.http_should_keep_alive(self._cparser)) - * upgrade = bool(self._cparser.upgrade) # <<<<<<<<<<<<<< - * chunked = bool(self._cparser.flags & cparser.F_CHUNKED) - * +/* 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 */ - __pyx_t_1 = __Pyx_PyInt_From_unsigned_int(__pyx_v_self->_cparser->upgrade); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 173, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(0, 173, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyBool_FromLong((!(!__pyx_t_2))); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 173, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_upgrade = __pyx_t_1; - __pyx_t_1 = 0; - /* "aiohttp/_http_parser.pyx":174 - * should_close = not bool(cparser.http_should_keep_alive(self._cparser)) - * upgrade = bool(self._cparser.upgrade) - * chunked = bool(self._cparser.flags & cparser.F_CHUNKED) # <<<<<<<<<<<<<< - * - * raw_headers = tuple(self._raw_headers) +/* 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; + __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 = __Pyx_PyInt_From_unsigned_int((__pyx_v_self->_cparser->flags & F_CHUNKED)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 174, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(0, 174, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyBool_FromLong((!(!__pyx_t_2))); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 174, __pyx_L1_error) + __pyx_t_1 = PyTuple_New(10); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 5, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - __pyx_v_chunked = __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; - /* "aiohttp/_http_parser.pyx":176 - * chunked = bool(self._cparser.flags & cparser.F_CHUNKED) - * - * raw_headers = tuple(self._raw_headers) # <<<<<<<<<<<<<< - * headers = CIMultiDict(self._headers) - * + /* "(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,) */ - if (unlikely(__pyx_v_self->_raw_headers == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - __PYX_ERR(0, 176, __pyx_L1_error) - } - __pyx_t_1 = PyList_AsTuple(__pyx_v_self->_raw_headers); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 176, __pyx_L1_error) + __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_raw_headers = ((PyObject*)__pyx_t_1); + __pyx_v__dict = __pyx_t_1; __pyx_t_1 = 0; - /* "aiohttp/_http_parser.pyx":177 - * - * raw_headers = tuple(self._raw_headers) - * headers = CIMultiDict(self._headers) # <<<<<<<<<<<<<< - * - * if upgrade or self._cparser.method == 5: # cparser.CONNECT: + /* "(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_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_CIMultiDict); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 177, __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); - } - } - if (!__pyx_t_4) { - __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_v_self->_headers); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 177, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - } else { - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[2] = {__pyx_t_4, __pyx_v_self->_headers}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 177, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[2] = {__pyx_t_4, __pyx_v_self->_headers}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 177, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_5 = PyTuple_New(1+1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 177, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __pyx_t_4 = NULL; - __Pyx_INCREF(__pyx_v_self->_headers); - __Pyx_GIVEREF(__pyx_v_self->_headers); - PyTuple_SET_ITEM(__pyx_t_5, 0+1, __pyx_v_self->_headers); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 177, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_headers = __pyx_t_1; - __pyx_t_1 = 0; + __pyx_t_2 = (__pyx_v__dict != Py_None); + __pyx_t_3 = (__pyx_t_2 != 0); + if (__pyx_t_3) { - /* "aiohttp/_http_parser.pyx":179 - * headers = CIMultiDict(self._headers) - * - * if upgrade or self._cparser.method == 5: # cparser.CONNECT: # <<<<<<<<<<<<<< - * self._upgraded = True - * + /* "(tree fragment)":8 + * _dict = getattr(self, '__dict__', None) + * if _dict is not None: + * state += (_dict,) # <<<<<<<<<<<<<< + * use_setstate = True + * else: */ - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_upgrade); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 179, __pyx_L1_error) - if (!__pyx_t_6) { - } else { - __pyx_t_2 = __pyx_t_6; - goto __pyx_L4_bool_binop_done; - } - __pyx_t_6 = ((__pyx_v_self->_cparser->method == 5) != 0); - __pyx_t_2 = __pyx_t_6; - __pyx_L4_bool_binop_done:; - if (__pyx_t_2) { + __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; - /* "aiohttp/_http_parser.pyx":180 - * - * if upgrade or self._cparser.method == 5: # cparser.CONNECT: - * self._upgraded = True # <<<<<<<<<<<<<< - * - * # do not support old websocket spec + /* "(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_self->_upgraded = 1; + __pyx_v_use_setstate = 1; - /* "aiohttp/_http_parser.pyx":179 - * headers = CIMultiDict(self._headers) - * - * if upgrade or self._cparser.method == 5: # cparser.CONNECT: # <<<<<<<<<<<<<< - * self._upgraded = True - * + /* "(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; } - /* "aiohttp/_http_parser.pyx":183 - * - * # do not support old websocket spec - * if SEC_WEBSOCKET_KEY1 in headers: # <<<<<<<<<<<<<< - * raise InvalidHeader(SEC_WEBSOCKET_KEY1) - * - */ - __pyx_t_2 = (__Pyx_PySequence_ContainsTF(__pyx_v_SEC_WEBSOCKET_KEY1, __pyx_v_headers, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(0, 183, __pyx_L1_error) - __pyx_t_6 = (__pyx_t_2 != 0); - if (unlikely(__pyx_t_6)) { - - /* "aiohttp/_http_parser.pyx":184 - * # do not support old websocket spec - * if SEC_WEBSOCKET_KEY1 in headers: - * raise InvalidHeader(SEC_WEBSOCKET_KEY1) # <<<<<<<<<<<<<< - * - * encoding = None + /* "(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 */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_InvalidHeader); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 184, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = NULL; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - } + /*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) { - __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_v_SEC_WEBSOCKET_KEY1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 184, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); } else { - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[2] = {__pyx_t_5, __pyx_v_SEC_WEBSOCKET_KEY1}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 184, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[2] = {__pyx_t_5, __pyx_v_SEC_WEBSOCKET_KEY1}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 184, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_4 = PyTuple_New(1+1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 184, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __pyx_t_5 = NULL; - __Pyx_INCREF(__pyx_v_SEC_WEBSOCKET_KEY1); - __Pyx_GIVEREF(__pyx_v_SEC_WEBSOCKET_KEY1); - PyTuple_SET_ITEM(__pyx_t_4, 0+1, __pyx_v_SEC_WEBSOCKET_KEY1); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 184, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } + __pyx_t_3 = __pyx_t_5; + goto __pyx_L4_bool_binop_done; } - __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, 184, __pyx_L1_error) - - /* "aiohttp/_http_parser.pyx":183 - * - * # do not support old websocket spec - * if SEC_WEBSOCKET_KEY1 in headers: # <<<<<<<<<<<<<< - * raise InvalidHeader(SEC_WEBSOCKET_KEY1) - * - */ + __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:; - /* "aiohttp/_http_parser.pyx":186 - * raise InvalidHeader(SEC_WEBSOCKET_KEY1) - * - * encoding = None # <<<<<<<<<<<<<< - * enc = headers.get(CONTENT_ENCODING) - * if enc: + /* "(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_INCREF(Py_None); - __pyx_v_encoding = Py_None; + __pyx_t_3 = (__pyx_v_use_setstate != 0); + if (__pyx_t_3) { - /* "aiohttp/_http_parser.pyx":187 - * - * encoding = None - * enc = headers.get(CONTENT_ENCODING) # <<<<<<<<<<<<<< - * if enc: - * enc = enc.lower() + /* "(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_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_headers, __pyx_n_s_get); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 187, __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); - } - } - if (!__pyx_t_4) { - __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_v_CONTENT_ENCODING); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 187, __pyx_L1_error) + __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); - } else { - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[2] = {__pyx_t_4, __pyx_v_CONTENT_ENCODING}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 187, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[2] = {__pyx_t_4, __pyx_v_CONTENT_ENCODING}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 187, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else - #endif - { - __pyx_t_5 = PyTuple_New(1+1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 187, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __pyx_t_4 = NULL; - __Pyx_INCREF(__pyx_v_CONTENT_ENCODING); - __Pyx_GIVEREF(__pyx_v_CONTENT_ENCODING); - PyTuple_SET_ITEM(__pyx_t_5, 0+1, __pyx_v_CONTENT_ENCODING); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 187, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_enc = __pyx_t_1; - __pyx_t_1 = 0; + __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; - /* "aiohttp/_http_parser.pyx":188 - * encoding = None - * enc = headers.get(CONTENT_ENCODING) - * if enc: # <<<<<<<<<<<<<< - * enc = enc.lower() - * if enc in SUPPORTED: + /* "(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_6 = __Pyx_PyObject_IsTrue(__pyx_v_enc); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 188, __pyx_L1_error) - if (__pyx_t_6) { + } - /* "aiohttp/_http_parser.pyx":189 - * enc = headers.get(CONTENT_ENCODING) - * if enc: - * enc = enc.lower() # <<<<<<<<<<<<<< - * if enc in SUPPORTED: - * encoding = enc + /* "(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) */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_enc, __pyx_n_s_lower); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 189, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_5 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - } - } - if (__pyx_t_5) { - __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_5); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 189, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } else { - __pyx_t_1 = __Pyx_PyObject_CallNoArg(__pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 189, __pyx_L1_error) - } + /*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_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF_SET(__pyx_v_enc, __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; + } - /* "aiohttp/_http_parser.pyx":190 - * if enc: - * enc = enc.lower() - * if enc in SUPPORTED: # <<<<<<<<<<<<<< - * encoding = enc - * + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict */ - __pyx_t_6 = (__Pyx_PySequence_ContainsTF(__pyx_v_enc, __pyx_v_SUPPORTED, Py_EQ)); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 190, __pyx_L1_error) - __pyx_t_2 = (__pyx_t_6 != 0); - if (__pyx_t_2) { - /* "aiohttp/_http_parser.pyx":191 - * enc = enc.lower() - * if enc in SUPPORTED: - * encoding = enc # <<<<<<<<<<<<<< - * - * if self._cparser.type == cparser.HTTP_REQUEST: - */ - __Pyx_INCREF(__pyx_v_enc); - __Pyx_DECREF_SET(__pyx_v_encoding, __pyx_v_enc); + /* 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; +} - /* "aiohttp/_http_parser.pyx":190 - * if enc: - * enc = enc.lower() - * if enc in SUPPORTED: # <<<<<<<<<<<<<< - * encoding = enc - * +/* "(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) */ - } - /* "aiohttp/_http_parser.pyx":188 - * encoding = None - * enc = headers.get(CONTENT_ENCODING) - * if enc: # <<<<<<<<<<<<<< - * enc = enc.lower() - * if enc in SUPPORTED: +/* 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; + __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; - /* "aiohttp/_http_parser.pyx":193 - * encoding = enc - * - * if self._cparser.type == cparser.HTTP_REQUEST: # <<<<<<<<<<<<<< - * msg = RawRequestMessage( - * method.decode(ENCODING, ENCODING_ERR), self._path, + /* "(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) */ - __pyx_t_2 = ((__pyx_v_self->_cparser->type == HTTP_REQUEST) != 0); - if (__pyx_t_2) { - /* "aiohttp/_http_parser.pyx":194 + /* 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":167 + * return ret * - * if self._cparser.type == cparser.HTTP_REQUEST: - * msg = RawRequestMessage( # <<<<<<<<<<<<<< - * method.decode(ENCODING, ENCODING_ERR), self._path, - * self.http_version(), headers, raw_headers, + * cdef _new_request_message(str method, # <<<<<<<<<<<<<< + * str path, + * object version, */ - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_RawRequestMessage); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 194, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - /* "aiohttp/_http_parser.pyx":195 - * if self._cparser.type == cparser.HTTP_REQUEST: - * msg = RawRequestMessage( - * method.decode(ENCODING, ENCODING_ERR), self._path, # <<<<<<<<<<<<<< - * self.http_version(), headers, raw_headers, - * should_close, encoding, upgrade, chunked, self._url) - */ - __pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_method); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 195, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_decode); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 195, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = NULL; - __pyx_t_8 = 0; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_7))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_7); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_7, function); - __pyx_t_8 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[3] = {__pyx_t_4, __pyx_v_ENCODING, __pyx_v_ENCODING_ERR}; - __pyx_t_5 = __Pyx_PyFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 195, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_GOTREF(__pyx_t_5); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[3] = {__pyx_t_4, __pyx_v_ENCODING, __pyx_v_ENCODING_ERR}; - __pyx_t_5 = __Pyx_PyCFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 195, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_GOTREF(__pyx_t_5); - } else - #endif - { - __pyx_t_9 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 195, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - if (__pyx_t_4) { - __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_4); __pyx_t_4 = NULL; - } - __Pyx_INCREF(__pyx_v_ENCODING); - __Pyx_GIVEREF(__pyx_v_ENCODING); - PyTuple_SET_ITEM(__pyx_t_9, 0+__pyx_t_8, __pyx_v_ENCODING); - __Pyx_INCREF(__pyx_v_ENCODING_ERR); - __Pyx_GIVEREF(__pyx_v_ENCODING_ERR); - PyTuple_SET_ITEM(__pyx_t_9, 1+__pyx_t_8, __pyx_v_ENCODING_ERR); - __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_9, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 195, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; +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; + __Pyx_RefNannySetupContext("_new_request_message", 0); - /* "aiohttp/_http_parser.pyx":196 - * msg = RawRequestMessage( - * method.decode(ENCODING, ENCODING_ERR), self._path, - * self.http_version(), headers, raw_headers, # <<<<<<<<<<<<<< - * should_close, encoding, upgrade, chunked, self._url) - * else: - */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_http_version); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 196, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_4 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_9))) { - __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_9); - if (likely(__pyx_t_4)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_9); - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_9, function); - } - } - if (__pyx_t_4) { - __pyx_t_7 = __Pyx_PyObject_CallOneArg(__pyx_t_9, __pyx_t_4); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 196, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } else { - __pyx_t_7 = __Pyx_PyObject_CallNoArg(__pyx_t_9); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 196, __pyx_L1_error) - } - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + /* "aiohttp/_http_parser.pyx":178 + * 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, 178, __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":197 - * method.decode(ENCODING, ENCODING_ERR), self._path, - * self.http_version(), headers, raw_headers, - * should_close, encoding, upgrade, chunked, self._url) # <<<<<<<<<<<<<< - * else: - * msg = RawResponseMessage( + /* "aiohttp/_http_parser.pyx":179 + * 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":180 + * 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":181 + * 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":182 + * 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":183 + * 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":184 + * ret.headers = headers + * ret.raw_headers = raw_headers + * ret.should_close = should_close # <<<<<<<<<<<<<< + * ret.compression = compression + * ret.upgrade = upgrade */ - __pyx_t_9 = __Pyx_PyBool_FromLong(__pyx_v_should_close); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 197, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_4 = NULL; - __pyx_t_8 = 0; - 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_8 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[11] = {__pyx_t_4, __pyx_t_5, __pyx_v_self->_path, __pyx_t_7, __pyx_v_headers, __pyx_v_raw_headers, __pyx_t_9, __pyx_v_encoding, __pyx_v_upgrade, __pyx_v_chunked, __pyx_v_self->_url}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_8, 10+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 194, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[11] = {__pyx_t_4, __pyx_t_5, __pyx_v_self->_path, __pyx_t_7, __pyx_v_headers, __pyx_v_raw_headers, __pyx_t_9, __pyx_v_encoding, __pyx_v_upgrade, __pyx_v_chunked, __pyx_v_self->_url}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_8, 10+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 194, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } else - #endif - { - __pyx_t_10 = PyTuple_New(10+__pyx_t_8); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 194, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_10); - if (__pyx_t_4) { - __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_4); __pyx_t_4 = NULL; - } - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_10, 0+__pyx_t_8, __pyx_t_5); - __Pyx_INCREF(__pyx_v_self->_path); - __Pyx_GIVEREF(__pyx_v_self->_path); - PyTuple_SET_ITEM(__pyx_t_10, 1+__pyx_t_8, __pyx_v_self->_path); - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_10, 2+__pyx_t_8, __pyx_t_7); - __Pyx_INCREF(__pyx_v_headers); - __Pyx_GIVEREF(__pyx_v_headers); - PyTuple_SET_ITEM(__pyx_t_10, 3+__pyx_t_8, __pyx_v_headers); - __Pyx_INCREF(__pyx_v_raw_headers); - __Pyx_GIVEREF(__pyx_v_raw_headers); - PyTuple_SET_ITEM(__pyx_t_10, 4+__pyx_t_8, __pyx_v_raw_headers); - __Pyx_GIVEREF(__pyx_t_9); - PyTuple_SET_ITEM(__pyx_t_10, 5+__pyx_t_8, __pyx_t_9); - __Pyx_INCREF(__pyx_v_encoding); - __Pyx_GIVEREF(__pyx_v_encoding); - PyTuple_SET_ITEM(__pyx_t_10, 6+__pyx_t_8, __pyx_v_encoding); - __Pyx_INCREF(__pyx_v_upgrade); - __Pyx_GIVEREF(__pyx_v_upgrade); - PyTuple_SET_ITEM(__pyx_t_10, 7+__pyx_t_8, __pyx_v_upgrade); - __Pyx_INCREF(__pyx_v_chunked); - __Pyx_GIVEREF(__pyx_v_chunked); - PyTuple_SET_ITEM(__pyx_t_10, 8+__pyx_t_8, __pyx_v_chunked); - __Pyx_INCREF(__pyx_v_self->_url); - __Pyx_GIVEREF(__pyx_v_self->_url); - PyTuple_SET_ITEM(__pyx_t_10, 9+__pyx_t_8, __pyx_v_self->_url); - __pyx_t_5 = 0; - __pyx_t_7 = 0; - __pyx_t_9 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_10, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 194, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_msg = __pyx_t_1; - __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_v_should_close); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 184, __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":193 - * encoding = enc - * - * if self._cparser.type == cparser.HTTP_REQUEST: # <<<<<<<<<<<<<< - * msg = RawRequestMessage( - * method.decode(ENCODING, ENCODING_ERR), self._path, + /* "aiohttp/_http_parser.pyx":185 + * 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":186 + * ret.should_close = should_close + * ret.compression = compression + * ret.upgrade = upgrade # <<<<<<<<<<<<<< + * ret.chunked = chunked + * ret.url = url */ - goto __pyx_L9; - } + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_v_upgrade); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 186, __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":199 - * should_close, encoding, upgrade, chunked, self._url) - * else: - * msg = RawResponseMessage( # <<<<<<<<<<<<<< - * self.http_version(), self._cparser.status_code, self._reason, - * headers, raw_headers, should_close, encoding, + /* "aiohttp/_http_parser.pyx":187 + * ret.compression = compression + * ret.upgrade = upgrade + * ret.chunked = chunked # <<<<<<<<<<<<<< + * ret.url = url + * return ret */ - /*else*/ { - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_RawResponseMessage); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 199, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_v_chunked); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 187, __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":200 - * else: - * msg = RawResponseMessage( - * self.http_version(), self._cparser.status_code, self._reason, # <<<<<<<<<<<<<< - * headers, raw_headers, should_close, encoding, - * upgrade, chunked) + /* "aiohttp/_http_parser.pyx":188 + * 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":189 + * ret.chunked = chunked + * ret.url = url + * return ret # <<<<<<<<<<<<<< + * + * */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_http_version); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 200, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_7 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_9))) { - __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_9); - if (likely(__pyx_t_7)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_9); - __Pyx_INCREF(__pyx_t_7); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_9, function); - } - } - if (__pyx_t_7) { - __pyx_t_10 = __Pyx_PyObject_CallOneArg(__pyx_t_9, __pyx_t_7); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 200, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } else { - __pyx_t_10 = __Pyx_PyObject_CallNoArg(__pyx_t_9); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 200, __pyx_L1_error) - } - __Pyx_GOTREF(__pyx_t_10); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_9 = __Pyx_PyInt_From_unsigned_int(__pyx_v_self->_cparser->status_code); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 200, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_ret)); + __pyx_r = ((PyObject *)__pyx_v_ret); + goto __pyx_L0; - /* "aiohttp/_http_parser.pyx":201 - * msg = RawResponseMessage( - * self.http_version(), self._cparser.status_code, self._reason, - * headers, raw_headers, should_close, encoding, # <<<<<<<<<<<<<< - * upgrade, chunked) + /* "aiohttp/_http_parser.pyx":167 + * return ret * + * cdef _new_request_message(str method, # <<<<<<<<<<<<<< + * str path, + * object version, */ - __pyx_t_7 = __Pyx_PyBool_FromLong(__pyx_v_should_close); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 201, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - /* "aiohttp/_http_parser.pyx":202 - * self.http_version(), self._cparser.status_code, self._reason, - * headers, raw_headers, should_close, encoding, - * upgrade, chunked) # <<<<<<<<<<<<<< + /* 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":204 + * cdef readonly object chunked * - * if (self._cparser.content_length > 0 or chunked or + * def __init__(self, version, code, reason, headers, raw_headers, # <<<<<<<<<<<<<< + * should_close, compression, upgrade, chunked): + * self.version = version */ - __pyx_t_5 = NULL; - __pyx_t_8 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_5)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - __pyx_t_8 = 1; + +/* 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_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; } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[10] = {__pyx_t_5, __pyx_t_10, __pyx_t_9, __pyx_v_self->_reason, __pyx_v_headers, __pyx_v_raw_headers, __pyx_t_7, __pyx_v_encoding, __pyx_v_upgrade, __pyx_v_chunked}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_8, 9+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 199, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[10] = {__pyx_t_5, __pyx_t_10, __pyx_t_9, __pyx_v_self->_reason, __pyx_v_headers, __pyx_v_raw_headers, __pyx_t_7, __pyx_v_encoding, __pyx_v_upgrade, __pyx_v_chunked}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_8, 9+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 199, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } else - #endif - { - __pyx_t_4 = PyTuple_New(9+__pyx_t_8); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 199, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - if (__pyx_t_5) { - __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __pyx_t_5 = NULL; + 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, 204, __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, 204, __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, 204, __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, 204, __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, 204, __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, 204, __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, 204, __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, 204, __pyx_L3_error) + } } - __Pyx_GIVEREF(__pyx_t_10); - PyTuple_SET_ITEM(__pyx_t_4, 0+__pyx_t_8, __pyx_t_10); - __Pyx_GIVEREF(__pyx_t_9); - PyTuple_SET_ITEM(__pyx_t_4, 1+__pyx_t_8, __pyx_t_9); - __Pyx_INCREF(__pyx_v_self->_reason); - __Pyx_GIVEREF(__pyx_v_self->_reason); - PyTuple_SET_ITEM(__pyx_t_4, 2+__pyx_t_8, __pyx_v_self->_reason); - __Pyx_INCREF(__pyx_v_headers); - __Pyx_GIVEREF(__pyx_v_headers); - PyTuple_SET_ITEM(__pyx_t_4, 3+__pyx_t_8, __pyx_v_headers); - __Pyx_INCREF(__pyx_v_raw_headers); - __Pyx_GIVEREF(__pyx_v_raw_headers); - PyTuple_SET_ITEM(__pyx_t_4, 4+__pyx_t_8, __pyx_v_raw_headers); - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_4, 5+__pyx_t_8, __pyx_t_7); - __Pyx_INCREF(__pyx_v_encoding); - __Pyx_GIVEREF(__pyx_v_encoding); - PyTuple_SET_ITEM(__pyx_t_4, 6+__pyx_t_8, __pyx_v_encoding); - __Pyx_INCREF(__pyx_v_upgrade); - __Pyx_GIVEREF(__pyx_v_upgrade); - PyTuple_SET_ITEM(__pyx_t_4, 7+__pyx_t_8, __pyx_v_upgrade); - __Pyx_INCREF(__pyx_v_chunked); - __Pyx_GIVEREF(__pyx_v_chunked); - PyTuple_SET_ITEM(__pyx_t_4, 8+__pyx_t_8, __pyx_v_chunked); - __pyx_t_10 = 0; - __pyx_t_9 = 0; - __pyx_t_7 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 199, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_v_msg = __pyx_t_1; - __pyx_t_1 = 0; + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) __PYX_ERR(0, 204, __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]; } - __pyx_L9:; + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 1, 9, 9, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 204, __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); - /* "aiohttp/_http_parser.pyx":204 - * upgrade, chunked) - * - * if (self._cparser.content_length > 0 or chunked or # <<<<<<<<<<<<<< - * self._cparser.method == 5): # CONNECT: 5 - * payload = StreamReader( - */ - __pyx_t_6 = ((__pyx_v_self->_cparser->content_length > 0) != 0); - if (!__pyx_t_6) { - } else { - __pyx_t_2 = __pyx_t_6; - goto __pyx_L11_bool_binop_done; - } - __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_chunked); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 204, __pyx_L1_error) - if (!__pyx_t_6) { - } else { - __pyx_t_2 = __pyx_t_6; - goto __pyx_L11_bool_binop_done; - } + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "aiohttp/_http_parser.pyx":205 - * - * if (self._cparser.content_length > 0 or chunked or - * self._cparser.method == 5): # CONNECT: 5 # <<<<<<<<<<<<<< - * payload = StreamReader( - * self._protocol, timer=self._timer, loop=self._loop) - */ - __pyx_t_6 = ((__pyx_v_self->_cparser->method == 5) != 0); - __pyx_t_2 = __pyx_t_6; - __pyx_L11_bool_binop_done:; +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; + __Pyx_RefNannySetupContext("__init__", 0); + + /* "aiohttp/_http_parser.pyx":206 + * 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":207 + * 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, 207, __pyx_L1_error) + __pyx_v_self->code = __pyx_t_1; + + /* "aiohttp/_http_parser.pyx":208 + * 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, 208, __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":209 + * 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":210 + * 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":211 + * 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":212 + * 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":213 + * 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":214 + * 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":204 - * upgrade, chunked) + * cdef readonly object chunked * - * if (self._cparser.content_length > 0 or chunked or # <<<<<<<<<<<<<< - * self._cparser.method == 5): # CONNECT: 5 - * payload = StreamReader( + * def __init__(self, version, code, reason, headers, raw_headers, # <<<<<<<<<<<<<< + * should_close, compression, upgrade, chunked): + * self.version = version */ - if (__pyx_t_2) { - /* "aiohttp/_http_parser.pyx":206 - * if (self._cparser.content_length > 0 or chunked or - * self._cparser.method == 5): # CONNECT: 5 - * payload = StreamReader( # <<<<<<<<<<<<<< - * self._protocol, timer=self._timer, loop=self._loop) - * else: - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_StreamReader); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 206, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); + /* 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":207 - * self._cparser.method == 5): # CONNECT: 5 - * payload = StreamReader( - * self._protocol, timer=self._timer, loop=self._loop) # <<<<<<<<<<<<<< - * else: - * payload = EMPTY_PAYLOAD +/* "aiohttp/_http_parser.pyx":216 + * self.chunked = chunked + * + * def __repr__(self): # <<<<<<<<<<<<<< + * info = [] + * info.append(("version", self.version)) */ - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 206, __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); - __pyx_t_4 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 207, __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, 207, __pyx_L1_error) - if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_loop, __pyx_v_self->_loop) < 0) __PYX_ERR(0, 207, __pyx_L1_error) - /* "aiohttp/_http_parser.pyx":206 - * if (self._cparser.content_length > 0 or chunked or - * self._cparser.method == 5): # CONNECT: 5 - * payload = StreamReader( # <<<<<<<<<<<<<< - * self._protocol, timer=self._timer, loop=self._loop) - * else: - */ - __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 206, __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_payload = __pyx_t_7; - __pyx_t_7 = 0; +/* 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)); - /* "aiohttp/_http_parser.pyx":204 - * upgrade, chunked) + /* 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":227 + * info.append(("upgrade", self.upgrade)) + * info.append(("chunked", self.chunked)) + * sinfo = ', '.join(name + '=' + repr(val) for name, val in info) # <<<<<<<<<<<<<< + * return '' * - * if (self._cparser.content_length > 0 or chunked or # <<<<<<<<<<<<<< - * self._cparser.method == 5): # CONNECT: 5 - * payload = StreamReader( */ - goto __pyx_L10; - } - /* "aiohttp/_http_parser.pyx":209 - * self._protocol, timer=self._timer, loop=self._loop) - * else: - * payload = EMPTY_PAYLOAD # <<<<<<<<<<<<<< - * - * self._payload = payload - */ - /*else*/ { - __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s_EMPTY_PAYLOAD); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 209, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_v_payload = __pyx_t_7; - __pyx_t_7 = 0; +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 + __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, 227, __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, 227, __pyx_L1_error) + __Pyx_DECREF(__pyx_cur_scope); + __Pyx_RefNannyFinishContext(); + return (PyObject *) gen; } - __pyx_L10:; - /* "aiohttp/_http_parser.pyx":211 - * 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; + /* 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; +} - /* "aiohttp/_http_parser.pyx":212 - * - * self._payload = payload - * if encoding is not None and self._auto_decompress: # <<<<<<<<<<<<<< - * self._payload = DeflateBuffer(payload, encoding) - * - */ - __pyx_t_6 = (__pyx_v_encoding != Py_None); - __pyx_t_11 = (__pyx_t_6 != 0); - if (__pyx_t_11) { - } else { - __pyx_t_2 = __pyx_t_11; - goto __pyx_L15_bool_binop_done; +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 *); + __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_t_11 = (__pyx_v_self->_auto_decompress != 0); - __pyx_t_2 = __pyx_t_11; - __pyx_L15_bool_binop_done:; - if (__pyx_t_2) { - - /* "aiohttp/_http_parser.pyx":213 - * self._payload = payload - * if encoding is not None and self._auto_decompress: - * self._payload = DeflateBuffer(payload, encoding) # <<<<<<<<<<<<<< - * - * if not self._response_with_body: - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_DeflateBuffer); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 213, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = NULL; - __pyx_t_8 = 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_8 = 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_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 213, __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_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 213, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_GOTREF(__pyx_t_7); - } else + __pyx_L3_first_run:; + if (unlikely(!__pyx_sent_value)) __PYX_ERR(0, 227, __pyx_L1_error) + __pyx_r = PyList_New(0); if (unlikely(!__pyx_r)) __PYX_ERR(0, 227, __pyx_L1_error) + __Pyx_GOTREF(__pyx_r); + if (unlikely(!__pyx_cur_scope->__pyx_outer_scope->__pyx_v_info)) { __Pyx_RaiseClosureNameError("info"); __PYX_ERR(0, 227, __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, 227, __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, 227, __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, 227, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); #endif - { - __pyx_t_1 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 213, __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; + 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, 227, __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_v_payload); - __Pyx_GIVEREF(__pyx_v_payload); - PyTuple_SET_ITEM(__pyx_t_1, 0+__pyx_t_8, __pyx_v_payload); - __Pyx_INCREF(__pyx_v_encoding); - __Pyx_GIVEREF(__pyx_v_encoding); - PyTuple_SET_ITEM(__pyx_t_1, 1+__pyx_t_8, __pyx_v_encoding); - __pyx_t_7 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_1, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 213, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __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, 227, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 227, __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, 227, __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, 227, __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, 227, __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, 227, __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, 227, __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, 227, __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, 227, __pyx_L1_error) __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":212 - * - * self._payload = payload - * if encoding is not None and self._auto_decompress: # <<<<<<<<<<<<<< - * self._payload = DeflateBuffer(payload, encoding) - * - */ - } - - /* "aiohttp/_http_parser.pyx":215 - * self._payload = DeflateBuffer(payload, encoding) - * - * if not self._response_with_body: # <<<<<<<<<<<<<< - * payload = EMPTY_PAYLOAD - * - */ - __pyx_t_2 = ((!(__pyx_v_self->_response_with_body != 0)) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_http_parser.pyx":216 - * - * if not self._response_with_body: - * payload = EMPTY_PAYLOAD # <<<<<<<<<<<<<< - * - * self._messages.append((msg, payload)) - */ - __pyx_t_7 = __Pyx_GetModuleGlobalName(__pyx_n_s_EMPTY_PAYLOAD); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 216, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF_SET(__pyx_v_payload, __pyx_t_7); - __pyx_t_7 = 0; - - /* "aiohttp/_http_parser.pyx":215 - * self._payload = DeflateBuffer(payload, encoding) - * - * if not self._response_with_body: # <<<<<<<<<<<<<< - * payload = EMPTY_PAYLOAD - * - */ - } - - /* "aiohttp/_http_parser.pyx":218 - * 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, 218, __pyx_L1_error) } - __pyx_t_7 = PyTuple_New(2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 218, __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_12 = __Pyx_PyList_Append(__pyx_v_self->_messages, __pyx_t_7); if (unlikely(__pyx_t_12 == ((int)-1))) __PYX_ERR(0, 218, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - - /* "aiohttp/_http_parser.pyx":163 - * self._raw_header_value += raw_val - * - * cdef _on_headers_complete(self, # <<<<<<<<<<<<<< - * ENCODING='utf-8', - * ENCODING_ERR='surrogateescape', - */ + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + CYTHON_MAYBE_UNUSED_VAR(__pyx_cur_scope); /* function exit code */ - __pyx_r = Py_None; __Pyx_INCREF(Py_None); 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_7); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_XDECREF(__pyx_t_10); - __Pyx_AddTraceback("aiohttp._http_parser.HttpParser._on_headers_complete", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = 0; + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("genexpr", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_L0:; - __Pyx_XDECREF(__pyx_v_upgrade); - __Pyx_XDECREF(__pyx_v_chunked); - __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); + #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":220 - * self._messages.append((msg, payload)) +/* "aiohttp/_http_parser.pyx":216 + * self.chunked = chunked * - * cdef _on_message_complete(self): # <<<<<<<<<<<<<< - * self._payload.feed_eof() - * self._payload = None + * def __repr__(self): # <<<<<<<<<<<<<< + * info = [] + * info.append(("version", self.version)) */ -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_message_complete(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self) { +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_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; + int __pyx_t_2; PyObject *__pyx_t_3 = NULL; - __Pyx_RefNannySetupContext("_on_message_complete", 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, 216, __pyx_L1_error) + } else { + __Pyx_GOTREF(__pyx_cur_scope); + } - /* "aiohttp/_http_parser.pyx":221 - * - * cdef _on_message_complete(self): - * self._payload.feed_eof() # <<<<<<<<<<<<<< - * self._payload = None + /* "aiohttp/_http_parser.pyx":217 * + * def __repr__(self): + * info = [] # <<<<<<<<<<<<<< + * info.append(("version", self.version)) + * info.append(("code", self.code)) */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self->_payload, __pyx_n_s_feed_eof); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 221, __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); - } - } - if (__pyx_t_3) { - __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 221, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } else { - __pyx_t_1 = __Pyx_PyObject_CallNoArg(__pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 221, __pyx_L1_error) - } + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 217, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_GIVEREF(__pyx_t_1); + __pyx_cur_scope->__pyx_v_info = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "aiohttp/_http_parser.pyx":218 + * 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, 218, __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, 218, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "aiohttp/_http_parser.pyx":222 - * cdef _on_message_complete(self): - * self._payload.feed_eof() - * self._payload = None # <<<<<<<<<<<<<< - * - * cdef _on_chunk_header(self): + /* "aiohttp/_http_parser.pyx":219 + * info = [] + * info.append(("version", self.version)) + * info.append(("code", self.code)) # <<<<<<<<<<<<<< + * info.append(("reason", self.reason)) + * info.append(("headers", self.headers)) */ - __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; + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->code); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 219, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 219, __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, 219, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "aiohttp/_http_parser.pyx":220 - * self._messages.append((msg, payload)) - * - * cdef _on_message_complete(self): # <<<<<<<<<<<<<< - * self._payload.feed_eof() - * self._payload = None + * 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, 220, __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, 220, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - /* 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":221 + * 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, 221, __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, 221, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; -/* "aiohttp/_http_parser.pyx":224 - * self._payload = None - * - * cdef _on_chunk_header(self): # <<<<<<<<<<<<<< - * self._payload.begin_http_chunk_receiving() - * + /* "aiohttp/_http_parser.pyx":222 + * 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, 222, __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, 222, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; -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; - __Pyx_RefNannySetupContext("_on_chunk_header", 0); + /* "aiohttp/_http_parser.pyx":223 + * 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, 223, __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, 223, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "aiohttp/_http_parser.pyx":224 + * 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, 224, __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, 224, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "aiohttp/_http_parser.pyx":225 + * 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, 225, __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, 225, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "aiohttp/_http_parser.pyx":226 + * 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, 226, __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, 226, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "aiohttp/_http_parser.pyx":227 + * info.append(("upgrade", self.upgrade)) + * info.append(("chunked", self.chunked)) + * sinfo = ', '.join(name + '=' + repr(val) for name, val in info) # <<<<<<<<<<<<<< + * return '' * - * 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, 225, __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); - } - } - if (__pyx_t_3) { - __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 225, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } else { - __pyx_t_1 = __Pyx_PyObject_CallNoArg(__pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 225, __pyx_L1_error) - } + __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, 227, __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, 227, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __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, 227, __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":224 - * self._payload = None + /* "aiohttp/_http_parser.pyx":228 + * info.append(("chunked", self.chunked)) + * sinfo = ', '.join(name + '=' + repr(val) for name, val in info) + * return '' # <<<<<<<<<<<<<< * - * cdef _on_chunk_header(self): # <<<<<<<<<<<<<< - * self._payload.begin_http_chunk_receiving() * */ + __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, 228, __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, 228, __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":216 + * self.chunked = chunked + * + * def __repr__(self): # <<<<<<<<<<<<<< + * info = [] + * info.append(("version", self.version)) + */ /* 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_AddTraceback("aiohttp._http_parser.RawResponseMessage.__repr__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; __pyx_L0:; + __Pyx_XDECREF(__pyx_v_sinfo); + __Pyx_DECREF(((PyObject *)__pyx_cur_scope)); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "aiohttp/_http_parser.pyx":227 - * self._payload.begin_http_chunk_receiving() - * - * cdef _on_chunk_complete(self): # <<<<<<<<<<<<<< - * self._payload.end_http_chunk_receiving() - * +/* "aiohttp/_http_parser.pyx":194 + * @cython.freelist(DEFAULT_FREELIST_SIZE) + * cdef class RawResponseMessage: + * cdef readonly object version # HttpVersion # <<<<<<<<<<<<<< + * cdef readonly int code + * cdef readonly str reason */ -static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__on_chunk_complete(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self) { +/* 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 - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - __Pyx_RefNannySetupContext("_on_chunk_complete", 0); + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->version); + __pyx_r = __pyx_v_self->version; + goto __pyx_L0; - /* "aiohttp/_http_parser.pyx":228 - * - * 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, 228, __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); - } - } - if (__pyx_t_3) { - __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 228, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } else { - __pyx_t_1 = __Pyx_PyObject_CallNoArg(__pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 228, __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; + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "aiohttp/_http_parser.pyx":227 - * self._payload.begin_http_chunk_receiving() - * - * cdef _on_chunk_complete(self): # <<<<<<<<<<<<<< - * self._payload.end_http_chunk_receiving() - * +/* "aiohttp/_http_parser.pyx":195 + * 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_r = Py_None; __Pyx_INCREF(Py_None); + __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; + __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, 195, __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_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_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":230 - * self._payload.end_http_chunk_receiving() - * - * cdef object _on_status_complete(self): # <<<<<<<<<<<<<< - * pass - * +/* "aiohttp/_http_parser.pyx":196 + * cdef readonly object version # HttpVersion + * cdef readonly int code + * cdef readonly str reason # <<<<<<<<<<<<<< + * cdef readonly object headers # CIMultiDict + * cdef readonly object raw_headers # tuple */ -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) { +/* 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("_on_status_complete", 0); + __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_r = Py_None; __Pyx_INCREF(Py_None); + __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "aiohttp/_http_parser.pyx":235 - * ### Public API ### - * - * def http_version(self): # <<<<<<<<<<<<<< - * cdef cparser.http_parser* parser = self._cparser - * +/* "aiohttp/_http_parser.pyx":197 + * 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_10HttpParser_5http_version(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_10HttpParser_5http_version(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { +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("http_version (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_10HttpParser_4http_version(((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)__pyx_v_self)); + __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_10HttpParser_4http_version(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self) { - struct http_parser *__pyx_v_parser; +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 - struct http_parser *__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; - __Pyx_RefNannySetupContext("http_version", 0); + __Pyx_RefNannySetupContext("__get__", 0); + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v_self->headers); + __pyx_r = __pyx_v_self->headers; + goto __pyx_L0; - /* "aiohttp/_http_parser.pyx":236 - * - * def http_version(self): - * cdef cparser.http_parser* parser = self._cparser # <<<<<<<<<<<<<< - * - * if parser.http_major == 1: - */ - __pyx_t_1 = __pyx_v_self->_cparser; - __pyx_v_parser = __pyx_t_1; + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "aiohttp/_http_parser.pyx":238 - * cdef cparser.http_parser* parser = self._cparser - * - * if parser.http_major == 1: # <<<<<<<<<<<<<< - * if parser.http_minor == 0: - * return HttpVersion10 +/* "aiohttp/_http_parser.pyx":198 + * cdef readonly str reason + * cdef readonly object headers # CIMultiDict + * cdef readonly object raw_headers # tuple # <<<<<<<<<<<<<< + * cdef readonly object should_close + * cdef readonly object compression */ - __pyx_t_2 = ((__pyx_v_parser->http_major == 1) != 0); - if (__pyx_t_2) { - /* "aiohttp/_http_parser.pyx":239 - * - * 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: +/* 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)); - /* "aiohttp/_http_parser.pyx":240 - * if parser.http_major == 1: - * if parser.http_minor == 0: - * return HttpVersion10 # <<<<<<<<<<<<<< - * elif parser.http_minor == 1: - * return HttpVersion11 - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_HttpVersion10); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 240, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "aiohttp/_http_parser.pyx":239 - * - * if parser.http_major == 1: - * if parser.http_minor == 0: # <<<<<<<<<<<<<< - * return HttpVersion10 - * elif parser.http_minor == 1: - */ - break; +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; - /* "aiohttp/_http_parser.pyx":241 - * if parser.http_minor == 0: - * return HttpVersion10 - * elif parser.http_minor == 1: # <<<<<<<<<<<<<< - * return HttpVersion11 - * - */ - case 1: + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "aiohttp/_http_parser.pyx":242 - * return HttpVersion10 - * elif parser.http_minor == 1: - * return HttpVersion11 # <<<<<<<<<<<<<< - * - * return HttpVersion(parser.http_major, parser.http_minor) +/* "aiohttp/_http_parser.pyx":199 + * cdef readonly object headers # CIMultiDict + * cdef readonly object raw_headers # tuple + * cdef readonly object should_close # <<<<<<<<<<<<<< + * cdef readonly object compression + * cdef readonly object upgrade */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_HttpVersion11); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 242, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; - goto __pyx_L0; - /* "aiohttp/_http_parser.pyx":241 - * if parser.http_minor == 0: - * return HttpVersion10 - * elif parser.http_minor == 1: # <<<<<<<<<<<<<< - * return HttpVersion11 - * - */ - break; - default: break; - } +/* 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)); - /* "aiohttp/_http_parser.pyx":238 - * cdef cparser.http_parser* parser = self._cparser - * - * if parser.http_major == 1: # <<<<<<<<<<<<<< - * if parser.http_minor == 0: - * return HttpVersion10 + /* 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":200 + * cdef readonly object raw_headers # tuple + * cdef readonly object should_close + * cdef readonly object compression # <<<<<<<<<<<<<< + * cdef readonly object upgrade + * cdef readonly object chunked */ - } - /* "aiohttp/_http_parser.pyx":244 - * return HttpVersion11 - * - * return HttpVersion(parser.http_major, parser.http_minor) # <<<<<<<<<<<<<< +/* 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":201 + * cdef readonly object should_close + * cdef readonly object compression + * cdef readonly object upgrade # <<<<<<<<<<<<<< + * cdef readonly object chunked * - * def feed_eof(self): */ + +/* 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_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_HttpVersion); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 244, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = __Pyx_PyInt_From_unsigned_short(__pyx_v_parser->http_major); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 244, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = __Pyx_PyInt_From_unsigned_short(__pyx_v_parser->http_minor); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 244, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_7 = NULL; - __pyx_t_8 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_7)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_7); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - __pyx_t_8 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_4)) { - PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_t_5, __pyx_t_6}; - __pyx_t_3 = __Pyx_PyFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 244, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_4)) { - PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_t_5, __pyx_t_6}; - __pyx_t_3 = __Pyx_PyCFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 244, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __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, 244, __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_5); - PyTuple_SET_ITEM(__pyx_t_9, 0+__pyx_t_8, __pyx_t_5); - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_9, 1+__pyx_t_8, __pyx_t_6); - __pyx_t_5 = 0; - __pyx_t_6 = 0; - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_9, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 244, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_r = __pyx_t_3; - __pyx_t_3 = 0; + __Pyx_INCREF(__pyx_v_self->upgrade); + __pyx_r = __pyx_v_self->upgrade; goto __pyx_L0; - /* "aiohttp/_http_parser.pyx":235 - * ### Public API ### - * - * def http_version(self): # <<<<<<<<<<<<<< - * cdef cparser.http_parser* parser = self._cparser + /* function exit code */ + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "aiohttp/_http_parser.pyx":202 + * 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_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 = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "aiohttp/_http_parser.pyx":246 - * return HttpVersion(parser.http_major, parser.http_minor) - * - * def feed_eof(self): # <<<<<<<<<<<<<< - * cdef bytes desc - * +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict */ /* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_10HttpParser_7feed_eof(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_10HttpParser_7feed_eof(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { +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("feed_eof (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_10HttpParser_6feed_eof(((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)__pyx_v_self)); + __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_10HttpParser_6feed_eof(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self) { - PyObject *__pyx_v_desc = 0; +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 - 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_1 = NULL; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; PyObject *__pyx_t_6 = NULL; - PyObject *__pyx_t_7 = NULL; - __Pyx_RefNannySetupContext("feed_eof", 0); + __Pyx_RefNannySetupContext("__reduce_cython__", 0); - /* "aiohttp/_http_parser.pyx":249 - * cdef bytes desc - * - * if self._payload is not None: # <<<<<<<<<<<<<< - * if self._cparser.flags & cparser.F_CHUNKED: - * raise TransferEncodingError( + /* "(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_v_self->_payload != Py_None); - __pyx_t_2 = (__pyx_t_1 != 0); - if (__pyx_t_2) { + __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; - /* "aiohttp/_http_parser.pyx":250 - * - * if self._payload is not None: - * if self._cparser.flags & cparser.F_CHUNKED: # <<<<<<<<<<<<<< - * raise TransferEncodingError( - * "Not enough data for satisfy transfer length header.") + /* "(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_v_self->_cparser->flags & F_CHUNKED) != 0); - if (unlikely(__pyx_t_2)) { + __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; - /* "aiohttp/_http_parser.pyx":251 - * 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_CONTENTLENGTH: + /* "(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_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_TransferEncodingError); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 251, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 251, __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, 251, __pyx_L1_error) + __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; - /* "aiohttp/_http_parser.pyx":250 - * - * if self._payload is not None: - * if self._cparser.flags & cparser.F_CHUNKED: # <<<<<<<<<<<<<< - * raise TransferEncodingError( - * "Not enough data for satisfy transfer length header.") + /* "(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; - /* "aiohttp/_http_parser.pyx":253 - * raise TransferEncodingError( - * "Not enough data for satisfy transfer length header.") - * elif self._cparser.flags & cparser.F_CONTENTLENGTH: # <<<<<<<<<<<<<< - * raise ContentLengthError( - * "Not enough data for satisfy content length header.") + /* "(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_2 = ((__pyx_v_self->_cparser->flags & F_CONTENTLENGTH) != 0); - if (unlikely(__pyx_t_2)) { - - /* "aiohttp/_http_parser.pyx":254 - * "Not enough data for satisfy transfer length header.") - * elif self._cparser.flags & cparser.F_CONTENTLENGTH: - * raise ContentLengthError( # <<<<<<<<<<<<<< - * "Not enough data for satisfy content length header.") - * elif self._cparser.http_errno != cparser.HPE_OK: - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_ContentLengthError); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 254, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 254, __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, 254, __pyx_L1_error) + goto __pyx_L3; + } - /* "aiohttp/_http_parser.pyx":253 - * raise TransferEncodingError( - * "Not enough data for satisfy transfer length header.") - * elif self._cparser.flags & cparser.F_CONTENTLENGTH: # <<<<<<<<<<<<<< - * raise ContentLengthError( - * "Not enough data for satisfy content length header.") + /* "(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; } - - /* "aiohttp/_http_parser.pyx":256 - * raise ContentLengthError( - * "Not enough data for satisfy content length header.") - * elif self._cparser.http_errno != cparser.HPE_OK: # <<<<<<<<<<<<<< - * desc = cparser.http_errno_description( - * self._cparser.http_errno) - */ - __pyx_t_2 = ((__pyx_v_self->_cparser->http_errno != HPE_OK) != 0); - if (unlikely(__pyx_t_2)) { - - /* "aiohttp/_http_parser.pyx":257 - * "Not enough data for satisfy content length header.") - * elif self._cparser.http_errno != cparser.HPE_OK: - * desc = cparser.http_errno_description( # <<<<<<<<<<<<<< - * self._cparser.http_errno) - * raise PayloadEncodingError(desc.decode('latin-1')) - */ - __pyx_t_3 = __Pyx_PyBytes_FromString(http_errno_description(((enum http_errno)__pyx_v_self->_cparser->http_errno))); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 257, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_v_desc = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; - - /* "aiohttp/_http_parser.pyx":259 - * desc = cparser.http_errno_description( - * self._cparser.http_errno) - * raise PayloadEncodingError(desc.decode('latin-1')) # <<<<<<<<<<<<<< - * else: - * self._payload.feed_eof() - */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_PayloadEncodingError); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 259, __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, 259, __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); - } - } - if (!__pyx_t_6) { - __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_5); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 259, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_GOTREF(__pyx_t_3); - } else { - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_4)) { - PyObject *__pyx_temp[2] = {__pyx_t_6, __pyx_t_5}; - __pyx_t_3 = __Pyx_PyFunction_FastCall(__pyx_t_4, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 259, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_4)) { - PyObject *__pyx_temp[2] = {__pyx_t_6, __pyx_t_5}; - __pyx_t_3 = __Pyx_PyCFunction_FastCall(__pyx_t_4, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 259, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } else - #endif - { - __pyx_t_7 = PyTuple_New(1+1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 259, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_6); __pyx_t_6 = NULL; - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_7, 0+1, __pyx_t_5); - __pyx_t_5 = 0; - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_7, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 259, __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_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __PYX_ERR(0, 259, __pyx_L1_error) - - /* "aiohttp/_http_parser.pyx":256 - * raise ContentLengthError( - * "Not enough data for satisfy content length header.") - * elif self._cparser.http_errno != cparser.HPE_OK: # <<<<<<<<<<<<<< - * desc = cparser.http_errno_description( - * self._cparser.http_errno) - */ + __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; } - - /* "aiohttp/_http_parser.pyx":261 - * 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, 261, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_7 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_7)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_7); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - if (__pyx_t_7) { - __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_7); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 261, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } else { - __pyx_t_3 = __Pyx_PyObject_CallNoArg(__pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 261, __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; + __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; } - - /* "aiohttp/_http_parser.pyx":249 - * cdef bytes desc - * - * if self._payload is not None: # <<<<<<<<<<<<<< - * if self._cparser.flags & cparser.F_CHUNKED: - * raise TransferEncodingError( - */ - goto __pyx_L3; + __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:; - /* "aiohttp/_http_parser.pyx":262 - * 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":263 - * 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, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 263, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - - /* "aiohttp/_http_parser.pyx":264 - * elif self._started: - * self._on_headers_complete() - * if self._messages: # <<<<<<<<<<<<<< - * return self._messages[-1][0] - * + /* "(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_2 = (__pyx_v_self->_messages != Py_None)&&(PyList_GET_SIZE(__pyx_v_self->_messages) != 0); - if (__pyx_t_2) { + __pyx_t_4 = (__pyx_v_use_setstate != 0); + if (__pyx_t_4) { - /* "aiohttp/_http_parser.pyx":265 - * self._on_headers_complete() - * if self._messages: - * return self._messages[-1][0] # <<<<<<<<<<<<<< - * - * def feed_data(self, data): + /* "(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); - if (unlikely(__pyx_v_self->_messages == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - __PYX_ERR(0, 265, __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, 265, __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, 265, __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; + __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; - /* "aiohttp/_http_parser.pyx":264 - * elif self._started: - * self._on_headers_complete() - * if self._messages: # <<<<<<<<<<<<<< - * return self._messages[-1][0] - * + /* "(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: */ - } + } - /* "aiohttp/_http_parser.pyx":262 - * else: - * self._payload.feed_eof() - * elif self._started: # <<<<<<<<<<<<<< - * self._on_headers_complete() - * if self._messages: + /* "(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; } - __pyx_L3:; - /* "aiohttp/_http_parser.pyx":246 - * return HttpVersion(parser.http_major, parser.http_minor) - * - * def feed_eof(self): # <<<<<<<<<<<<<< - * cdef bytes desc - * + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef tuple state + * cdef object _dict */ /* 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_1); + __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_6); - __Pyx_XDECREF(__pyx_t_7); - __Pyx_AddTraceback("aiohttp._http_parser.HttpParser.feed_eof", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("aiohttp._http_parser.RawResponseMessage.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; - __Pyx_XDECREF(__pyx_v_desc); + __Pyx_XDECREF(__pyx_v_state); + __Pyx_XDECREF(__pyx_v__dict); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "aiohttp/_http_parser.pyx":267 - * return self._messages[-1][0] - * - * def feed_data(self, data): # <<<<<<<<<<<<<< - * cdef: - * size_t data_len +/* "(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_10HttpParser_9feed_data(PyObject *__pyx_v_self, PyObject *__pyx_v_data); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_10HttpParser_9feed_data(PyObject *__pyx_v_self, PyObject *__pyx_v_data) { +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("feed_data (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_10HttpParser_8feed_data(((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)__pyx_v_self), ((PyObject *)__pyx_v_data)); + __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_10HttpParser_8feed_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; - PyObject *__pyx_v_ex = NULL; - PyObject *__pyx_v_messages = NULL; +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 - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; - __Pyx_RefNannySetupContext("feed_data", 0); + PyObject *__pyx_t_1 = NULL; + __Pyx_RefNannySetupContext("__setstate_cython__", 0); - /* "aiohttp/_http_parser.pyx":272 - * size_t nb - * - * PyObject_GetBuffer(data, &self.py_buf, PyBUF_SIMPLE) # <<<<<<<<<<<<<< - * data_len = self.py_buf.len - * + /* "(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) # <<<<<<<<<<<<<< */ - __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, 272, __pyx_L1_error) + 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; - /* "aiohttp/_http_parser.pyx":273 - * - * PyObject_GetBuffer(data, &self.py_buf, PyBUF_SIMPLE) - * data_len = self.py_buf.len # <<<<<<<<<<<<<< - * - * nb = cparser.http_parser_execute( + /* "(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) */ - __pyx_v_data_len = ((size_t)__pyx_v_self->py_buf.len); - /* "aiohttp/_http_parser.pyx":275 - * data_len = self.py_buf.len - * - * nb = cparser.http_parser_execute( # <<<<<<<<<<<<<< - * self._cparser, - * self._csettings, - */ - __pyx_v_nb = http_parser_execute(__pyx_v_self->_cparser, __pyx_v_self->_csettings, ((char *)__pyx_v_self->py_buf.buf), __pyx_v_data_len); + /* 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":281 - * data_len) +/* "aiohttp/_http_parser.pyx":231 * - * PyBuffer_Release(&self.py_buf) # <<<<<<<<<<<<<< * - * # i am not sure about cparser.HPE_INVALID_METHOD, + * cdef _new_response_message(object version, # <<<<<<<<<<<<<< + * int code, + * str reason, */ - PyBuffer_Release((&__pyx_v_self->py_buf)); - /* "aiohttp/_http_parser.pyx":286 - * # seems get err for valid request - * # test_client_functional.py::test_post_data_with_bytesio_file - * if (self._cparser.http_errno != cparser.HPE_OK and # <<<<<<<<<<<<<< - * (self._cparser.http_errno != cparser.HPE_INVALID_METHOD or - * self._cparser.method == 0)): - */ - __pyx_t_3 = ((__pyx_v_self->_cparser->http_errno != HPE_OK) != 0); - if (__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L4_bool_binop_done; - } +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; + __Pyx_RefNannySetupContext("_new_response_message", 0); - /* "aiohttp/_http_parser.pyx":287 - * # test_client_functional.py::test_post_data_with_bytesio_file - * if (self._cparser.http_errno != cparser.HPE_OK and - * (self._cparser.http_errno != cparser.HPE_INVALID_METHOD or # <<<<<<<<<<<<<< - * self._cparser.method == 0)): - * if self._payload_error == 0: - */ - __pyx_t_3 = ((__pyx_v_self->_cparser->http_errno != HPE_INVALID_METHOD) != 0); - if (!__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L4_bool_binop_done; - } + /* "aiohttp/_http_parser.pyx":241 + * 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, 241, __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":288 - * if (self._cparser.http_errno != cparser.HPE_OK and - * (self._cparser.http_errno != cparser.HPE_INVALID_METHOD or - * self._cparser.method == 0)): # <<<<<<<<<<<<<< - * if self._payload_error == 0: - * if self._last_error is not None: + /* "aiohttp/_http_parser.pyx":242 + * 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":243 + * ret = RawResponseMessage.__new__(RawResponseMessage) + * ret.version = version + * ret.code = code # <<<<<<<<<<<<<< + * ret.reason = reason + * ret.headers = headers */ - __pyx_t_3 = ((__pyx_v_self->_cparser->method == 0) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L4_bool_binop_done:; + __pyx_v_ret->code = __pyx_v_code; - /* "aiohttp/_http_parser.pyx":286 - * # seems get err for valid request - * # test_client_functional.py::test_post_data_with_bytesio_file - * if (self._cparser.http_errno != cparser.HPE_OK and # <<<<<<<<<<<<<< - * (self._cparser.http_errno != cparser.HPE_INVALID_METHOD or - * self._cparser.method == 0)): - */ - if (__pyx_t_2) { + /* "aiohttp/_http_parser.pyx":244 + * 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":245 + * 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":289 - * (self._cparser.http_errno != cparser.HPE_INVALID_METHOD or - * self._cparser.method == 0)): - * if self._payload_error == 0: # <<<<<<<<<<<<<< - * if self._last_error is not None: - * ex = self._last_error + /* "aiohttp/_http_parser.pyx":246 + * 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":247 + * ret.headers = headers + * ret.raw_headers = raw_headers + * ret.should_close = should_close # <<<<<<<<<<<<<< + * ret.compression = compression + * ret.upgrade = upgrade */ - __pyx_t_2 = ((__pyx_v_self->_payload_error == 0) != 0); - if (__pyx_t_2) { + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_v_should_close); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 247, __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":290 - * self._cparser.method == 0)): - * if self._payload_error == 0: - * if self._last_error is not None: # <<<<<<<<<<<<<< - * ex = self._last_error - * self._last_error = None - */ - __pyx_t_2 = (__pyx_v_self->_last_error != Py_None); - __pyx_t_3 = (__pyx_t_2 != 0); - if (__pyx_t_3) { + /* "aiohttp/_http_parser.pyx":248 + * 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":291 - * if self._payload_error == 0: - * if self._last_error is not None: - * ex = self._last_error # <<<<<<<<<<<<<< - * self._last_error = None - * else: + /* "aiohttp/_http_parser.pyx":249 + * ret.should_close = should_close + * ret.compression = compression + * ret.upgrade = upgrade # <<<<<<<<<<<<<< + * ret.chunked = chunked + * return ret */ - __pyx_t_4 = __pyx_v_self->_last_error; - __Pyx_INCREF(__pyx_t_4); - __pyx_v_ex = __pyx_t_4; - __pyx_t_4 = 0; + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_v_upgrade); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 249, __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":292 - * if self._last_error is not None: - * ex = self._last_error - * self._last_error = None # <<<<<<<<<<<<<< - * else: - * ex = parser_error_from_errno( + /* "aiohttp/_http_parser.pyx":250 + * ret.compression = compression + * ret.upgrade = upgrade + * ret.chunked = chunked # <<<<<<<<<<<<<< + * return ret + * */ - __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; + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_v_chunked); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 250, __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":290 - * self._cparser.method == 0)): - * if self._payload_error == 0: - * if self._last_error is not None: # <<<<<<<<<<<<<< - * ex = self._last_error - * self._last_error = None + /* "aiohttp/_http_parser.pyx":251 + * ret.upgrade = upgrade + * ret.chunked = chunked + * return ret # <<<<<<<<<<<<<< + * + * */ - goto __pyx_L8; - } + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(((PyObject *)__pyx_v_ret)); + __pyx_r = ((PyObject *)__pyx_v_ret); + goto __pyx_L0; - /* "aiohttp/_http_parser.pyx":294 - * self._last_error = None - * else: - * ex = parser_error_from_errno( # <<<<<<<<<<<<<< - * self._cparser.http_errno) - * self._payload = None + /* "aiohttp/_http_parser.pyx":231 + * + * + * cdef _new_response_message(object version, # <<<<<<<<<<<<<< + * int code, + * str reason, */ - /*else*/ { - /* "aiohttp/_http_parser.pyx":295 - * else: - * ex = parser_error_from_errno( - * self._cparser.http_errno) # <<<<<<<<<<<<<< - * self._payload = None - * raise ex + /* 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":293 + * Py_buffer py_buf + * + * def __cinit__(self): # <<<<<<<<<<<<<< + * self._cparser = \ + * PyMem_Malloc(sizeof(cparser.http_parser)) */ - __pyx_t_4 = __pyx_f_7aiohttp_12_http_parser_parser_error_from_errno(((enum http_errno)__pyx_v_self->_cparser->http_errno)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 294, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_v_ex = __pyx_t_4; - __pyx_t_4 = 0; - } - __pyx_L8:; - /* "aiohttp/_http_parser.pyx":296 - * ex = parser_error_from_errno( - * self._cparser.http_errno) - * self._payload = None # <<<<<<<<<<<<<< - * raise ex +/* 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; + __Pyx_RefNannySetupContext("__cinit__", 0); + + /* "aiohttp/_http_parser.pyx":294 * + * def __cinit__(self): + * self._cparser = \ # <<<<<<<<<<<<<< + * PyMem_Malloc(sizeof(cparser.http_parser)) + * if self._cparser is NULL: */ - __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; + __pyx_v_self->_cparser = ((struct http_parser *)PyMem_Malloc((sizeof(struct http_parser)))); - /* "aiohttp/_http_parser.pyx":297 - * self._cparser.http_errno) - * self._payload = None - * raise ex # <<<<<<<<<<<<<< + /* "aiohttp/_http_parser.pyx":296 + * self._cparser = \ + * PyMem_Malloc(sizeof(cparser.http_parser)) + * if self._cparser is NULL: # <<<<<<<<<<<<<< + * raise MemoryError() * - * if self._messages: */ - __Pyx_Raise(__pyx_v_ex, 0, 0, 0); - __PYX_ERR(0, 297, __pyx_L1_error) + __pyx_t_1 = ((__pyx_v_self->_cparser == NULL) != 0); + if (unlikely(__pyx_t_1)) { - /* "aiohttp/_http_parser.pyx":289 - * (self._cparser.http_errno != cparser.HPE_INVALID_METHOD or - * self._cparser.method == 0)): - * if self._payload_error == 0: # <<<<<<<<<<<<<< - * if self._last_error is not None: - * ex = self._last_error + /* "aiohttp/_http_parser.pyx":297 + * PyMem_Malloc(sizeof(cparser.http_parser)) + * if self._cparser is NULL: + * raise MemoryError() # <<<<<<<<<<<<<< + * + * self._csettings = \ */ - } + PyErr_NoMemory(); __PYX_ERR(0, 297, __pyx_L1_error) - /* "aiohttp/_http_parser.pyx":286 - * # seems get err for valid request - * # test_client_functional.py::test_post_data_with_bytesio_file - * if (self._cparser.http_errno != cparser.HPE_OK and # <<<<<<<<<<<<<< - * (self._cparser.http_errno != cparser.HPE_INVALID_METHOD or - * self._cparser.method == 0)): + /* "aiohttp/_http_parser.pyx":296 + * self._cparser = \ + * PyMem_Malloc(sizeof(cparser.http_parser)) + * if self._cparser is NULL: # <<<<<<<<<<<<<< + * raise MemoryError() + * */ } /* "aiohttp/_http_parser.pyx":299 - * raise ex + * raise MemoryError() * - * if self._messages: # <<<<<<<<<<<<<< - * messages = self._messages - * self._messages = [] + * self._csettings = \ # <<<<<<<<<<<<<< + * PyMem_Malloc(sizeof(cparser.http_parser_settings)) + * if self._csettings is NULL: */ - __pyx_t_3 = (__pyx_v_self->_messages != Py_None)&&(PyList_GET_SIZE(__pyx_v_self->_messages) != 0); - if (__pyx_t_3) { + __pyx_v_self->_csettings = ((struct http_parser_settings *)PyMem_Malloc((sizeof(struct http_parser_settings)))); - /* "aiohttp/_http_parser.pyx":300 + /* "aiohttp/_http_parser.pyx":301 + * self._csettings = \ + * PyMem_Malloc(sizeof(cparser.http_parser_settings)) + * if self._csettings is NULL: # <<<<<<<<<<<<<< + * raise MemoryError() * - * 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":301 - * if self._messages: - * messages = self._messages - * self._messages = [] # <<<<<<<<<<<<<< - * else: - * messages = () - */ - __pyx_t_4 = PyList_New(0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 301, __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":299 - * raise ex - * - * if self._messages: # <<<<<<<<<<<<<< - * messages = self._messages - * self._messages = [] - */ - goto __pyx_L9; - } - - /* "aiohttp/_http_parser.pyx":303 - * self._messages = [] - * else: - * messages = () # <<<<<<<<<<<<<< - * - * if self._upgraded: - */ - /*else*/ { - __Pyx_INCREF(__pyx_empty_tuple); - __pyx_v_messages = __pyx_empty_tuple; - } - __pyx_L9:; - - /* "aiohttp/_http_parser.pyx":305 - * messages = () - * - * if self._upgraded: # <<<<<<<<<<<<<< - * return messages, True, data[nb:] - * else: - */ - __pyx_t_3 = (__pyx_v_self->_upgraded != 0); - if (__pyx_t_3) { - - /* "aiohttp/_http_parser.pyx":306 - * - * 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, 306, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 306, __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; + __pyx_t_1 = ((__pyx_v_self->_csettings == NULL) != 0); + if (unlikely(__pyx_t_1)) { - /* "aiohttp/_http_parser.pyx":305 - * messages = () + /* "aiohttp/_http_parser.pyx":302 + * PyMem_Malloc(sizeof(cparser.http_parser_settings)) + * if self._csettings is NULL: + * raise MemoryError() # <<<<<<<<<<<<<< * - * if self._upgraded: # <<<<<<<<<<<<<< - * return messages, True, data[nb:] - * else: + * def __dealloc__(self): */ - } + PyErr_NoMemory(); __PYX_ERR(0, 302, __pyx_L1_error) - /* "aiohttp/_http_parser.pyx":308 - * return messages, True, data[nb:] - * else: - * return messages, False, b'' # <<<<<<<<<<<<<< - * + /* "aiohttp/_http_parser.pyx":301 + * self._csettings = \ + * PyMem_Malloc(sizeof(cparser.http_parser_settings)) + * if self._csettings is NULL: # <<<<<<<<<<<<<< + * raise MemoryError() * */ - /*else*/ { - __Pyx_XDECREF(__pyx_r); - __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 308, __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__6); - __Pyx_GIVEREF(__pyx_kp_b__6); - PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_kp_b__6); - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; - goto __pyx_L0; } - /* "aiohttp/_http_parser.pyx":267 - * return self._messages[-1][0] + /* "aiohttp/_http_parser.pyx":293 + * Py_buffer py_buf * - * def feed_data(self, data): # <<<<<<<<<<<<<< - * cdef: - * size_t data_len + * def __cinit__(self): # <<<<<<<<<<<<<< + * self._cparser = \ + * PyMem_Malloc(sizeof(cparser.http_parser)) */ /* function exit code */ + __pyx_r = 0; + goto __pyx_L0; __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_AddTraceback("aiohttp._http_parser.HttpParser.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = -1; __pyx_L0:; - __Pyx_XDECREF(__pyx_v_ex); - __Pyx_XDECREF(__pyx_v_messages); - __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): +/* "aiohttp/_http_parser.pyx":304 + * raise MemoryError() + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * PyMem_Free(self._cparser) + * PyMem_Free(self._csettings) */ /* 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; +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("__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)); + __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(); - 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; +static void __pyx_pf_7aiohttp_12_http_parser_10HttpParser_2__dealloc__(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self) { __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - __Pyx_RefNannySetupContext("__reduce_cython__", 0); + __Pyx_RefNannySetupContext("__dealloc__", 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__") + /* "aiohttp/_http_parser.pyx":305 + * + * def __dealloc__(self): + * PyMem_Free(self._cparser) # <<<<<<<<<<<<<< + * PyMem_Free(self._csettings) + * */ - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__7, 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) + PyMem_Free(__pyx_v_self->_cparser); - /* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): + /* "aiohttp/_http_parser.pyx":306 + * def __dealloc__(self): + * PyMem_Free(self._cparser) + * PyMem_Free(self._csettings) # <<<<<<<<<<<<<< + * + * cdef _init(self, cparser.http_parser_type mode, */ + PyMem_Free(__pyx_v_self->_csettings); - /* 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__") + /* "aiohttp/_http_parser.pyx":304 + * raise MemoryError() + * + * def __dealloc__(self): # <<<<<<<<<<<<<< + * PyMem_Free(self._cparser) + * PyMem_Free(self._csettings) */ -/* 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; - __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__8, 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__") +/* "aiohttp/_http_parser.pyx":308 + * PyMem_Free(self._csettings) + * + * cdef _init(self, cparser.http_parser_type mode, # <<<<<<<<<<<<<< + * object protocol, object loop, object timer=None, + * size_t max_line_size=8190, size_t max_headers=32768, */ - /* 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; -} +static PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser__init(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self, enum http_parser_type __pyx_v_mode, PyObject *__pyx_v_protocol, PyObject *__pyx_v_loop, struct __pyx_opt_args_7aiohttp_12_http_parser_10HttpParser__init *__pyx_optional_args) { -/* "aiohttp/_http_parser.pyx":313 - * cdef class HttpRequestParserC(HttpParser): + /* "aiohttp/_http_parser.pyx":309 * - * def __init__(self, protocol, loop, timer=None, # <<<<<<<<<<<<<< - * size_t max_line_size=8190, size_t max_headers=32768, - * size_t max_field_size=8190, payload_exception=None, + * cdef _init(self, cparser.http_parser_type mode, + * object protocol, object loop, 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); -/* Python wrapper */ -static int __pyx_pw_7aiohttp_12_http_parser_18HttpRequestParserC_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pw_7aiohttp_12_http_parser_18HttpRequestParserC_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_protocol = 0; - PyObject *__pyx_v_loop = 0; - 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; - PyObject *__pyx_v_response_with_body = 0; - CYTHON_UNUSED PyObject *__pyx_v_read_until_eof = 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_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,0}; - PyObject* values[9] = {0,0,0,0,0,0,0,0,0}; - values[2] = ((PyObject *)Py_None); - - /* "aiohttp/_http_parser.pyx":315 - * def __init__(self, protocol, loop, timer=None, - * size_t max_line_size=8190, size_t max_headers=32768, - * size_t max_field_size=8190, payload_exception=None, # <<<<<<<<<<<<<< - * response_with_body=True, read_until_eof=False): - * self._init(cparser.HTTP_REQUEST, protocol, loop, timer, + /* "aiohttp/_http_parser.pyx":311 + * object protocol, object loop, 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 auto_decompress=True): + * cparser.http_parser_init(self._cparser, mode) */ - values[6] = ((PyObject *)Py_None); + PyObject *__pyx_v_payload_exception = ((PyObject *)Py_None); - /* "aiohttp/_http_parser.pyx":316 - * size_t max_line_size=8190, size_t max_headers=32768, - * size_t max_field_size=8190, payload_exception=None, - * response_with_body=True, read_until_eof=False): # <<<<<<<<<<<<<< - * self._init(cparser.HTTP_REQUEST, protocol, loop, timer, - * max_line_size, max_headers, max_field_size, + /* "aiohttp/_http_parser.pyx":312 + * 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 auto_decompress=True): # <<<<<<<<<<<<<< + * cparser.http_parser_init(self._cparser, mode) + * self._cparser.data = self */ - values[7] = ((PyObject *)Py_True); - values[8] = ((PyObject *)Py_False); - 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_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, 2, 9, 1); __PYX_ERR(0, 313, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_timer); - if (value) { values[2] = value; kw_args--; } - } - CYTHON_FALLTHROUGH; - case 3: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_max_line_size); - 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_headers); - 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_field_size); - 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_payload_exception); - 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_response_with_body); - 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_read_until_eof); - if (value) { values[8] = value; kw_args--; } + int __pyx_v_response_with_body = ((int)1); + int __pyx_v_auto_decompress = ((int)1); + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + __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_auto_decompress = __pyx_optional_args->auto_decompress; + } + } + } + } } } - if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) __PYX_ERR(0, 313, __pyx_L3_error) - } - } else { - switch (PyTuple_GET_SIZE(__pyx_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); - 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_timer = values[2]; - if (values[3]) { - __pyx_v_max_line_size = __Pyx_PyInt_As_size_t(values[3]); if (unlikely((__pyx_v_max_line_size == (size_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 314, __pyx_L3_error) - } else { - __pyx_v_max_line_size = ((size_t)0x1FFE); - } - if (values[4]) { - __pyx_v_max_headers = __Pyx_PyInt_As_size_t(values[4]); if (unlikely((__pyx_v_max_headers == (size_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 314, __pyx_L3_error) - } else { - __pyx_v_max_headers = ((size_t)0x8000); - } - if (values[5]) { - __pyx_v_max_field_size = __Pyx_PyInt_As_size_t(values[5]); if (unlikely((__pyx_v_max_field_size == (size_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 315, __pyx_L3_error) - } else { - __pyx_v_max_field_size = ((size_t)0x1FFE); } - __pyx_v_payload_exception = values[6]; - __pyx_v_response_with_body = values[7]; - __pyx_v_read_until_eof = values[8]; } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__init__", 0, 2, 9, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 313, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._http_parser.HttpRequestParserC.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_18HttpRequestParserC___init__(((struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParserC *)__pyx_v_self), __pyx_v_protocol, __pyx_v_loop, __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); /* "aiohttp/_http_parser.pyx":313 - * cdef class HttpRequestParserC(HttpParser): - * - * def __init__(self, protocol, loop, timer=None, # <<<<<<<<<<<<<< - * size_t max_line_size=8190, size_t max_headers=32768, - * size_t max_field_size=8190, payload_exception=None, + * size_t max_field_size=8190, payload_exception=None, + * bint response_with_body=True, bint auto_decompress=True): + * cparser.http_parser_init(self._cparser, mode) # <<<<<<<<<<<<<< + * self._cparser.data = self + * self._cparser.content_length = 0 */ + http_parser_init(__pyx_v_self->_cparser, __pyx_v_mode); - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "aiohttp/_http_parser.pyx":314 + * bint response_with_body=True, bint auto_decompress=True): + * cparser.http_parser_init(self._cparser, mode) + * self._cparser.data = self # <<<<<<<<<<<<<< + * self._cparser.content_length = 0 + * + */ + __pyx_v_self->_cparser->data = ((void *)__pyx_v_self); -static int __pyx_pf_7aiohttp_12_http_parser_18HttpRequestParserC___init__(struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParserC *__pyx_v_self, PyObject *__pyx_v_protocol, PyObject *__pyx_v_loop, 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, PyObject *__pyx_v_response_with_body, CYTHON_UNUSED PyObject *__pyx_v_read_until_eof) { - int __pyx_r; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - struct __pyx_opt_args_7aiohttp_12_http_parser_10HttpParser__init __pyx_t_2; - __Pyx_RefNannySetupContext("__init__", 0); + /* "aiohttp/_http_parser.pyx":315 + * cparser.http_parser_init(self._cparser, mode) + * self._cparser.data = self + * self._cparser.content_length = 0 # <<<<<<<<<<<<<< + * + * cparser.http_parser_settings_init(self._csettings) + */ + __pyx_v_self->_cparser->content_length = 0; /* "aiohttp/_http_parser.pyx":317 - * size_t max_field_size=8190, payload_exception=None, - * response_with_body=True, read_until_eof=False): - * self._init(cparser.HTTP_REQUEST, protocol, loop, timer, # <<<<<<<<<<<<<< - * max_line_size, max_headers, max_field_size, - * payload_exception, response_with_body) + * self._cparser.content_length = 0 + * + * cparser.http_parser_settings_init(self._csettings) # <<<<<<<<<<<<<< + * + * self._protocol = protocol */ - __pyx_t_2.__pyx_n = 6; - __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_1 = ((struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpRequestParserC *)__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_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 317, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + http_parser_settings_init(__pyx_v_self->_csettings); - /* "aiohttp/_http_parser.pyx":313 - * cdef class HttpRequestParserC(HttpParser): + /* "aiohttp/_http_parser.pyx":319 + * cparser.http_parser_settings_init(self._csettings) * - * def __init__(self, protocol, loop, timer=None, # <<<<<<<<<<<<<< - * size_t max_line_size=8190, size_t max_headers=32768, - * size_t max_field_size=8190, payload_exception=None, + * 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; - /* function exit code */ - __pyx_r = 0; - goto __pyx_L0; - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._http_parser.HttpRequestParserC.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; - __pyx_L0:; - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":321 - * payload_exception, response_with_body) + /* "aiohttp/_http_parser.pyx":320 + * + * self._protocol = protocol + * self._loop = loop # <<<<<<<<<<<<<< + * self._timer = timer * - * cdef object _on_status_complete(self): # <<<<<<<<<<<<<< - * cdef Py_buffer py_buf - * if not self._buf: */ + __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; -static PyObject *__pyx_f_7aiohttp_12_http_parser_18HttpRequestParserC__on_status_complete(struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParserC *__pyx_v_self) { - Py_buffer __pyx_v_py_buf; - 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_t_7; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - int __pyx_t_10; - char const *__pyx_t_11; - 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; - __Pyx_RefNannySetupContext("_on_status_complete", 0); - - /* "aiohttp/_http_parser.pyx":323 - * cdef object _on_status_complete(self): - * cdef Py_buffer py_buf - * if not self._buf: # <<<<<<<<<<<<<< - * return - * self._path = self._buf.decode('utf-8', 'surrogateescape') + /* "aiohttp/_http_parser.pyx":321 + * self._protocol = protocol + * self._loop = loop + * self._timer = timer # <<<<<<<<<<<<<< + * + * self._buf = bytearray() */ - __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) { + __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":324 - * cdef Py_buffer py_buf - * if not self._buf: - * return # <<<<<<<<<<<<<< - * self._path = self._buf.decode('utf-8', 'surrogateescape') - * if self._cparser.method == 5: # CONNECT + /* "aiohttp/_http_parser.pyx":323 + * self._timer = timer + * + * self._buf = bytearray() # <<<<<<<<<<<<<< + * self._payload = None + * self._payload_error = 0 */ - __Pyx_XDECREF(__pyx_r); - __pyx_r = Py_None; __Pyx_INCREF(Py_None); - goto __pyx_L0; + __pyx_t_1 = __Pyx_PyObject_CallNoArg(((PyObject *)(&PyByteArray_Type))); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 323, __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":323 - * cdef object _on_status_complete(self): - * cdef Py_buffer py_buf - * if not self._buf: # <<<<<<<<<<<<<< - * return - * self._path = self._buf.decode('utf-8', 'surrogateescape') + /* "aiohttp/_http_parser.pyx":324 + * + * 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":325 - * if not self._buf: - * return - * self._path = self._buf.decode('utf-8', 'surrogateescape') # <<<<<<<<<<<<<< - * if self._cparser.method == 5: # CONNECT - * self._url = URL(self._path) + * self._buf = bytearray() + * self._payload = None + * self._payload_error = 0 # <<<<<<<<<<<<<< + * self._payload_exception = payload_exception + * self._messages = [] */ - if (unlikely(__pyx_v_self->__pyx_base._buf == Py_None)) { - PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "decode"); - __PYX_ERR(0, 325, __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, 325, __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; + __pyx_v_self->_payload_error = 0; /* "aiohttp/_http_parser.pyx":326 - * return - * self._path = self._buf.decode('utf-8', 'surrogateescape') - * if self._cparser.method == 5: # CONNECT # <<<<<<<<<<<<<< - * self._url = URL(self._path) - * else: - */ - __pyx_t_2 = ((__pyx_v_self->__pyx_base._cparser->method == 5) != 0); - if (__pyx_t_2) { - - /* "aiohttp/_http_parser.pyx":327 - * self._path = self._buf.decode('utf-8', 'surrogateescape') - * if self._cparser.method == 5: # CONNECT - * self._url = URL(self._path) # <<<<<<<<<<<<<< - * else: - * PyObject_GetBuffer(self._buf, &py_buf, PyBUF_SIMPLE) + * self._payload = None + * self._payload_error = 0 + * self._payload_exception = payload_exception # <<<<<<<<<<<<<< + * self._messages = [] + * */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_URL); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 327, __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); - } - } - if (!__pyx_t_5) { - __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_v_self->__pyx_base._path); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 327, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - } else { - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_4)) { - PyObject *__pyx_temp[2] = {__pyx_t_5, __pyx_v_self->__pyx_base._path}; - __pyx_t_3 = __Pyx_PyFunction_FastCall(__pyx_t_4, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 327, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_GOTREF(__pyx_t_3); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_4)) { - PyObject *__pyx_temp[2] = {__pyx_t_5, __pyx_v_self->__pyx_base._path}; - __pyx_t_3 = __Pyx_PyCFunction_FastCall(__pyx_t_4, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 327, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_GOTREF(__pyx_t_3); - } else - #endif - { - __pyx_t_6 = PyTuple_New(1+1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 327, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); __pyx_t_5 = NULL; - __Pyx_INCREF(__pyx_v_self->__pyx_base._path); - __Pyx_GIVEREF(__pyx_v_self->__pyx_base._path); - PyTuple_SET_ITEM(__pyx_t_6, 0+1, __pyx_v_self->__pyx_base._path); - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_6, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 327, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } - } - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_GIVEREF(__pyx_t_3); - __Pyx_GOTREF(__pyx_v_self->__pyx_base._url); - __Pyx_DECREF(__pyx_v_self->__pyx_base._url); - __pyx_v_self->__pyx_base._url = __pyx_t_3; - __pyx_t_3 = 0; + __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":326 - * return - * self._path = self._buf.decode('utf-8', 'surrogateescape') - * if self._cparser.method == 5: # CONNECT # <<<<<<<<<<<<<< - * self._url = URL(self._path) - * else: + /* "aiohttp/_http_parser.pyx":327 + * self._payload_error = 0 + * self._payload_exception = payload_exception + * self._messages = [] # <<<<<<<<<<<<<< + * + * self._raw_name = bytearray() */ - goto __pyx_L4; - } + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 327, __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":329 - * self._url = URL(self._path) - * else: - * PyObject_GetBuffer(self._buf, &py_buf, PyBUF_SIMPLE) # <<<<<<<<<<<<<< - * try: - * self._url = _parse_url(py_buf.buf, + * self._messages = [] + * + * self._raw_name = bytearray() # <<<<<<<<<<<<<< + * self._raw_value = bytearray() + * self._has_value = False */ - /*else*/ { - __pyx_t_3 = __pyx_v_self->__pyx_base._buf; - __Pyx_INCREF(__pyx_t_3); - __pyx_t_7 = PyObject_GetBuffer(__pyx_t_3, (&__pyx_v_py_buf), PyBUF_SIMPLE); if (unlikely(__pyx_t_7 == ((int)-1))) __PYX_ERR(0, 329, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_1 = __Pyx_PyObject_CallNoArg(((PyObject *)(&PyByteArray_Type))); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 329, __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":330 - * else: - * PyObject_GetBuffer(self._buf, &py_buf, PyBUF_SIMPLE) - * try: # <<<<<<<<<<<<<< - * self._url = _parse_url(py_buf.buf, - * py_buf.len) + /* "aiohttp/_http_parser.pyx":330 + * + * self._raw_name = bytearray() + * self._raw_value = bytearray() # <<<<<<<<<<<<<< + * self._has_value = False + * */ - /*try:*/ { + __pyx_t_1 = __Pyx_PyObject_CallNoArg(((PyObject *)(&PyByteArray_Type))); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 330, __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":331 - * PyObject_GetBuffer(self._buf, &py_buf, PyBUF_SIMPLE) - * try: - * self._url = _parse_url(py_buf.buf, # <<<<<<<<<<<<<< - * py_buf.len) - * finally: + /* "aiohttp/_http_parser.pyx":331 + * self._raw_name = bytearray() + * self._raw_value = bytearray() + * self._has_value = False # <<<<<<<<<<<<<< + * + * self._max_line_size = max_line_size */ - __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_parse_url); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 331, __pyx_L6_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_6 = __Pyx_PyBytes_FromString(((char *)__pyx_v_py_buf.buf)); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 331, __pyx_L6_error) - __Pyx_GOTREF(__pyx_t_6); + __pyx_v_self->_has_value = 0; - /* "aiohttp/_http_parser.pyx":332 - * try: - * self._url = _parse_url(py_buf.buf, - * py_buf.len) # <<<<<<<<<<<<<< - * finally: - * PyBuffer_Release(&py_buf) + /* "aiohttp/_http_parser.pyx":333 + * self._has_value = False + * + * self._max_line_size = max_line_size # <<<<<<<<<<<<<< + * self._max_headers = max_headers + * self._max_field_size = max_field_size */ - __pyx_t_5 = PyInt_FromSsize_t(__pyx_v_py_buf.len); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 332, __pyx_L6_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_8 = NULL; - __pyx_t_7 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_8)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_8); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - __pyx_t_7 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_4)) { - PyObject *__pyx_temp[3] = {__pyx_t_8, __pyx_t_6, __pyx_t_5}; - __pyx_t_3 = __Pyx_PyFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 331, __pyx_L6_error) - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_4)) { - PyObject *__pyx_temp[3] = {__pyx_t_8, __pyx_t_6, __pyx_t_5}; - __pyx_t_3 = __Pyx_PyCFunction_FastCall(__pyx_t_4, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 331, __pyx_L6_error) - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } else - #endif - { - __pyx_t_9 = PyTuple_New(2+__pyx_t_7); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 331, __pyx_L6_error) - __Pyx_GOTREF(__pyx_t_9); - if (__pyx_t_8) { - __Pyx_GIVEREF(__pyx_t_8); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_8); __pyx_t_8 = NULL; - } - __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_9, 0+__pyx_t_7, __pyx_t_6); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_9, 1+__pyx_t_7, __pyx_t_5); - __pyx_t_6 = 0; - __pyx_t_5 = 0; - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_9, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 331, __pyx_L6_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_v_self->_max_line_size = __pyx_v_max_line_size; - /* "aiohttp/_http_parser.pyx":331 - * PyObject_GetBuffer(self._buf, &py_buf, PyBUF_SIMPLE) - * try: - * self._url = _parse_url(py_buf.buf, # <<<<<<<<<<<<<< - * py_buf.len) - * finally: + /* "aiohttp/_http_parser.pyx":334 + * + * 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_GIVEREF(__pyx_t_3); - __Pyx_GOTREF(__pyx_v_self->__pyx_base._url); - __Pyx_DECREF(__pyx_v_self->__pyx_base._url); - __pyx_v_self->__pyx_base._url = __pyx_t_3; - __pyx_t_3 = 0; - } + __pyx_v_self->_max_headers = __pyx_v_max_headers; - /* "aiohttp/_http_parser.pyx":334 - * py_buf.len) - * finally: - * PyBuffer_Release(&py_buf) # <<<<<<<<<<<<<< - * self._buf.clear() + /* "aiohttp/_http_parser.pyx":335 + * 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._upgraded = False + */ + __pyx_v_self->_max_field_size = __pyx_v_max_field_size; + + /* "aiohttp/_http_parser.pyx":336 + * self._max_headers = max_headers + * self._max_field_size = max_field_size + * self._response_with_body = response_with_body # <<<<<<<<<<<<<< + * self._upgraded = False + * self._auto_decompress = auto_decompress + */ + __pyx_v_self->_response_with_body = __pyx_v_response_with_body; + + /* "aiohttp/_http_parser.pyx":337 + * self._max_field_size = max_field_size + * self._response_with_body = response_with_body + * self._upgraded = False # <<<<<<<<<<<<<< + * self._auto_decompress = auto_decompress + * self._content_encoding = None + */ + __pyx_v_self->_upgraded = 0; + + /* "aiohttp/_http_parser.pyx":338 + * self._response_with_body = response_with_body + * self._upgraded = False + * self._auto_decompress = auto_decompress # <<<<<<<<<<<<<< + * self._content_encoding = None * */ - /*finally:*/ { - /*normal exit:*/{ - PyBuffer_Release((&__pyx_v_py_buf)); - goto __pyx_L7; - } - __pyx_L6_error:; - /*exception exit:*/{ - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __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_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_15, &__pyx_t_16, &__pyx_t_17); - if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_12, &__pyx_t_13, &__pyx_t_14) < 0)) __Pyx_ErrFetch(&__pyx_t_12, &__pyx_t_13, &__pyx_t_14); - __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_XGOTREF(__pyx_t_17); - __pyx_t_7 = __pyx_lineno; __pyx_t_10 = __pyx_clineno; __pyx_t_11 = __pyx_filename; - { - PyBuffer_Release((&__pyx_v_py_buf)); - } - if (PY_MAJOR_VERSION >= 3) { - __Pyx_XGIVEREF(__pyx_t_15); - __Pyx_XGIVEREF(__pyx_t_16); - __Pyx_XGIVEREF(__pyx_t_17); - __Pyx_ExceptionReset(__pyx_t_15, __pyx_t_16, __pyx_t_17); - } - __Pyx_XGIVEREF(__pyx_t_12); - __Pyx_XGIVEREF(__pyx_t_13); - __Pyx_XGIVEREF(__pyx_t_14); - __Pyx_ErrRestore(__pyx_t_12, __pyx_t_13, __pyx_t_14); - __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_lineno = __pyx_t_7; __pyx_clineno = __pyx_t_10; __pyx_filename = __pyx_t_11; - goto __pyx_L1_error; - } - __pyx_L7:; - } - } - __pyx_L4:; + __pyx_v_self->_auto_decompress = __pyx_v_auto_decompress; - /* "aiohttp/_http_parser.pyx":335 - * finally: - * PyBuffer_Release(&py_buf) - * self._buf.clear() # <<<<<<<<<<<<<< + /* "aiohttp/_http_parser.pyx":339 + * 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":341 + * 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_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_self->__pyx_base._buf, __pyx_n_s_clear); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 335, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_9 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_9 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_9)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_9); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - if (__pyx_t_9) { - __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_9); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 335, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - } else { - __pyx_t_3 = __Pyx_PyObject_CallNoArg(__pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 335, __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; + __pyx_v_self->_csettings->on_url = __pyx_f_7aiohttp_12_http_parser_cb_on_url; - /* "aiohttp/_http_parser.pyx":321 - * payload_exception, response_with_body) + /* "aiohttp/_http_parser.pyx":342 * - * cdef object _on_status_complete(self): # <<<<<<<<<<<<<< - * cdef Py_buffer py_buf - * if not self._buf: + * 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; - /* 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_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_9); - __Pyx_AddTraceback("aiohttp._http_parser.HttpRequestParserC._on_status_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":343 + * 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; -/* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): + /* "aiohttp/_http_parser.pyx":344 + * 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; -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18HttpRequestParserC_3__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18HttpRequestParserC_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_18HttpRequestParserC_2__reduce_cython__(((struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParserC *)__pyx_v_self)); + /* "aiohttp/_http_parser.pyx":345 + * 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; - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "aiohttp/_http_parser.pyx":346 + * 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; -static PyObject *__pyx_pf_7aiohttp_12_http_parser_18HttpRequestParserC_2__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParserC *__pyx_v_self) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - __Pyx_RefNannySetupContext("__reduce_cython__", 0); + /* "aiohttp/_http_parser.pyx":347 + * 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; - /* "(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__") + /* "aiohttp/_http_parser.pyx":348 + * 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_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) + __pyx_v_self->_csettings->on_message_complete = __pyx_f_7aiohttp_12_http_parser_cb_on_message_complete; - /* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): + /* "aiohttp/_http_parser.pyx":349 + * 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":350 + * 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":352 + * self._csettings.on_chunk_complete = cb_on_chunk_complete + * + * self._last_error = None # <<<<<<<<<<<<<< + * + * cdef _process_header(self): + */ + __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":308 + * PyMem_Free(self._csettings) + * + * cdef _init(self, cparser.http_parser_type mode, # <<<<<<<<<<<<<< + * object protocol, object loop, object timer=None, + * size_t max_line_size=8190, size_t max_headers=32768, */ /* 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.HttpRequestParserC.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + __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; } -/* "(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__") +/* "aiohttp/_http_parser.pyx":354 + * self._last_error = None + * + * cdef _process_header(self): # <<<<<<<<<<<<<< + * if self._raw_name: + * raw_name = bytes(self._raw_name) */ -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18HttpRequestParserC_5__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_18HttpRequestParserC_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_18HttpRequestParserC_4__setstate_cython__(((struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParserC *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_18HttpRequestParserC_4__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParserC *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { +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 - PyObject *__pyx_t_1 = NULL; - __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) + 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; + __Pyx_RefNannySetupContext("_process_header", 0); - /* "(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__") + /* "aiohttp/_http_parser.pyx":355 + * + * 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) { - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._http_parser.HttpRequestParserC.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; - __Pyx_XGIVEREF(__pyx_r); - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -/* "aiohttp/_http_parser.pyx":340 - * cdef class HttpResponseParserC(HttpParser): + /* "aiohttp/_http_parser.pyx":356 + * cdef _process_header(self): + * if self._raw_name: + * raw_name = bytes(self._raw_name) # <<<<<<<<<<<<<< + * raw_value = bytes(self._raw_value) * - * def __init__(self, protocol, loop, timer=None, # <<<<<<<<<<<<<< - * size_t max_line_size=8190, size_t max_headers=32768, - * size_t max_field_size=8190, payload_exception=None, */ + __pyx_t_2 = __Pyx_PyObject_CallOneArg(((PyObject *)(&PyBytes_Type)), __pyx_v_self->_raw_name); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 356, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_raw_name = ((PyObject*)__pyx_t_2); + __pyx_t_2 = 0; -/* Python wrapper */ -static int __pyx_pw_7aiohttp_12_http_parser_19HttpResponseParserC_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static int __pyx_pw_7aiohttp_12_http_parser_19HttpResponseParserC_1__init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - PyObject *__pyx_v_protocol = 0; - PyObject *__pyx_v_loop = 0; - 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; - PyObject *__pyx_v_response_with_body = 0; - CYTHON_UNUSED PyObject *__pyx_v_read_until_eof = 0; - PyObject *__pyx_v_auto_decompress = 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_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[10] = {0,0,0,0,0,0,0,0,0,0}; - values[2] = ((PyObject *)Py_None); + /* "aiohttp/_http_parser.pyx":357 + * 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, 357, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_raw_value = ((PyObject*)__pyx_t_2); + __pyx_t_2 = 0; - /* "aiohttp/_http_parser.pyx":342 - * def __init__(self, protocol, loop, timer=None, - * size_t max_line_size=8190, size_t max_headers=32768, - * size_t max_field_size=8190, payload_exception=None, # <<<<<<<<<<<<<< - * response_with_body=True, read_until_eof=False, - * auto_decompress=True): + /* "aiohttp/_http_parser.pyx":359 + * raw_value = bytes(self._raw_value) + * + * name = find_header(raw_name) # <<<<<<<<<<<<<< + * value = raw_value.decode('utf-8', 'surrogateescape') + * */ - values[6] = ((PyObject *)Py_None); + __pyx_t_2 = __pyx_f_7aiohttp_12_http_parser_find_header(__pyx_v_raw_name); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 359, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_name = __pyx_t_2; + __pyx_t_2 = 0; - /* "aiohttp/_http_parser.pyx":343 - * size_t max_line_size=8190, size_t max_headers=32768, - * size_t max_field_size=8190, payload_exception=None, - * response_with_body=True, read_until_eof=False, # <<<<<<<<<<<<<< - * auto_decompress=True): - * self._init(cparser.HTTP_RESPONSE, protocol, loop, timer, + /* "aiohttp/_http_parser.pyx":360 + * + * name = find_header(raw_name) + * value = raw_value.decode('utf-8', 'surrogateescape') # <<<<<<<<<<<<<< + * + * self._headers.add(name, value) */ - values[7] = ((PyObject *)Py_True); - values[8] = ((PyObject *)Py_False); + __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, 360, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_v_value = __pyx_t_2; + __pyx_t_2 = 0; - /* "aiohttp/_http_parser.pyx":344 - * size_t max_field_size=8190, payload_exception=None, - * response_with_body=True, read_until_eof=False, - * auto_decompress=True): # <<<<<<<<<<<<<< - * self._init(cparser.HTTP_RESPONSE, protocol, loop, timer, - * max_line_size, max_headers, max_field_size, + /* "aiohttp/_http_parser.pyx":362 + * value = raw_value.decode('utf-8', 'surrogateescape') + * + * self._headers.add(name, value) # <<<<<<<<<<<<<< + * + * if name is CONTENT_ENCODING: */ - values[9] = ((PyObject *)Py_True); - 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_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, 2, 10, 1); __PYX_ERR(0, 340, __pyx_L3_error) - } - CYTHON_FALLTHROUGH; - case 2: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_timer); - if (value) { values[2] = value; kw_args--; } - } - CYTHON_FALLTHROUGH; - case 3: - if (kw_args > 0) { - PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_max_line_size); - 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_headers); - 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_field_size); - 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_payload_exception); - 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_response_with_body); - 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_read_until_eof); - 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_auto_decompress); - if (value) { values[9] = 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, 340, __pyx_L3_error) - } - } else { - switch (PyTuple_GET_SIZE(__pyx_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); - values[0] = PyTuple_GET_ITEM(__pyx_args, 0); - break; - default: goto __pyx_L5_argtuple_error; + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_self->_headers, __pyx_n_s_add); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 362, __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; } } - __pyx_v_protocol = values[0]; - __pyx_v_loop = values[1]; - __pyx_v_timer = values[2]; - if (values[3]) { - __pyx_v_max_line_size = __Pyx_PyInt_As_size_t(values[3]); if (unlikely((__pyx_v_max_line_size == (size_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 341, __pyx_L3_error) - } else { - __pyx_v_max_line_size = ((size_t)0x1FFE); - } - if (values[4]) { - __pyx_v_max_headers = __Pyx_PyInt_As_size_t(values[4]); if (unlikely((__pyx_v_max_headers == (size_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 341, __pyx_L3_error) - } else { - __pyx_v_max_headers = ((size_t)0x8000); - } - if (values[5]) { - __pyx_v_max_field_size = __Pyx_PyInt_As_size_t(values[5]); if (unlikely((__pyx_v_max_field_size == (size_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 342, __pyx_L3_error) - } else { - __pyx_v_max_field_size = ((size_t)0x1FFE); + #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, 362, __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, 362, __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, 362, __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, 362, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; } - __pyx_v_payload_exception = values[6]; - __pyx_v_response_with_body = values[7]; - __pyx_v_read_until_eof = values[8]; - __pyx_v_auto_decompress = values[9]; - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__init__", 0, 2, 10, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 340, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._http_parser.HttpResponseParserC.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return -1; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_19HttpResponseParserC___init__(((struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParserC *)__pyx_v_self), __pyx_v_protocol, __pyx_v_loop, __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); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "aiohttp/_http_parser.pyx":340 - * cdef class HttpResponseParserC(HttpParser): + /* "aiohttp/_http_parser.pyx":364 + * self._headers.add(name, value) + * + * if name is CONTENT_ENCODING: # <<<<<<<<<<<<<< + * self._content_encoding = value * - * def __init__(self, protocol, loop, timer=None, # <<<<<<<<<<<<<< - * size_t max_line_size=8190, size_t max_headers=32768, - * size_t max_field_size=8190, payload_exception=None, */ + __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) { - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} + /* "aiohttp/_http_parser.pyx":365 + * + * 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, 365, __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; -static int __pyx_pf_7aiohttp_12_http_parser_19HttpResponseParserC___init__(struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParserC *__pyx_v_self, PyObject *__pyx_v_protocol, PyObject *__pyx_v_loop, 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, PyObject *__pyx_v_response_with_body, CYTHON_UNUSED PyObject *__pyx_v_read_until_eof, PyObject *__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; - __Pyx_RefNannySetupContext("__init__", 0); + /* "aiohttp/_http_parser.pyx":364 + * self._headers.add(name, value) + * + * if name is CONTENT_ENCODING: # <<<<<<<<<<<<<< + * self._content_encoding = value + * + */ + } - /* "aiohttp/_http_parser.pyx":345 - * response_with_body=True, read_until_eof=False, - * auto_decompress=True): - * self._init(cparser.HTTP_RESPONSE, protocol, loop, timer, # <<<<<<<<<<<<<< - * max_line_size, max_headers, max_field_size, - * payload_exception, response_with_body, auto_decompress) + /* "aiohttp/_http_parser.pyx":367 + * self._content_encoding = value + * + * PyByteArray_Resize(self._raw_name, 0) # <<<<<<<<<<<<<< + * PyByteArray_Resize(self._raw_value, 0) + * self._has_value = False */ - __pyx_t_2.__pyx_n = 7; - __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.auto_decompress = __pyx_v_auto_decompress; - __pyx_t_1 = ((struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpResponseParserC *)__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_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 345, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __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, 367, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "aiohttp/_http_parser.pyx":340 - * cdef class HttpResponseParserC(HttpParser): + /* "aiohttp/_http_parser.pyx":368 * - * def __init__(self, protocol, loop, timer=None, # <<<<<<<<<<<<<< - * size_t max_line_size=8190, size_t max_headers=32768, - * size_t max_field_size=8190, payload_exception=None, + * 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, 368, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "aiohttp/_http_parser.pyx":369 + * 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":370 + * 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, 370, __pyx_L1_error) + } + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 370, __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, 370, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "aiohttp/_http_parser.pyx":355 + * + * cdef _process_header(self): + * if self._raw_name: # <<<<<<<<<<<<<< + * raw_name = bytes(self._raw_name) + * raw_value = bytes(self._raw_value) + */ + } + + /* "aiohttp/_http_parser.pyx":354 + * self._last_error = None + * + * cdef _process_header(self): # <<<<<<<<<<<<<< + * if self._raw_name: + * raw_name = bytes(self._raw_name) */ /* function exit code */ - __pyx_r = 0; + __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._http_parser.HttpResponseParserC.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; + __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":349 - * payload_exception, response_with_body, auto_decompress) +/* "aiohttp/_http_parser.pyx":372 + * self._raw_headers.append((raw_name, raw_value)) * - * cdef object _on_status_complete(self): # <<<<<<<<<<<<<< - * if self._buf: - * self._reason = self._buf.decode('utf-8', 'surrogateescape') + * 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_19HttpResponseParserC__on_status_complete(struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParserC *__pyx_v_self) { +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; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - __Pyx_RefNannySetupContext("_on_status_complete", 0); + Py_ssize_t __pyx_t_3; + int __pyx_t_4; + __Pyx_RefNannySetupContext("_on_header_field", 0); - /* "aiohttp/_http_parser.pyx":350 + /* "aiohttp/_http_parser.pyx":375 + * cdef Py_ssize_t size + * cdef char *buf + * if self._has_value: # <<<<<<<<<<<<<< + * self._process_header() * - * cdef object _on_status_complete(self): - * if self._buf: # <<<<<<<<<<<<<< - * self._reason = self._buf.decode('utf-8', 'surrogateescape') - * self._buf.clear() */ - __pyx_t_1 = (__pyx_v_self->__pyx_base._buf != Py_None)&&(PyByteArray_GET_SIZE(__pyx_v_self->__pyx_base._buf) != 0); + __pyx_t_1 = (__pyx_v_self->_has_value != 0); if (__pyx_t_1) { - /* "aiohttp/_http_parser.pyx":351 - * cdef object _on_status_complete(self): - * if self._buf: - * self._reason = self._buf.decode('utf-8', 'surrogateescape') # <<<<<<<<<<<<<< - * self._buf.clear() + /* "aiohttp/_http_parser.pyx":376 + * cdef char *buf + * if self._has_value: + * self._process_header() # <<<<<<<<<<<<<< * + * size = PyByteArray_Size(self._raw_name) */ - if (unlikely(__pyx_v_self->__pyx_base._buf == Py_None)) { - PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "decode"); - __PYX_ERR(0, 351, __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, 351, __pyx_L1_error) + __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, 376, __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; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "aiohttp/_http_parser.pyx":352 - * if self._buf: - * self._reason = self._buf.decode('utf-8', 'surrogateescape') - * self._buf.clear() # <<<<<<<<<<<<<< + /* "aiohttp/_http_parser.pyx":375 + * cdef Py_ssize_t size + * cdef char *buf + * if self._has_value: # <<<<<<<<<<<<<< + * self._process_header() + * + */ + } + + /* "aiohttp/_http_parser.pyx":378 + * 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, 378, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v_size = __pyx_t_3; + + /* "aiohttp/_http_parser.pyx":379 * + * 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, 379, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "aiohttp/_http_parser.pyx":380 + * 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_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_self->__pyx_base._buf, __pyx_n_s_clear); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 352, __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); - } - } - if (__pyx_t_4) { - __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 352, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - } else { - __pyx_t_2 = __Pyx_PyObject_CallNoArg(__pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 352, __pyx_L1_error) - } - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __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":350 + /* "aiohttp/_http_parser.pyx":381 + * PyByteArray_Resize(self._raw_name, size + length) + * buf = PyByteArray_AsString(self._raw_name) + * memcpy(buf + size, at, length) # <<<<<<<<<<<<<< * - * cdef object _on_status_complete(self): - * if self._buf: # <<<<<<<<<<<<<< - * self._reason = self._buf.decode('utf-8', 'surrogateescape') - * self._buf.clear() + * 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":349 - * payload_exception, response_with_body, auto_decompress) + /* "aiohttp/_http_parser.pyx":372 + * self._raw_headers.append((raw_name, raw_value)) * - * cdef object _on_status_complete(self): # <<<<<<<<<<<<<< - * if self._buf: - * self._reason = self._buf.decode('utf-8', 'surrogateescape') + * cdef _on_header_field(self, char* at, size_t length): # <<<<<<<<<<<<<< + * cdef Py_ssize_t size + * cdef char *buf */ /* function exit code */ @@ -6342,9 +7565,7 @@ goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); - __Pyx_AddTraceback("aiohttp._http_parser.HttpResponseParserC._on_status_complete", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("aiohttp._http_parser.HttpParser._on_header_field", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); @@ -6352,3645 +7573,2742 @@ 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): +/* "aiohttp/_http_parser.pyx":383 + * memcpy(buf + size, at, length) + * + * cdef _on_header_value(self, char* at, size_t length): # <<<<<<<<<<<<<< + * cdef Py_ssize_t size + * cdef char *buf */ -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_19HttpResponseParserC_3__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_19HttpResponseParserC_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_19HttpResponseParserC_2__reduce_cython__(((struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParserC *)__pyx_v_self)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_19HttpResponseParserC_2__reduce_cython__(CYTHON_UNUSED struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParserC *__pyx_v_self) { +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; - __Pyx_RefNannySetupContext("__reduce_cython__", 0); + Py_ssize_t __pyx_t_2; + int __pyx_t_3; + __Pyx_RefNannySetupContext("_on_header_value", 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__") + /* "aiohttp/_http_parser.pyx":387 + * 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_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_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, 387, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(1, 2, __pyx_L1_error) + __pyx_v_size = __pyx_t_2; - /* "(tree fragment)":1 - * def __reduce_cython__(self): # <<<<<<<<<<<<<< - * raise TypeError("no default __reduce__ due to non-trivial __cinit__") - * def __setstate_cython__(self, __pyx_state): + /* "aiohttp/_http_parser.pyx":388 + * + * 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, 388, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* function exit code */ - __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_1); - __Pyx_AddTraceback("aiohttp._http_parser.HttpResponseParserC.__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__") + /* "aiohttp/_http_parser.pyx":389 + * 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; -/* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_19HttpResponseParserC_5__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_19HttpResponseParserC_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_19HttpResponseParserC_4__setstate_cython__(((struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParserC *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_19HttpResponseParserC_4__setstate_cython__(CYTHON_UNUSED struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParserC *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - __Pyx_RefNannySetupContext("__setstate_cython__", 0); + /* "aiohttp/_http_parser.pyx":390 + * 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)); - /* "(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__") # <<<<<<<<<<<<<< + /* "aiohttp/_http_parser.pyx":391 + * buf = PyByteArray_AsString(self._raw_value) + * memcpy(buf + size, at, length) + * self._has_value = True # <<<<<<<<<<<<<< + * + * cdef _on_headers_complete(self): */ - __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) + __pyx_v_self->_has_value = 1; - /* "(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__") + /* "aiohttp/_http_parser.pyx":383 + * 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.HttpResponseParserC.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + __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":355 +/* "aiohttp/_http_parser.pyx":393 + * self._has_value = True * - * - * cdef int cb_on_message_begin(cparser.http_parser* parser) except -1: # <<<<<<<<<<<<<< - * cdef HttpParser pyparser = parser.data + * cdef _on_headers_complete(self): # <<<<<<<<<<<<<< + * self._process_header() * */ -static int __pyx_f_7aiohttp_12_http_parser_cb_on_message_begin(struct http_parser *__pyx_v_parser) { - struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_pyparser = 0; - int __pyx_r; +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; + unsigned int __pyx_v_upgrade; + unsigned 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; - PyObject *__pyx_t_2 = NULL; + unsigned int __pyx_t_2; PyObject *__pyx_t_3 = NULL; - __Pyx_RefNannySetupContext("cb_on_message_begin", 0); + 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; + __Pyx_RefNannySetupContext("_on_headers_complete", 0); - /* "aiohttp/_http_parser.pyx":356 + /* "aiohttp/_http_parser.pyx":394 * - * cdef int cb_on_message_begin(cparser.http_parser* parser) except -1: - * cdef HttpParser pyparser = parser.data # <<<<<<<<<<<<<< + * cdef _on_headers_complete(self): + * self._process_header() # <<<<<<<<<<<<<< * - * pyparser._started = True + * method = http_method_str(self._cparser.method) */ - __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 = ((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, 394, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "aiohttp/_http_parser.pyx":396 + * self._process_header() + * + * method = http_method_str(self._cparser.method) # <<<<<<<<<<<<<< + * should_close = not cparser.http_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, 396, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_method = ((PyObject*)__pyx_t_1); __pyx_t_1 = 0; - /* "aiohttp/_http_parser.pyx":358 - * cdef HttpParser pyparser = parser.data + /* "aiohttp/_http_parser.pyx":397 * - * pyparser._started = True # <<<<<<<<<<<<<< - * pyparser._headers = [] - * pyparser._raw_headers = [] + * method = http_method_str(self._cparser.method) + * should_close = not cparser.http_should_keep_alive(self._cparser) # <<<<<<<<<<<<<< + * upgrade = self._cparser.upgrade + * chunked = self._cparser.flags & cparser.F_CHUNKED */ - __pyx_v_pyparser->_started = 1; + __pyx_v_should_close = (!(http_should_keep_alive(__pyx_v_self->_cparser) != 0)); - /* "aiohttp/_http_parser.pyx":359 + /* "aiohttp/_http_parser.pyx":398 + * method = http_method_str(self._cparser.method) + * should_close = not cparser.http_should_keep_alive(self._cparser) + * upgrade = self._cparser.upgrade # <<<<<<<<<<<<<< + * chunked = self._cparser.flags & cparser.F_CHUNKED * - * pyparser._started = True - * pyparser._headers = [] # <<<<<<<<<<<<<< - * pyparser._raw_headers = [] - * pyparser._buf.clear() */ - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 359, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_v_pyparser->_headers); - __Pyx_DECREF(__pyx_v_pyparser->_headers); - __pyx_v_pyparser->_headers = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; + __pyx_t_2 = __pyx_v_self->_cparser->upgrade; + __pyx_v_upgrade = __pyx_t_2; + + /* "aiohttp/_http_parser.pyx":399 + * should_close = not cparser.http_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":360 - * pyparser._started = True - * pyparser._headers = [] - * pyparser._raw_headers = [] # <<<<<<<<<<<<<< - * pyparser._buf.clear() - * pyparser._path = None + /* "aiohttp/_http_parser.pyx":401 + * chunked = self._cparser.flags & cparser.F_CHUNKED + * + * raw_headers = tuple(self._raw_headers) # <<<<<<<<<<<<<< + * headers = CIMultiDictProxy(self._headers) + * */ - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 360, __pyx_L1_error) + if (unlikely(__pyx_v_self->_raw_headers == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + __PYX_ERR(0, 401, __pyx_L1_error) + } + __pyx_t_1 = PyList_AsTuple(__pyx_v_self->_raw_headers); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 401, __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_v_raw_headers = ((PyObject*)__pyx_t_1); __pyx_t_1 = 0; - /* "aiohttp/_http_parser.pyx":361 - * pyparser._headers = [] - * pyparser._raw_headers = [] - * pyparser._buf.clear() # <<<<<<<<<<<<<< - * pyparser._path = None - * pyparser._reason = None + /* "aiohttp/_http_parser.pyx":402 + * + * raw_headers = tuple(self._raw_headers) + * headers = CIMultiDictProxy(self._headers) # <<<<<<<<<<<<<< + * + * if upgrade or self._cparser.method == 5: # cparser.CONNECT: */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_pyparser->_buf, __pyx_n_s_clear); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 361, __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(__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_2, function); + __Pyx_DECREF_SET(__pyx_t_3, function); } } - if (__pyx_t_3) { - __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 361, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } else { - __pyx_t_1 = __Pyx_PyObject_CallNoArg(__pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 361, __pyx_L1_error) - } + __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, 402, __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; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_headers = __pyx_t_1; + __pyx_t_1 = 0; - /* "aiohttp/_http_parser.pyx":362 - * pyparser._raw_headers = [] - * pyparser._buf.clear() - * pyparser._path = None # <<<<<<<<<<<<<< - * pyparser._reason = None - * return 0 + /* "aiohttp/_http_parser.pyx":404 + * headers = CIMultiDictProxy(self._headers) + * + * if upgrade or self._cparser.method == 5: # cparser.CONNECT: # <<<<<<<<<<<<<< + * self._upgraded = True + * */ - __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); + __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":363 - * pyparser._buf.clear() - * pyparser._path = None - * pyparser._reason = None # <<<<<<<<<<<<<< - * return 0 + /* "aiohttp/_http_parser.pyx":405 + * + * if upgrade or self._cparser.method == 5: # cparser.CONNECT: + * self._upgraded = True # <<<<<<<<<<<<<< * + * # do not support old websocket spec */ - __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); + __pyx_v_self->_upgraded = 1; - /* "aiohttp/_http_parser.pyx":364 - * pyparser._path = None - * pyparser._reason = None - * return 0 # <<<<<<<<<<<<<< + /* "aiohttp/_http_parser.pyx":404 + * headers = CIMultiDictProxy(self._headers) * + * if upgrade or self._cparser.method == 5: # cparser.CONNECT: # <<<<<<<<<<<<<< + * self._upgraded = True * */ - __pyx_r = 0; - goto __pyx_L0; + } - /* "aiohttp/_http_parser.pyx":355 - * + /* "aiohttp/_http_parser.pyx":408 * - * cdef int cb_on_message_begin(cparser.http_parser* parser) except -1: # <<<<<<<<<<<<<< - * cdef HttpParser pyparser = parser.data + * # 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, 408, __pyx_L1_error) + __pyx_t_6 = (__pyx_t_5 != 0); + if (unlikely(__pyx_t_6)) { - /* 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":409 + * # 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, 409, __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, 409, __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, 409, __pyx_L1_error) -/* "aiohttp/_http_parser.pyx":367 + /* "aiohttp/_http_parser.pyx":408 * + * # do not support old websocket spec + * if SEC_WEBSOCKET_KEY1 in headers: # <<<<<<<<<<<<<< + * raise InvalidHeader(SEC_WEBSOCKET_KEY1) * - * cdef int cb_on_url(cparser.http_parser* 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(struct http_parser *__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; - __Pyx_RefNannySetupContext("cb_on_url", 0); + /* "aiohttp/_http_parser.pyx":411 + * 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":369 - * cdef int cb_on_url(cparser.http_parser* parser, - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data # <<<<<<<<<<<<<< - * try: - * if length > pyparser._max_line_size: + /* "aiohttp/_http_parser.pyx":412 + * + * encoding = None + * enc = self._content_encoding # <<<<<<<<<<<<<< + * if enc is not None: + * self._content_encoding = None */ - __pyx_t_1 = ((PyObject *)__pyx_v_parser->data); + __pyx_t_1 = __pyx_v_self->_content_encoding; __Pyx_INCREF(__pyx_t_1); - __pyx_v_pyparser = ((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)__pyx_t_1); + __pyx_v_enc = __pyx_t_1; __pyx_t_1 = 0; - /* "aiohttp/_http_parser.pyx":370 - * 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":413 + * encoding = None + * enc = self._content_encoding + * if enc is not None: # <<<<<<<<<<<<<< + * self._content_encoding = None + * enc = enc.lower() */ - { - __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":371 - * 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_6 = (__pyx_v_enc != Py_None); + __pyx_t_5 = (__pyx_t_6 != 0); + if (__pyx_t_5) { + + /* "aiohttp/_http_parser.pyx":414 + * enc = self._content_encoding + * if enc is not None: + * self._content_encoding = None # <<<<<<<<<<<<<< + * enc = enc.lower() + * if enc in ('gzip', 'deflate', 'br'): */ - __pyx_t_5 = ((__pyx_v_length > __pyx_v_pyparser->_max_line_size) != 0); - if (unlikely(__pyx_t_5)) { - - /* "aiohttp/_http_parser.pyx":372 - * try: - * if length > pyparser._max_line_size: - * raise LineTooLong( # <<<<<<<<<<<<<< - * 'Status line is too long', pyparser._max_line_size, length) - * pyparser._buf.extend(at[:length]) + __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":415 + * if enc is not None: + * self._content_encoding = None + * enc = enc.lower() # <<<<<<<<<<<<<< + * if enc in ('gzip', 'deflate', 'br'): + * encoding = enc */ - __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_LineTooLong); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 372, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_6); + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_enc, __pyx_n_s_lower); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 415, __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, 415, __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":373 - * if length > pyparser._max_line_size: - * raise LineTooLong( - * 'Status line is too long', pyparser._max_line_size, length) # <<<<<<<<<<<<<< - * pyparser._buf.extend(at[:length]) - * except BaseException as ex: + /* "aiohttp/_http_parser.pyx":416 + * self._content_encoding = None + * enc = enc.lower() + * if enc in ('gzip', 'deflate', 'br'): # <<<<<<<<<<<<<< + * encoding = enc + * */ - __pyx_t_7 = __Pyx_PyInt_FromSize_t(__pyx_v_pyparser->_max_line_size); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 373, __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, 373, __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, 372, __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, 372, __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, 372, __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, 372, __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, 372, __pyx_L3_error) + __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, 416, __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, 416, __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, 416, __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":371 - * 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":417 + * 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":374 - * raise LineTooLong( - * 'Status line is too long', pyparser._max_line_size, length) - * pyparser._buf.extend(at[:length]) # <<<<<<<<<<<<<< - * except BaseException as ex: - * pyparser._last_error = ex + /* "aiohttp/_http_parser.pyx":416 + * self._content_encoding = None + * enc = enc.lower() + * if enc in ('gzip', 'deflate', 'br'): # <<<<<<<<<<<<<< + * encoding = enc + * */ - __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_pyparser->_buf, __pyx_n_s_extend); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 374, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_11 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_at + 0, __pyx_v_length - 0); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 374, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_11); - __pyx_t_8 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_6))) { - __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_6); - if (likely(__pyx_t_8)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); - __Pyx_INCREF(__pyx_t_8); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_6, function); - } - } - if (!__pyx_t_8) { - __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_6, __pyx_t_11); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 374, __pyx_L3_error) - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else { - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_6)) { - PyObject *__pyx_temp[2] = {__pyx_t_8, __pyx_t_11}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_6, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 374, __pyx_L3_error) - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_6)) { - PyObject *__pyx_temp[2] = {__pyx_t_8, __pyx_t_11}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_6, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 374, __pyx_L3_error) - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - } else - #endif - { - __pyx_t_7 = PyTuple_New(1+1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 374, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_GIVEREF(__pyx_t_8); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_8); __pyx_t_8 = NULL; - __Pyx_GIVEREF(__pyx_t_11); - PyTuple_SET_ITEM(__pyx_t_7, 0+1, __pyx_t_11); - __pyx_t_11 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_7, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 374, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } - } - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } - /* "aiohttp/_http_parser.pyx":370 - * 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":413 + * encoding = None + * enc = self._content_encoding + * if enc is not None: # <<<<<<<<<<<<<< + * self._content_encoding = None + * enc = enc.lower() */ - } + } - /* "aiohttp/_http_parser.pyx":379 - * return -1 - * else: - * return 0 # <<<<<<<<<<<<<< - * + /* "aiohttp/_http_parser.pyx":419 + * encoding = enc * + * if self._cparser.type == cparser.HTTP_REQUEST: # <<<<<<<<<<<<<< + * msg = _new_request_message( + * method, self._path, */ - /*else:*/ { - __pyx_r = 0; - goto __pyx_L6_except_return; - } - __pyx_L3_error:; - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_6 = ((__pyx_v_self->_cparser->type == HTTP_REQUEST) != 0); + if (__pyx_t_6) { - /* "aiohttp/_http_parser.pyx":375 - * 'Status line is too long', pyparser._max_line_size, length) - * pyparser._buf.extend(at[:length]) - * except BaseException as ex: # <<<<<<<<<<<<<< - * pyparser._last_error = ex - * return -1 + /* "aiohttp/_http_parser.pyx":421 + * 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_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_1, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(0, 375, __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_ex = __pyx_t_6; - /*try:*/ { + __pyx_t_1 = __pyx_v_self->_path; + __Pyx_INCREF(__pyx_t_1); - /* "aiohttp/_http_parser.pyx":376 - * pyparser._buf.extend(at[:length]) - * except BaseException as ex: - * pyparser._last_error = ex # <<<<<<<<<<<<<< - * return -1 - * else: + /* "aiohttp/_http_parser.pyx":422 + * msg = _new_request_message( + * method, self._path, + * self.http_version(), headers, raw_headers, # <<<<<<<<<<<<<< + * should_close, encoding, upgrade, chunked, self._url) + * 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; + __pyx_t_3 = __pyx_f_7aiohttp_12_http_parser_10HttpParser_http_version(__pyx_v_self); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 422, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); - /* "aiohttp/_http_parser.pyx":377 - * except BaseException as ex: - * pyparser._last_error = ex - * return -1 # <<<<<<<<<<<<<< - * else: - * return 0 + /* "aiohttp/_http_parser.pyx":423 + * method, self._path, + * self.http_version(), headers, raw_headers, + * should_close, encoding, upgrade, chunked, self._url) # <<<<<<<<<<<<<< + * else: + * msg = _new_response_message( */ - __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_L14_return; - } + __pyx_t_4 = __pyx_v_self->_url; + __Pyx_INCREF(__pyx_t_4); - /* "aiohttp/_http_parser.pyx":375 - * 'Status line is too long', pyparser._max_line_size, length) - * pyparser._buf.extend(at[:length]) - * except BaseException as ex: # <<<<<<<<<<<<<< - * pyparser._last_error = ex - * return -1 + /* "aiohttp/_http_parser.pyx":420 + * + * if self._cparser.type == cparser.HTTP_REQUEST: + * msg = _new_request_message( # <<<<<<<<<<<<<< + * method, self._path, + * self.http_version(), headers, raw_headers, */ - /*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:; + __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, 420, __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":370 - * 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":419 + * encoding = enc + * + * if self._cparser.type == cparser.HTTP_REQUEST: # <<<<<<<<<<<<<< + * msg = _new_request_message( + * method, self._path, */ - __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; + goto __pyx_L12; } - /* "aiohttp/_http_parser.pyx":367 - * - * - * cdef int cb_on_url(cparser.http_parser* parser, # <<<<<<<<<<<<<< - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data + /* "aiohttp/_http_parser.pyx":425 + * 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*/ { - /* 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":382 - * - * - * cdef int cb_on_status(cparser.http_parser* parser, # <<<<<<<<<<<<<< - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data + /* "aiohttp/_http_parser.pyx":426 + * 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, 426, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_4 = __pyx_v_self->_reason; + __Pyx_INCREF(__pyx_t_4); -static int __pyx_f_7aiohttp_12_http_parser_cb_on_status(struct http_parser *__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; - __Pyx_RefNannySetupContext("cb_on_status", 0); - - /* "aiohttp/_http_parser.pyx":384 - * cdef int cb_on_status(cparser.http_parser* parser, - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data # <<<<<<<<<<<<<< - * cdef str reason - * try: + /* "aiohttp/_http_parser.pyx":425 + * 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_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; + __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, 425, __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":386 - * cdef HttpParser pyparser = parser.data - * cdef str reason - * try: # <<<<<<<<<<<<<< - * if length > pyparser._max_line_size: - * raise LineTooLong( + /* "aiohttp/_http_parser.pyx":430 + * upgrade, chunked) + * + * if (self._cparser.content_length > 0 or chunked or # <<<<<<<<<<<<<< + * self._cparser.method == 5): # CONNECT: 5 + * payload = StreamReader( */ - { - __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:*/ { + __pyx_t_5 = ((__pyx_v_self->_cparser->content_length > 0) != 0); + if (!__pyx_t_5) { + } else { + __pyx_t_6 = __pyx_t_5; + goto __pyx_L14_bool_binop_done; + } + __pyx_t_5 = (__pyx_v_chunked != 0); + if (!__pyx_t_5) { + } else { + __pyx_t_6 = __pyx_t_5; + goto __pyx_L14_bool_binop_done; + } - /* "aiohttp/_http_parser.pyx":387 - * 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":431 + * + * if (self._cparser.content_length > 0 or chunked or + * self._cparser.method == 5): # CONNECT: 5 # <<<<<<<<<<<<<< + * payload = StreamReader( + * self._protocol, timer=self._timer, loop=self._loop) */ - __pyx_t_5 = ((__pyx_v_length > __pyx_v_pyparser->_max_line_size) != 0); - if (unlikely(__pyx_t_5)) { + __pyx_t_5 = ((__pyx_v_self->_cparser->method == 5) != 0); + __pyx_t_6 = __pyx_t_5; + __pyx_L14_bool_binop_done:; - /* "aiohttp/_http_parser.pyx":388 - * try: - * if length > pyparser._max_line_size: - * raise LineTooLong( # <<<<<<<<<<<<<< - * 'Status line is too long', pyparser._max_line_size, length) - * pyparser._buf.extend(at[:length]) + /* "aiohttp/_http_parser.pyx":430 + * upgrade, chunked) + * + * if (self._cparser.content_length > 0 or chunked or # <<<<<<<<<<<<<< + * self._cparser.method == 5): # CONNECT: 5 + * payload = StreamReader( */ - __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_LineTooLong); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 388, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_6); + if (__pyx_t_6) { - /* "aiohttp/_http_parser.pyx":389 - * if length > pyparser._max_line_size: - * raise LineTooLong( - * 'Status line is too long', pyparser._max_line_size, length) # <<<<<<<<<<<<<< - * pyparser._buf.extend(at[:length]) - * except BaseException as ex: + /* "aiohttp/_http_parser.pyx":432 + * if (self._cparser.content_length > 0 or chunked or + * self._cparser.method == 5): # CONNECT: 5 + * payload = StreamReader( # <<<<<<<<<<<<<< + * self._protocol, timer=self._timer, loop=self._loop) + * else: */ - __pyx_t_7 = __Pyx_PyInt_FromSize_t(__pyx_v_pyparser->_max_line_size); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 389, __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, 389, __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, 388, __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, 388, __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, 388, __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, 388, __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, 388, __pyx_L3_error) + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 432, __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":387 - * 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":433 + * self._cparser.method == 5): # CONNECT: 5 + * payload = StreamReader( + * self._protocol, timer=self._timer, loop=self._loop) # <<<<<<<<<<<<<< + * else: + * payload = EMPTY_PAYLOAD */ - } + __pyx_t_4 = __Pyx_PyDict_NewPresized(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 433, __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, 433, __pyx_L1_error) + if (PyDict_SetItem(__pyx_t_4, __pyx_n_s_loop, __pyx_v_self->_loop) < 0) __PYX_ERR(0, 433, __pyx_L1_error) - /* "aiohttp/_http_parser.pyx":390 - * raise LineTooLong( - * 'Status line is too long', pyparser._max_line_size, length) - * pyparser._buf.extend(at[:length]) # <<<<<<<<<<<<<< - * except BaseException as ex: - * pyparser._last_error = ex + /* "aiohttp/_http_parser.pyx":432 + * if (self._cparser.content_length > 0 or chunked or + * self._cparser.method == 5): # CONNECT: 5 + * payload = StreamReader( # <<<<<<<<<<<<<< + * self._protocol, timer=self._timer, loop=self._loop) + * else: */ - __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_pyparser->_buf, __pyx_n_s_extend); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 390, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_6); - __pyx_t_11 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_at + 0, __pyx_v_length - 0); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 390, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_11); - __pyx_t_8 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_6))) { - __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_6); - if (likely(__pyx_t_8)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); - __Pyx_INCREF(__pyx_t_8); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_6, function); - } - } - if (!__pyx_t_8) { - __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_6, __pyx_t_11); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 390, __pyx_L3_error) - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else { - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_6)) { - PyObject *__pyx_temp[2] = {__pyx_t_8, __pyx_t_11}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_6, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 390, __pyx_L3_error) - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_6)) { - PyObject *__pyx_temp[2] = {__pyx_t_8, __pyx_t_11}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_6, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 390, __pyx_L3_error) - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - } else - #endif - { - __pyx_t_7 = PyTuple_New(1+1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 390, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_GIVEREF(__pyx_t_8); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_8); __pyx_t_8 = NULL; - __Pyx_GIVEREF(__pyx_t_11); - PyTuple_SET_ITEM(__pyx_t_7, 0+1, __pyx_t_11); - __pyx_t_11 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_7, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 390, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } - } - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __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, 432, __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":386 - * cdef HttpParser pyparser = parser.data - * cdef str reason - * try: # <<<<<<<<<<<<<< - * if length > pyparser._max_line_size: - * raise LineTooLong( + /* "aiohttp/_http_parser.pyx":430 + * upgrade, chunked) + * + * if (self._cparser.content_length > 0 or chunked or # <<<<<<<<<<<<<< + * self._cparser.method == 5): # CONNECT: 5 + * payload = StreamReader( */ - } + goto __pyx_L13; + } - /* "aiohttp/_http_parser.pyx":395 - * return -1 - * else: - * return 0 # <<<<<<<<<<<<<< - * + /* "aiohttp/_http_parser.pyx":435 + * self._protocol, timer=self._timer, loop=self._loop) + * else: + * payload = EMPTY_PAYLOAD # <<<<<<<<<<<<<< * + * self._payload = payload */ - /*else:*/ { - __pyx_r = 0; - goto __pyx_L6_except_return; - } - __pyx_L3_error:; - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + /*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":391 - * 'Status line is too long', pyparser._max_line_size, length) - * pyparser._buf.extend(at[:length]) - * except BaseException as ex: # <<<<<<<<<<<<<< - * pyparser._last_error = ex - * return -1 + /* "aiohttp/_http_parser.pyx":437 + * payload = EMPTY_PAYLOAD + * + * self._payload = payload # <<<<<<<<<<<<<< + * if encoding is not None and self._auto_decompress: + * self._payload = DeflateBuffer(payload, encoding) */ - __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_1, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(0, 391, __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_ex = __pyx_t_6; - /*try:*/ { + __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":392 - * pyparser._buf.extend(at[:length]) - * except BaseException as ex: - * pyparser._last_error = ex # <<<<<<<<<<<<<< - * return -1 - * else: + /* "aiohttp/_http_parser.pyx":438 + * + * self._payload = payload + * if encoding is not None and self._auto_decompress: # <<<<<<<<<<<<<< + * self._payload = DeflateBuffer(payload, encoding) + * */ - __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; + __pyx_t_5 = (__pyx_v_encoding != Py_None); + __pyx_t_8 = (__pyx_t_5 != 0); + if (__pyx_t_8) { + } else { + __pyx_t_6 = __pyx_t_8; + goto __pyx_L18_bool_binop_done; + } + __pyx_t_8 = (__pyx_v_self->_auto_decompress != 0); + __pyx_t_6 = __pyx_t_8; + __pyx_L18_bool_binop_done:; + if (__pyx_t_6) { - /* "aiohttp/_http_parser.pyx":393 - * except BaseException as ex: - * pyparser._last_error = ex - * return -1 # <<<<<<<<<<<<<< - * else: - * return 0 + /* "aiohttp/_http_parser.pyx":439 + * self._payload = payload + * if encoding is not None and self._auto_decompress: + * self._payload = DeflateBuffer(payload, encoding) # <<<<<<<<<<<<<< + * + * if not self._response_with_body: */ - __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_L14_return; + __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; } - - /* "aiohttp/_http_parser.pyx":391 - * 'Status line is too long', pyparser._max_line_size, length) - * pyparser._buf.extend(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; - } + } + #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, 439, __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, 439, __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, 439, __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, 439, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; + __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":386 - * cdef HttpParser pyparser = parser.data - * cdef str reason - * try: # <<<<<<<<<<<<<< - * if length > pyparser._max_line_size: - * raise LineTooLong( + /* "aiohttp/_http_parser.pyx":438 + * + * self._payload = payload + * if encoding is not None and self._auto_decompress: # <<<<<<<<<<<<<< + * self._payload = DeflateBuffer(payload, encoding) + * */ - __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":382 + /* "aiohttp/_http_parser.pyx":441 + * 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":442 + * + * 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":441 + * self._payload = DeflateBuffer(payload, encoding) + * + * if not self._response_with_body: # <<<<<<<<<<<<<< + * payload = EMPTY_PAYLOAD + * + */ + } + + /* "aiohttp/_http_parser.pyx":444 + * 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, 444, __pyx_L1_error) + } + __pyx_t_7 = PyTuple_New(2); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 444, __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, 444, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + + /* "aiohttp/_http_parser.pyx":393 + * self._has_value = True + * + * cdef _on_headers_complete(self): # <<<<<<<<<<<<<< + * self._process_header() * - * cdef int cb_on_status(cparser.http_parser* parser, # <<<<<<<<<<<<<< - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data */ /* 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_3); + __Pyx_XDECREF(__pyx_t_4); __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_AddTraceback("aiohttp._http_parser.HttpParser._on_headers_complete", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_pyparser); - __Pyx_XDECREF(__pyx_v_ex); + __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":398 - * +/* "aiohttp/_http_parser.pyx":446 + * self._messages.append((msg, payload)) * - * cdef int cb_on_header_field(cparser.http_parser* parser, # <<<<<<<<<<<<<< - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data + * cdef _on_message_complete(self): # <<<<<<<<<<<<<< + * self._payload.feed_eof() + * self._payload = None */ -static int __pyx_f_7aiohttp_12_http_parser_cb_on_header_field(struct http_parser *__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; +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; - 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; - __Pyx_RefNannySetupContext("cb_on_header_field", 0); + __Pyx_RefNannySetupContext("_on_message_complete", 0); - /* "aiohttp/_http_parser.pyx":400 - * cdef int cb_on_header_field(cparser.http_parser* parser, - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data # <<<<<<<<<<<<<< - * try: - * pyparser._on_status_complete() + /* "aiohttp/_http_parser.pyx":447 + * + * cdef _on_message_complete(self): + * self._payload.feed_eof() # <<<<<<<<<<<<<< + * self._payload = None + * */ - __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; + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_v_self->_payload, __pyx_n_s_feed_eof); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 447, __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, 447, __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":401 - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * pyparser._on_status_complete() - * if length > pyparser._max_field_size: + /* "aiohttp/_http_parser.pyx":448 + * cdef _on_message_complete(self): + * self._payload.feed_eof() + * self._payload = None # <<<<<<<<<<<<<< + * + * cdef _on_chunk_header(self): */ - { - __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:*/ { + __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":402 - * cdef HttpParser pyparser = parser.data - * try: - * pyparser._on_status_complete() # <<<<<<<<<<<<<< - * if length > pyparser._max_field_size: - * raise LineTooLong( - */ - __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, 402, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":403 - * try: - * pyparser._on_status_complete() - * if length > pyparser._max_field_size: # <<<<<<<<<<<<<< - * raise LineTooLong( - * 'Header name is too long', pyparser._max_field_size, length) - */ - __pyx_t_5 = ((__pyx_v_length > __pyx_v_pyparser->_max_field_size) != 0); - if (unlikely(__pyx_t_5)) { - - /* "aiohttp/_http_parser.pyx":404 - * pyparser._on_status_complete() - * if length > pyparser._max_field_size: - * raise LineTooLong( # <<<<<<<<<<<<<< - * 'Header name is too long', pyparser._max_field_size, length) - * pyparser._on_header_field( - */ - __pyx_t_6 = __Pyx_GetModuleGlobalName(__pyx_n_s_LineTooLong); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 404, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_6); - - /* "aiohttp/_http_parser.pyx":405 - * if length > pyparser._max_field_size: - * raise LineTooLong( - * 'Header name is too long', pyparser._max_field_size, length) # <<<<<<<<<<<<<< - * pyparser._on_header_field( - * at[:length].decode('utf-8', 'surrogateescape'), at[:length]) - */ - __pyx_t_7 = __Pyx_PyInt_FromSize_t(__pyx_v_pyparser->_max_field_size); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 405, __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, 405, __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_Header_name_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, 404, __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_Header_name_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, 404, __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, 404, __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_Header_name_is_too_long); - __Pyx_GIVEREF(__pyx_kp_u_Header_name_is_too_long); - PyTuple_SET_ITEM(__pyx_t_11, 0+__pyx_t_10, __pyx_kp_u_Header_name_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, 404, __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, 404, __pyx_L3_error) - - /* "aiohttp/_http_parser.pyx":403 - * try: - * pyparser._on_status_complete() - * if length > pyparser._max_field_size: # <<<<<<<<<<<<<< - * raise LineTooLong( - * 'Header name is too long', pyparser._max_field_size, length) - */ - } - - /* "aiohttp/_http_parser.pyx":407 - * 'Header name is too long', pyparser._max_field_size, length) - * pyparser._on_header_field( - * at[:length].decode('utf-8', 'surrogateescape'), at[:length]) # <<<<<<<<<<<<<< - * except BaseException as ex: - * pyparser._last_error = ex - */ - __pyx_t_1 = __Pyx_decode_c_string(__pyx_v_at, 0, __pyx_v_length, NULL, ((char const *)"surrogateescape"), PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 407, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_6 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_at + 0, __pyx_v_length - 0); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 407, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_6); - - /* "aiohttp/_http_parser.pyx":406 - * raise LineTooLong( - * 'Header name is too long', pyparser._max_field_size, length) - * pyparser._on_header_field( # <<<<<<<<<<<<<< - * at[:length].decode('utf-8', 'surrogateescape'), at[:length]) - * except BaseException as ex: + /* "aiohttp/_http_parser.pyx":446 + * self._messages.append((msg, payload)) + * + * cdef _on_message_complete(self): # <<<<<<<<<<<<<< + * self._payload.feed_eof() + * self._payload = None */ - __pyx_t_11 = ((struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser *)__pyx_v_pyparser->__pyx_vtab)->_on_header_field(__pyx_v_pyparser, ((PyObject*)__pyx_t_1), ((PyObject*)__pyx_t_6)); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 406, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_11); - __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; - /* "aiohttp/_http_parser.pyx":401 - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * pyparser._on_status_complete() - * if length > pyparser._max_field_size: - */ - } + /* 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":412 - * return -1 - * else: - * return 0 # <<<<<<<<<<<<<< +/* "aiohttp/_http_parser.pyx":450 + * self._payload = None * + * cdef _on_chunk_header(self): # <<<<<<<<<<<<<< + * self._payload.begin_http_chunk_receiving() * */ - /*else:*/ { - __pyx_r = 0; - goto __pyx_L6_except_return; - } - __pyx_L3_error:; - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; - - /* "aiohttp/_http_parser.pyx":408 - * pyparser._on_header_field( - * at[:length].decode('utf-8', 'surrogateescape'), 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_header_field", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_11, &__pyx_t_6, &__pyx_t_1) < 0) __PYX_ERR(0, 408, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_GOTREF(__pyx_t_6); - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_6); - __pyx_v_ex = __pyx_t_6; - /*try:*/ { - - /* "aiohttp/_http_parser.pyx":409 - * at[:length].decode('utf-8', 'surrogateescape'), 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":410 - * 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; - } +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; + __Pyx_RefNannySetupContext("_on_chunk_header", 0); - /* "aiohttp/_http_parser.pyx":408 - * pyparser._on_header_field( - * at[:length].decode('utf-8', 'surrogateescape'), at[:length]) - * except BaseException as ex: # <<<<<<<<<<<<<< - * pyparser._last_error = ex - * return -1 + /* "aiohttp/_http_parser.pyx":451 + * + * cdef _on_chunk_header(self): + * self._payload.begin_http_chunk_receiving() # <<<<<<<<<<<<<< + * + * cdef _on_chunk_complete(self): */ - /*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; - } - } + __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, 451, __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); } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; - - /* "aiohttp/_http_parser.pyx":401 - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * pyparser._on_status_complete() - * if length > 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; } + __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, 451, __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":398 + /* "aiohttp/_http_parser.pyx":450 + * self._payload = None * + * cdef _on_chunk_header(self): # <<<<<<<<<<<<<< + * self._payload.begin_http_chunk_receiving() * - * cdef int cb_on_header_field(cparser.http_parser* parser, # <<<<<<<<<<<<<< - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data */ /* 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_XDECREF(__pyx_t_9); - __Pyx_XDECREF(__pyx_t_11); - __Pyx_AddTraceback("aiohttp._http_parser.cb_on_header_field", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -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_XDECREF((PyObject *)__pyx_v_pyparser); - __Pyx_XDECREF(__pyx_v_ex); + __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "aiohttp/_http_parser.pyx":415 +/* "aiohttp/_http_parser.pyx":453 + * self._payload.begin_http_chunk_receiving() * + * cdef _on_chunk_complete(self): # <<<<<<<<<<<<<< + * self._payload.end_http_chunk_receiving() * - * cdef int cb_on_header_value(cparser.http_parser* 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(struct http_parser *__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; +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; - PyObject *__pyx_t_4 = NULL; - int __pyx_t_5; - int __pyx_t_6; - Py_ssize_t __pyx_t_7; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; - PyObject *__pyx_t_11 = NULL; - int __pyx_t_12; - PyObject *__pyx_t_13 = NULL; - __Pyx_RefNannySetupContext("cb_on_header_value", 0); + __Pyx_RefNannySetupContext("_on_chunk_complete", 0); - /* "aiohttp/_http_parser.pyx":417 - * cdef int cb_on_header_value(cparser.http_parser* parser, - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data # <<<<<<<<<<<<<< - * try: - * if pyparser._header_value is not None: + /* "aiohttp/_http_parser.pyx":454 + * + * cdef _on_chunk_complete(self): + * self._payload.end_http_chunk_receiving() # <<<<<<<<<<<<<< + * + * cdef object _on_status_complete(self): */ - __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; + __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, 454, __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, 454, __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":418 - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * if pyparser._header_value is not None: - * if len(pyparser._header_value) + length > pyparser._max_field_size: + /* "aiohttp/_http_parser.pyx":453 + * self._payload.begin_http_chunk_receiving() + * + * cdef _on_chunk_complete(self): # <<<<<<<<<<<<<< + * self._payload.end_http_chunk_receiving() + * */ - { - __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":419 - * cdef HttpParser pyparser = parser.data - * try: - * if pyparser._header_value is not None: # <<<<<<<<<<<<<< - * if len(pyparser._header_value) + length > pyparser._max_field_size: - * raise LineTooLong( - */ - __pyx_t_5 = (__pyx_v_pyparser->_header_value != ((PyObject*)Py_None)); - __pyx_t_6 = (__pyx_t_5 != 0); - if (__pyx_t_6) { + /* 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":420 - * try: - * if pyparser._header_value is not None: - * if len(pyparser._header_value) + length > pyparser._max_field_size: # <<<<<<<<<<<<<< - * raise LineTooLong( - * 'Header value is too long', pyparser._max_field_size, +/* "aiohttp/_http_parser.pyx":456 + * self._payload.end_http_chunk_receiving() + * + * cdef object _on_status_complete(self): # <<<<<<<<<<<<<< + * pass + * */ - __pyx_t_1 = __pyx_v_pyparser->_header_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, 420, __pyx_L3_error) - } - __pyx_t_7 = __Pyx_PyUnicode_GET_LENGTH(__pyx_t_1); if (unlikely(__pyx_t_7 == ((Py_ssize_t)-1))) __PYX_ERR(0, 420, __pyx_L3_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_6 = (((__pyx_t_7 + __pyx_v_length) > __pyx_v_pyparser->_max_field_size) != 0); - if (unlikely(__pyx_t_6)) { - /* "aiohttp/_http_parser.pyx":421 - * if pyparser._header_value is not None: - * if len(pyparser._header_value) + length > pyparser._max_field_size: - * raise LineTooLong( # <<<<<<<<<<<<<< - * 'Header value is too long', pyparser._max_field_size, - * len(pyparser._header_value) + length) - */ - __pyx_t_8 = __Pyx_GetModuleGlobalName(__pyx_n_s_LineTooLong); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 421, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_8); - - /* "aiohttp/_http_parser.pyx":422 - * if len(pyparser._header_value) + length > pyparser._max_field_size: - * raise LineTooLong( - * 'Header value is too long', pyparser._max_field_size, # <<<<<<<<<<<<<< - * len(pyparser._header_value) + length) - * elif length > pyparser._max_field_size: - */ - __pyx_t_9 = __Pyx_PyInt_FromSize_t(__pyx_v_pyparser->_max_field_size); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 422, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_9); - - /* "aiohttp/_http_parser.pyx":423 - * raise LineTooLong( - * 'Header value is too long', pyparser._max_field_size, - * len(pyparser._header_value) + length) # <<<<<<<<<<<<<< - * elif length > pyparser._max_field_size: - * raise LineTooLong( - */ - __pyx_t_10 = __pyx_v_pyparser->_header_value; - __Pyx_INCREF(__pyx_t_10); - if (unlikely(__pyx_t_10 == Py_None)) { - PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - __PYX_ERR(0, 423, __pyx_L3_error) - } - __pyx_t_7 = __Pyx_PyUnicode_GET_LENGTH(__pyx_t_10); if (unlikely(__pyx_t_7 == ((Py_ssize_t)-1))) __PYX_ERR(0, 423, __pyx_L3_error) - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_t_10 = __Pyx_PyInt_FromSize_t((__pyx_t_7 + __pyx_v_length)); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 423, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_10); - __pyx_t_11 = NULL; - __pyx_t_12 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_8))) { - __pyx_t_11 = PyMethod_GET_SELF(__pyx_t_8); - if (likely(__pyx_t_11)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_8); - __Pyx_INCREF(__pyx_t_11); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_8, function); - __pyx_t_12 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_8)) { - PyObject *__pyx_temp[4] = {__pyx_t_11, __pyx_kp_u_Header_value_is_too_long, __pyx_t_9, __pyx_t_10}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_8, __pyx_temp+1-__pyx_t_12, 3+__pyx_t_12); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 421, __pyx_L3_error) - __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_8)) { - PyObject *__pyx_temp[4] = {__pyx_t_11, __pyx_kp_u_Header_value_is_too_long, __pyx_t_9, __pyx_t_10}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_8, __pyx_temp+1-__pyx_t_12, 3+__pyx_t_12); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 421, __pyx_L3_error) - __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - } else - #endif - { - __pyx_t_13 = PyTuple_New(3+__pyx_t_12); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 421, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_13); - if (__pyx_t_11) { - __Pyx_GIVEREF(__pyx_t_11); PyTuple_SET_ITEM(__pyx_t_13, 0, __pyx_t_11); __pyx_t_11 = 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_13, 0+__pyx_t_12, __pyx_kp_u_Header_value_is_too_long); - __Pyx_GIVEREF(__pyx_t_9); - PyTuple_SET_ITEM(__pyx_t_13, 1+__pyx_t_12, __pyx_t_9); - __Pyx_GIVEREF(__pyx_t_10); - PyTuple_SET_ITEM(__pyx_t_13, 2+__pyx_t_12, __pyx_t_10); - __pyx_t_9 = 0; - __pyx_t_10 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_t_13, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 421, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; - } - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(0, 421, __pyx_L3_error) +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); - /* "aiohttp/_http_parser.pyx":420 - * try: - * if pyparser._header_value is not None: - * if len(pyparser._header_value) + length > pyparser._max_field_size: # <<<<<<<<<<<<<< - * raise LineTooLong( - * 'Header value is too long', pyparser._max_field_size, - */ - } + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "aiohttp/_http_parser.pyx":419 - * cdef HttpParser pyparser = parser.data - * try: - * if pyparser._header_value is not None: # <<<<<<<<<<<<<< - * if len(pyparser._header_value) + length > pyparser._max_field_size: - * raise LineTooLong( +/* "aiohttp/_http_parser.pyx":459 + * pass + * + * cdef inline http_version(self): # <<<<<<<<<<<<<< + * cdef cparser.http_parser* parser = self._cparser + * */ - goto __pyx_L9; - } - /* "aiohttp/_http_parser.pyx":424 - * 'Header value is too long', pyparser._max_field_size, - * len(pyparser._header_value) + length) - * elif length > pyparser._max_field_size: # <<<<<<<<<<<<<< - * raise LineTooLong( - * 'Header value is too long', pyparser._max_field_size, length) - */ - __pyx_t_6 = ((__pyx_v_length > __pyx_v_pyparser->_max_field_size) != 0); - if (unlikely(__pyx_t_6)) { +static CYTHON_INLINE PyObject *__pyx_f_7aiohttp_12_http_parser_10HttpParser_http_version(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_self) { + struct http_parser *__pyx_v_parser; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + struct http_parser *__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; + __Pyx_RefNannySetupContext("http_version", 0); - /* "aiohttp/_http_parser.pyx":425 - * len(pyparser._header_value) + length) - * elif length > pyparser._max_field_size: - * raise LineTooLong( # <<<<<<<<<<<<<< - * 'Header value is too long', pyparser._max_field_size, length) - * pyparser._on_header_value( + /* "aiohttp/_http_parser.pyx":460 + * + * cdef inline http_version(self): + * cdef cparser.http_parser* parser = self._cparser # <<<<<<<<<<<<<< + * + * if parser.http_major == 1: */ - __pyx_t_8 = __Pyx_GetModuleGlobalName(__pyx_n_s_LineTooLong); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 425, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_8); - - /* "aiohttp/_http_parser.pyx":426 - * elif length > pyparser._max_field_size: - * raise LineTooLong( - * 'Header value is too long', pyparser._max_field_size, length) # <<<<<<<<<<<<<< - * pyparser._on_header_value( - * at[:length].decode('utf-8', 'surrogateescape'), at[:length]) - */ - __pyx_t_13 = __Pyx_PyInt_FromSize_t(__pyx_v_pyparser->_max_field_size); if (unlikely(!__pyx_t_13)) __PYX_ERR(0, 426, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_13); - __pyx_t_10 = __Pyx_PyInt_FromSize_t(__pyx_v_length); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 426, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_10); - __pyx_t_9 = NULL; - __pyx_t_12 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(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_12 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_8)) { - PyObject *__pyx_temp[4] = {__pyx_t_9, __pyx_kp_u_Header_value_is_too_long, __pyx_t_13, __pyx_t_10}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_8, __pyx_temp+1-__pyx_t_12, 3+__pyx_t_12); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 425, __pyx_L3_error) - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_8)) { - PyObject *__pyx_temp[4] = {__pyx_t_9, __pyx_kp_u_Header_value_is_too_long, __pyx_t_13, __pyx_t_10}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_8, __pyx_temp+1-__pyx_t_12, 3+__pyx_t_12); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 425, __pyx_L3_error) - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - } else - #endif - { - __pyx_t_11 = PyTuple_New(3+__pyx_t_12); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 425, __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_Header_value_is_too_long); - __Pyx_GIVEREF(__pyx_kp_u_Header_value_is_too_long); - PyTuple_SET_ITEM(__pyx_t_11, 0+__pyx_t_12, __pyx_kp_u_Header_value_is_too_long); - __Pyx_GIVEREF(__pyx_t_13); - PyTuple_SET_ITEM(__pyx_t_11, 1+__pyx_t_12, __pyx_t_13); - __Pyx_GIVEREF(__pyx_t_10); - PyTuple_SET_ITEM(__pyx_t_11, 2+__pyx_t_12, __pyx_t_10); - __pyx_t_13 = 0; - __pyx_t_10 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_t_11, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 425, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - } - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_Raise(__pyx_t_1, 0, 0, 0); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __PYX_ERR(0, 425, __pyx_L3_error) + __pyx_t_1 = __pyx_v_self->_cparser; + __pyx_v_parser = __pyx_t_1; - /* "aiohttp/_http_parser.pyx":424 - * 'Header value is too long', pyparser._max_field_size, - * len(pyparser._header_value) + length) - * elif length > pyparser._max_field_size: # <<<<<<<<<<<<<< - * raise LineTooLong( - * 'Header value is too long', pyparser._max_field_size, length) + /* "aiohttp/_http_parser.pyx":462 + * cdef cparser.http_parser* parser = self._cparser + * + * if parser.http_major == 1: # <<<<<<<<<<<<<< + * if parser.http_minor == 0: + * return HttpVersion10 */ - } - __pyx_L9:; + __pyx_t_2 = ((__pyx_v_parser->http_major == 1) != 0); + if (__pyx_t_2) { - /* "aiohttp/_http_parser.pyx":428 - * 'Header value is too long', pyparser._max_field_size, length) - * pyparser._on_header_value( - * at[:length].decode('utf-8', 'surrogateescape'), at[:length]) # <<<<<<<<<<<<<< - * except BaseException as ex: - * pyparser._last_error = ex + /* "aiohttp/_http_parser.pyx":463 + * + * if parser.http_major == 1: + * if parser.http_minor == 0: # <<<<<<<<<<<<<< + * return HttpVersion10 + * elif parser.http_minor == 1: */ - __pyx_t_1 = __Pyx_decode_c_string(__pyx_v_at, 0, __pyx_v_length, NULL, ((char const *)"surrogateescape"), PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 428, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_8 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_at + 0, __pyx_v_length - 0); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 428, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_8); + switch (__pyx_v_parser->http_minor) { + case 0: - /* "aiohttp/_http_parser.pyx":427 - * raise LineTooLong( - * 'Header value is too long', pyparser._max_field_size, length) - * pyparser._on_header_value( # <<<<<<<<<<<<<< - * at[:length].decode('utf-8', 'surrogateescape'), at[:length]) - * except BaseException as ex: + /* "aiohttp/_http_parser.pyx":464 + * if parser.http_major == 1: + * if parser.http_minor == 0: + * return HttpVersion10 # <<<<<<<<<<<<<< + * elif parser.http_minor == 1: + * return HttpVersion11 */ - __pyx_t_11 = ((struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser *)__pyx_v_pyparser->__pyx_vtab)->_on_header_value(__pyx_v_pyparser, ((PyObject*)__pyx_t_1), ((PyObject*)__pyx_t_8)); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 427, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __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":418 - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * if pyparser._header_value is not None: - * if len(pyparser._header_value) + length > pyparser._max_field_size: + /* "aiohttp/_http_parser.pyx":463 + * + * if parser.http_major == 1: + * if parser.http_minor == 0: # <<<<<<<<<<<<<< + * return HttpVersion10 + * elif parser.http_minor == 1: */ - } + break; + case 1: - /* "aiohttp/_http_parser.pyx":433 - * return -1 - * else: - * return 0 # <<<<<<<<<<<<<< + /* "aiohttp/_http_parser.pyx":466 + * 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":465 + * if parser.http_minor == 0: + * return HttpVersion10 + * elif parser.http_minor == 1: # <<<<<<<<<<<<<< + * return HttpVersion11 * */ - /*else:*/ { - __pyx_r = 0; - goto __pyx_L6_except_return; + break; + default: break; } - __pyx_L3_error:; - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_XDECREF(__pyx_t_13); __pyx_t_13 = 0; - __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; - /* "aiohttp/_http_parser.pyx":429 - * pyparser._on_header_value( - * at[:length].decode('utf-8', 'surrogateescape'), at[:length]) - * except BaseException as ex: # <<<<<<<<<<<<<< - * pyparser._last_error = ex - * return -1 + /* "aiohttp/_http_parser.pyx":462 + * cdef cparser.http_parser* parser = self._cparser + * + * if parser.http_major == 1: # <<<<<<<<<<<<<< + * if parser.http_minor == 0: + * return HttpVersion10 */ - __pyx_t_12 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_BaseException); - if (__pyx_t_12) { - __Pyx_AddTraceback("aiohttp._http_parser.cb_on_header_value", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_11, &__pyx_t_8, &__pyx_t_1) < 0) __PYX_ERR(0, 429, __pyx_L5_except_error) - __Pyx_GOTREF(__pyx_t_11); - __Pyx_GOTREF(__pyx_t_8); - __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_t_8); - __pyx_v_ex = __pyx_t_8; - /*try:*/ { + } - /* "aiohttp/_http_parser.pyx":430 - * at[:length].decode('utf-8', 'surrogateescape'), 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":431 - * 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_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; - goto __pyx_L15_return; - } - - /* "aiohttp/_http_parser.pyx":429 - * pyparser._on_header_value( - * at[:length].decode('utf-8', 'surrogateescape'), at[:length]) - * except BaseException as ex: # <<<<<<<<<<<<<< - * pyparser._last_error = ex - * return -1 + /* "aiohttp/_http_parser.pyx":468 + * return HttpVersion11 + * + * return HttpVersion(parser.http_major, parser.http_minor) # <<<<<<<<<<<<<< + * + * ### Public API ### */ - /*finally:*/ { - __pyx_L15_return: { - __pyx_t_12 = __pyx_r; - __Pyx_DECREF(__pyx_v_ex); - __pyx_v_ex = NULL; - __pyx_r = __pyx_t_12; - goto __pyx_L6_except_return; - } - } + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = __Pyx_PyInt_From_unsigned_short(__pyx_v_parser->http_major); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 468, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = __Pyx_PyInt_From_unsigned_short(__pyx_v_parser->http_minor); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 468, __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; } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; - - /* "aiohttp/_http_parser.pyx":418 - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * if pyparser._header_value is not None: - * if len(pyparser._header_value) + length > 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; } + #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, 468, __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, 468, __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, 468, __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, 468, __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":415 + /* "aiohttp/_http_parser.pyx":459 + * pass * + * cdef inline http_version(self): # <<<<<<<<<<<<<< + * cdef cparser.http_parser* parser = self._cparser * - * cdef int cb_on_header_value(cparser.http_parser* 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_8); + __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_XDECREF(__pyx_t_10); - __Pyx_XDECREF(__pyx_t_11); - __Pyx_XDECREF(__pyx_t_13); - __Pyx_AddTraceback("aiohttp._http_parser.cb_on_header_value", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = -1; + __Pyx_AddTraceback("aiohttp._http_parser.HttpParser.http_version", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; __pyx_L0:; - __Pyx_XDECREF((PyObject *)__pyx_v_pyparser); - __Pyx_XDECREF(__pyx_v_ex); + __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "aiohttp/_http_parser.pyx":436 +/* "aiohttp/_http_parser.pyx":472 + * ### Public API ### * + * def feed_eof(self): # <<<<<<<<<<<<<< + * cdef bytes desc * - * cdef int cb_on_headers_complete(cparser.http_parser* parser) except -1: # <<<<<<<<<<<<<< - * cdef HttpParser pyparser = parser.data - * try: */ -static int __pyx_f_7aiohttp_12_http_parser_cb_on_headers_complete(struct http_parser *__pyx_v_parser) { - struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_pyparser = 0; - PyObject *__pyx_v_exc = NULL; - int __pyx_r; +/* 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 - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; + __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; - int __pyx_t_5; - int __pyx_t_6; - int __pyx_t_7; - PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - __Pyx_RefNannySetupContext("cb_on_headers_complete", 0); + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + __Pyx_RefNannySetupContext("feed_eof", 0); - /* "aiohttp/_http_parser.pyx":437 + /* "aiohttp/_http_parser.pyx":475 + * cdef bytes desc * - * cdef int cb_on_headers_complete(cparser.http_parser* parser) except -1: - * cdef HttpParser pyparser = parser.data # <<<<<<<<<<<<<< - * try: - * pyparser._on_status_complete() + * if self._payload is not None: # <<<<<<<<<<<<<< + * if self._cparser.flags & cparser.F_CHUNKED: + * raise TransferEncodingError( */ - __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; + __pyx_t_1 = (__pyx_v_self->_payload != Py_None); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { - /* "aiohttp/_http_parser.pyx":438 - * cdef int cb_on_headers_complete(cparser.http_parser* parser) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * pyparser._on_status_complete() - * pyparser._on_headers_complete() + /* "aiohttp/_http_parser.pyx":476 + * + * if self._payload is not None: + * if self._cparser.flags & cparser.F_CHUNKED: # <<<<<<<<<<<<<< + * raise TransferEncodingError( + * "Not enough data for satisfy transfer length header.") */ - { - __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:*/ { + __pyx_t_2 = ((__pyx_v_self->_cparser->flags & F_CHUNKED) != 0); + if (unlikely(__pyx_t_2)) { - /* "aiohttp/_http_parser.pyx":439 - * cdef HttpParser pyparser = parser.data - * try: - * pyparser._on_status_complete() # <<<<<<<<<<<<<< - * pyparser._on_headers_complete() - * except BaseException as exc: + /* "aiohttp/_http_parser.pyx":477 + * 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_CONTENTLENGTH: */ - __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, 439, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_TransferEncodingError); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 477, __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, 477, __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, 477, __pyx_L1_error) - /* "aiohttp/_http_parser.pyx":440 - * try: - * pyparser._on_status_complete() - * pyparser._on_headers_complete() # <<<<<<<<<<<<<< - * except BaseException as exc: - * pyparser._last_error = exc + /* "aiohttp/_http_parser.pyx":476 + * + * 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_1 = ((struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser *)__pyx_v_pyparser->__pyx_vtab)->_on_headers_complete(__pyx_v_pyparser, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 440, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } - /* "aiohttp/_http_parser.pyx":438 - * cdef int cb_on_headers_complete(cparser.http_parser* parser) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * pyparser._on_status_complete() - * pyparser._on_headers_complete() + /* "aiohttp/_http_parser.pyx":479 + * raise TransferEncodingError( + * "Not enough data for satisfy transfer length header.") + * elif self._cparser.flags & cparser.F_CONTENTLENGTH: # <<<<<<<<<<<<<< + * raise ContentLengthError( + * "Not enough data for satisfy content length header.") */ - } + __pyx_t_2 = ((__pyx_v_self->_cparser->flags & F_CONTENTLENGTH) != 0); + if (unlikely(__pyx_t_2)) { - /* "aiohttp/_http_parser.pyx":445 - * return -1 - * else: - * if pyparser._cparser.upgrade or pyparser._cparser.method == 5: # CONNECT # <<<<<<<<<<<<<< - * return 2 - * else: + /* "aiohttp/_http_parser.pyx":480 + * "Not enough data for satisfy transfer length header.") + * elif self._cparser.flags & cparser.F_CONTENTLENGTH: + * raise ContentLengthError( # <<<<<<<<<<<<<< + * "Not enough data for satisfy content length header.") + * elif self._cparser.http_errno != cparser.HPE_OK: */ - /*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_GetModuleGlobalName(__pyx_t_4, __pyx_n_s_ContentLengthError); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 480, __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_6 = ((__pyx_v_pyparser->_cparser->method == 5) != 0); - __pyx_t_5 = __pyx_t_6; - __pyx_L10_bool_binop_done:; - if (__pyx_t_5) { + __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, 480, __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, 480, __pyx_L1_error) - /* "aiohttp/_http_parser.pyx":446 - * else: - * if pyparser._cparser.upgrade or pyparser._cparser.method == 5: # CONNECT - * return 2 # <<<<<<<<<<<<<< - * else: - * return 0 + /* "aiohttp/_http_parser.pyx":479 + * raise TransferEncodingError( + * "Not enough data for satisfy transfer length header.") + * elif self._cparser.flags & cparser.F_CONTENTLENGTH: # <<<<<<<<<<<<<< + * raise ContentLengthError( + * "Not enough data for satisfy content length header.") */ - __pyx_r = 2; - goto __pyx_L6_except_return; + } - /* "aiohttp/_http_parser.pyx":445 - * return -1 - * else: - * if pyparser._cparser.upgrade or pyparser._cparser.method == 5: # CONNECT # <<<<<<<<<<<<<< - * return 2 - * else: + /* "aiohttp/_http_parser.pyx":482 + * raise ContentLengthError( + * "Not enough data for satisfy content length header.") + * elif self._cparser.http_errno != cparser.HPE_OK: # <<<<<<<<<<<<<< + * desc = cparser.http_errno_description( + * self._cparser.http_errno) */ + __pyx_t_2 = ((__pyx_v_self->_cparser->http_errno != HPE_OK) != 0); + if (unlikely(__pyx_t_2)) { + + /* "aiohttp/_http_parser.pyx":483 + * "Not enough data for satisfy content length header.") + * elif self._cparser.http_errno != cparser.HPE_OK: + * desc = cparser.http_errno_description( # <<<<<<<<<<<<<< + * self._cparser.http_errno) + * raise PayloadEncodingError(desc.decode('latin-1')) + */ + __pyx_t_3 = __Pyx_PyBytes_FromString(http_errno_description(((enum http_errno)__pyx_v_self->_cparser->http_errno))); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 483, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_v_desc = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + + /* "aiohttp/_http_parser.pyx":485 + * desc = cparser.http_errno_description( + * self._cparser.http_errno) + * 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, 485, __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, 485, __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, 485, __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, 485, __pyx_L1_error) - /* "aiohttp/_http_parser.pyx":448 - * return 2 - * else: - * return 0 # <<<<<<<<<<<<<< - * - * + /* "aiohttp/_http_parser.pyx":482 + * raise ContentLengthError( + * "Not enough data for satisfy content length header.") + * elif self._cparser.http_errno != cparser.HPE_OK: # <<<<<<<<<<<<<< + * desc = cparser.http_errno_description( + * self._cparser.http_errno) */ - /*else*/ { - __pyx_r = 0; - goto __pyx_L6_except_return; + } + + /* "aiohttp/_http_parser.pyx":487 + * 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, 487, __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, 487, __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; } - __pyx_L3_error:; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "aiohttp/_http_parser.pyx":441 - * pyparser._on_status_complete() - * pyparser._on_headers_complete() - * except BaseException as exc: # <<<<<<<<<<<<<< - * pyparser._last_error = exc - * return -1 + /* "aiohttp/_http_parser.pyx":475 + * cdef bytes desc + * + * if self._payload is not None: # <<<<<<<<<<<<<< + * if self._cparser.flags & cparser.F_CHUNKED: + * raise TransferEncodingError( */ - __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, 441, __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:*/ { + goto __pyx_L3; + } - /* "aiohttp/_http_parser.pyx":442 - * pyparser._on_headers_complete() - * except BaseException as exc: - * pyparser._last_error = exc # <<<<<<<<<<<<<< - * return -1 - * else: + /* "aiohttp/_http_parser.pyx":488 + * else: + * self._payload.feed_eof() + * elif self._started: # <<<<<<<<<<<<<< + * self._on_headers_complete() + * if self._messages: */ - __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; + __pyx_t_2 = (__pyx_v_self->_started != 0); + if (__pyx_t_2) { - /* "aiohttp/_http_parser.pyx":443 - * except BaseException as exc: - * pyparser._last_error = exc - * return -1 # <<<<<<<<<<<<<< - * else: - * if pyparser._cparser.upgrade or pyparser._cparser.method == 5: # CONNECT + /* "aiohttp/_http_parser.pyx":489 + * self._payload.feed_eof() + * elif self._started: + * self._on_headers_complete() # <<<<<<<<<<<<<< + * if self._messages: + * return self._messages[-1][0] */ - __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; - } + __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, 489, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - /* "aiohttp/_http_parser.pyx":441 - * pyparser._on_status_complete() - * pyparser._on_headers_complete() - * except BaseException as exc: # <<<<<<<<<<<<<< - * pyparser._last_error = exc - * return -1 + /* "aiohttp/_http_parser.pyx":490 + * elif self._started: + * self._on_headers_complete() + * if self._messages: # <<<<<<<<<<<<<< + * return self._messages[-1][0] + * */ - /*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; - } + __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":491 + * 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, 491, __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, 491, __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, 491, __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":490 + * elif self._started: + * self._on_headers_complete() + * if self._messages: # <<<<<<<<<<<<<< + * return self._messages[-1][0] + * + */ } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; - /* "aiohttp/_http_parser.pyx":438 - * cdef int cb_on_headers_complete(cparser.http_parser* parser) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * pyparser._on_status_complete() - * pyparser._on_headers_complete() + /* "aiohttp/_http_parser.pyx":488 + * else: + * self._payload.feed_eof() + * elif self._started: # <<<<<<<<<<<<<< + * self._on_headers_complete() + * if self._messages: */ - __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; } + __pyx_L3:; - /* "aiohttp/_http_parser.pyx":436 + /* "aiohttp/_http_parser.pyx":472 + * ### Public API ### * + * def feed_eof(self): # <<<<<<<<<<<<<< + * cdef bytes desc * - * cdef int cb_on_headers_complete(cparser.http_parser* parser) except -1: # <<<<<<<<<<<<<< - * cdef HttpParser pyparser = parser.data - * try: */ /* 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_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_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((PyObject *)__pyx_v_pyparser); - __Pyx_XDECREF(__pyx_v_exc); + __Pyx_XDECREF(__pyx_v_desc); + __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "aiohttp/_http_parser.pyx":451 - * +/* "aiohttp/_http_parser.pyx":493 + * return self._messages[-1][0] * - * cdef int cb_on_body(cparser.http_parser* parser, # <<<<<<<<<<<<<< - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data + * def feed_data(self, data): # <<<<<<<<<<<<<< + * cdef: + * size_t data_len */ -static int __pyx_f_7aiohttp_12_http_parser_cb_on_body(struct http_parser *__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; +/* 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 - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; + __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; + 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; - 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; - PyObject *__pyx_t_16 = NULL; - int __pyx_t_17; - char const *__pyx_t_18; - 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; - __Pyx_RefNannySetupContext("cb_on_body", 0); + __Pyx_RefNannySetupContext("feed_data", 0); - /* "aiohttp/_http_parser.pyx":453 - * cdef int cb_on_body(cparser.http_parser* parser, - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data # <<<<<<<<<<<<<< - * cdef bytes body = at[:length] - * try: + /* "aiohttp/_http_parser.pyx":498 + * size_t nb + * + * PyObject_GetBuffer(data, &self.py_buf, PyBUF_SIMPLE) # <<<<<<<<<<<<<< + * data_len = self.py_buf.len + * */ - __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; + __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, 498, __pyx_L1_error) - /* "aiohttp/_http_parser.pyx":454 - * 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) + /* "aiohttp/_http_parser.pyx":499 + * + * PyObject_GetBuffer(data, &self.py_buf, PyBUF_SIMPLE) + * data_len = self.py_buf.len # <<<<<<<<<<<<<< + * + * nb = cparser.http_parser_execute( */ - __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_at + 0, __pyx_v_length - 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 454, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_body = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; + __pyx_v_data_len = ((size_t)__pyx_v_self->py_buf.len); - /* "aiohttp/_http_parser.pyx":455 - * 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":501 + * data_len = self.py_buf.len + * + * nb = cparser.http_parser_execute( # <<<<<<<<<<<<<< + * self._cparser, + * self._csettings, */ - { - __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:*/ { + __pyx_v_nb = http_parser_execute(__pyx_v_self->_cparser, __pyx_v_self->_csettings, ((char *)__pyx_v_self->py_buf.buf), __pyx_v_data_len); - /* "aiohttp/_http_parser.pyx":456 - * cdef bytes body = at[:length] - * try: - * pyparser._payload.feed_data(body, length) # <<<<<<<<<<<<<< - * except BaseException as exc: - * if pyparser._payload_exception is not None: + /* "aiohttp/_http_parser.pyx":507 + * data_len) + * + * PyBuffer_Release(&self.py_buf) # <<<<<<<<<<<<<< + * + * # i am not sure about cparser.HPE_INVALID_METHOD, */ - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_pyparser->_payload, __pyx_n_s_feed_data); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 456, __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, 456, __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, 456, __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, 456, __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, 456, __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, 456, __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; + PyBuffer_Release((&__pyx_v_self->py_buf)); - /* "aiohttp/_http_parser.pyx":455 - * 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":512 + * # seems get err for valid request + * # test_client_functional.py::test_post_data_with_bytesio_file + * if (self._cparser.http_errno != cparser.HPE_OK and # <<<<<<<<<<<<<< + * (self._cparser.http_errno != cparser.HPE_INVALID_METHOD or + * self._cparser.method == 0)): */ - } + __pyx_t_3 = ((__pyx_v_self->_cparser->http_errno != HPE_OK) != 0); + if (__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L4_bool_binop_done; + } - /* "aiohttp/_http_parser.pyx":465 - * return -1 - * else: - * return 0 # <<<<<<<<<<<<<< - * - * + /* "aiohttp/_http_parser.pyx":513 + * # test_client_functional.py::test_post_data_with_bytesio_file + * if (self._cparser.http_errno != cparser.HPE_OK and + * (self._cparser.http_errno != cparser.HPE_INVALID_METHOD or # <<<<<<<<<<<<<< + * self._cparser.method == 0)): + * if self._payload_error == 0: */ - /*else:*/ { - __pyx_r = 0; - goto __pyx_L6_except_return; - } - __pyx_L3_error:; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_3 = ((__pyx_v_self->_cparser->http_errno != HPE_INVALID_METHOD) != 0); + if (!__pyx_t_3) { + } else { + __pyx_t_2 = __pyx_t_3; + goto __pyx_L4_bool_binop_done; + } - /* "aiohttp/_http_parser.pyx":457 - * 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))) + /* "aiohttp/_http_parser.pyx":514 + * if (self._cparser.http_errno != cparser.HPE_OK and + * (self._cparser.http_errno != cparser.HPE_INVALID_METHOD or + * self._cparser.method == 0)): # <<<<<<<<<<<<<< + * if self._payload_error == 0: + * if self._last_error is not None: */ - __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, 457, __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:*/ { + __pyx_t_3 = ((__pyx_v_self->_cparser->method == 0) != 0); + __pyx_t_2 = __pyx_t_3; + __pyx_L4_bool_binop_done:; - /* "aiohttp/_http_parser.pyx":458 - * 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: + /* "aiohttp/_http_parser.pyx":512 + * # seems get err for valid request + * # test_client_functional.py::test_post_data_with_bytesio_file + * if (self._cparser.http_errno != cparser.HPE_OK and # <<<<<<<<<<<<<< + * (self._cparser.http_errno != cparser.HPE_INVALID_METHOD or + * self._cparser.method == 0)): */ - __pyx_t_10 = (__pyx_v_pyparser->_payload_exception != Py_None); - __pyx_t_11 = (__pyx_t_10 != 0); - if (__pyx_t_11) { + if (__pyx_t_2) { - /* "aiohttp/_http_parser.pyx":459 - * 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) + /* "aiohttp/_http_parser.pyx":515 + * (self._cparser.http_errno != cparser.HPE_INVALID_METHOD or + * self._cparser.method == 0)): + * if self._payload_error == 0: # <<<<<<<<<<<<<< + * if self._last_error is not None: + * ex = self._last_error */ - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_v_pyparser->_payload, __pyx_n_s_set_exception); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 459, __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, 459, __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); - } - } - if (!__pyx_t_15) { - __pyx_t_12 = __Pyx_PyObject_CallOneArg(__pyx_t_14, __pyx_t_13); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 459, __pyx_L14_error) - __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; - __Pyx_GOTREF(__pyx_t_12); - } else { - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_14)) { - PyObject *__pyx_temp[2] = {__pyx_t_15, __pyx_t_13}; - __pyx_t_12 = __Pyx_PyFunction_FastCall(__pyx_t_14, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 459, __pyx_L14_error) - __Pyx_XDECREF(__pyx_t_15); __pyx_t_15 = 0; - __Pyx_GOTREF(__pyx_t_12); - __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_14)) { - PyObject *__pyx_temp[2] = {__pyx_t_15, __pyx_t_13}; - __pyx_t_12 = __Pyx_PyCFunction_FastCall(__pyx_t_14, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 459, __pyx_L14_error) - __Pyx_XDECREF(__pyx_t_15); __pyx_t_15 = 0; - __Pyx_GOTREF(__pyx_t_12); - __Pyx_DECREF(__pyx_t_13); __pyx_t_13 = 0; - } else - #endif - { - __pyx_t_16 = PyTuple_New(1+1); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 459, __pyx_L14_error) - __Pyx_GOTREF(__pyx_t_16); - __Pyx_GIVEREF(__pyx_t_15); PyTuple_SET_ITEM(__pyx_t_16, 0, __pyx_t_15); __pyx_t_15 = NULL; - __Pyx_GIVEREF(__pyx_t_13); - PyTuple_SET_ITEM(__pyx_t_16, 0+1, __pyx_t_13); - __pyx_t_13 = 0; - __pyx_t_12 = __Pyx_PyObject_Call(__pyx_t_14, __pyx_t_16, NULL); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 459, __pyx_L14_error) - __Pyx_GOTREF(__pyx_t_12); - __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; - } - } - __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); - } - } - if (!__pyx_t_14) { - __pyx_t_6 = __Pyx_PyObject_CallOneArg(__pyx_t_7, __pyx_t_12); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 459, __pyx_L14_error) - __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; - __Pyx_GOTREF(__pyx_t_6); - } else { - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[2] = {__pyx_t_14, __pyx_t_12}; - __pyx_t_6 = __Pyx_PyFunction_FastCall(__pyx_t_7, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 459, __pyx_L14_error) - __Pyx_XDECREF(__pyx_t_14); __pyx_t_14 = 0; - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[2] = {__pyx_t_14, __pyx_t_12}; - __pyx_t_6 = __Pyx_PyCFunction_FastCall(__pyx_t_7, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 459, __pyx_L14_error) - __Pyx_XDECREF(__pyx_t_14); __pyx_t_14 = 0; - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; - } else - #endif - { - __pyx_t_16 = PyTuple_New(1+1); if (unlikely(!__pyx_t_16)) __PYX_ERR(0, 459, __pyx_L14_error) - __Pyx_GOTREF(__pyx_t_16); - __Pyx_GIVEREF(__pyx_t_14); PyTuple_SET_ITEM(__pyx_t_16, 0, __pyx_t_14); __pyx_t_14 = NULL; - __Pyx_GIVEREF(__pyx_t_12); - PyTuple_SET_ITEM(__pyx_t_16, 0+1, __pyx_t_12); - __pyx_t_12 = 0; - __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_16, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 459, __pyx_L14_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_16); __pyx_t_16 = 0; - } - } - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_2 = ((__pyx_v_self->_payload_error == 0) != 0); + if (__pyx_t_2) { - /* "aiohttp/_http_parser.pyx":458 - * 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: + /* "aiohttp/_http_parser.pyx":516 + * self._cparser.method == 0)): + * if self._payload_error == 0: + * if self._last_error is not None: # <<<<<<<<<<<<<< + * ex = self._last_error + * self._last_error = None */ - goto __pyx_L16; - } + __pyx_t_2 = (__pyx_v_self->_last_error != Py_None); + __pyx_t_3 = (__pyx_t_2 != 0); + if (__pyx_t_3) { - /* "aiohttp/_http_parser.pyx":461 - * pyparser._payload.set_exception(pyparser._payload_exception(str(exc))) - * else: - * pyparser._payload.set_exception(exc) # <<<<<<<<<<<<<< - * pyparser._payload_error = 1 - * return -1 + /* "aiohttp/_http_parser.pyx":517 + * if self._payload_error == 0: + * if self._last_error is not None: + * ex = self._last_error # <<<<<<<<<<<<<< + * self._last_error = None + * else: */ - /*else*/ { - __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_v_pyparser->_payload, __pyx_n_s_set_exception); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 461, __pyx_L14_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_16 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_7))) { - __pyx_t_16 = PyMethod_GET_SELF(__pyx_t_7); - if (likely(__pyx_t_16)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); - __Pyx_INCREF(__pyx_t_16); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_7, function); - } - } - if (!__pyx_t_16) { - __pyx_t_6 = __Pyx_PyObject_CallOneArg(__pyx_t_7, __pyx_v_exc); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 461, __pyx_L14_error) - __Pyx_GOTREF(__pyx_t_6); - } else { - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[2] = {__pyx_t_16, __pyx_v_exc}; - __pyx_t_6 = __Pyx_PyFunction_FastCall(__pyx_t_7, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 461, __pyx_L14_error) - __Pyx_XDECREF(__pyx_t_16); __pyx_t_16 = 0; - __Pyx_GOTREF(__pyx_t_6); - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_7)) { - PyObject *__pyx_temp[2] = {__pyx_t_16, __pyx_v_exc}; - __pyx_t_6 = __Pyx_PyCFunction_FastCall(__pyx_t_7, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 461, __pyx_L14_error) - __Pyx_XDECREF(__pyx_t_16); __pyx_t_16 = 0; - __Pyx_GOTREF(__pyx_t_6); - } else - #endif - { - __pyx_t_12 = PyTuple_New(1+1); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 461, __pyx_L14_error) - __Pyx_GOTREF(__pyx_t_12); - __Pyx_GIVEREF(__pyx_t_16); PyTuple_SET_ITEM(__pyx_t_12, 0, __pyx_t_16); __pyx_t_16 = NULL; - __Pyx_INCREF(__pyx_v_exc); - __Pyx_GIVEREF(__pyx_v_exc); - PyTuple_SET_ITEM(__pyx_t_12, 0+1, __pyx_v_exc); - __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_12, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 461, __pyx_L14_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; - } - } - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - } - __pyx_L16:; + __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":462 - * else: - * pyparser._payload.set_exception(exc) - * pyparser._payload_error = 1 # <<<<<<<<<<<<<< - * return -1 - * else: + /* "aiohttp/_http_parser.pyx":518 + * if self._last_error is not None: + * ex = self._last_error + * self._last_error = None # <<<<<<<<<<<<<< + * else: + * ex = parser_error_from_errno( */ - __pyx_v_pyparser->_payload_error = 1; + __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":463 - * pyparser._payload.set_exception(exc) - * pyparser._payload_error = 1 - * return -1 # <<<<<<<<<<<<<< - * else: - * return 0 + /* "aiohttp/_http_parser.pyx":516 + * self._cparser.method == 0)): + * if self._payload_error == 0: + * if self._last_error is not None: # <<<<<<<<<<<<<< + * ex = self._last_error + * self._last_error = None */ - __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; + goto __pyx_L8; } - /* "aiohttp/_http_parser.pyx":457 - * 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))) + /* "aiohttp/_http_parser.pyx":520 + * self._last_error = None + * else: + * ex = parser_error_from_errno( # <<<<<<<<<<<<<< + * self._cparser.http_errno) + * self._payload = None */ - /*finally:*/ { - __pyx_L14_error:; - /*exception exit:*/{ - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __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_XDECREF(__pyx_t_15); __pyx_t_15 = 0; - __Pyx_XDECREF(__pyx_t_13); __pyx_t_13 = 0; - __Pyx_XDECREF(__pyx_t_14); __pyx_t_14 = 0; - __Pyx_XDECREF(__pyx_t_16); __pyx_t_16 = 0; - __Pyx_XDECREF(__pyx_t_12); __pyx_t_12 = 0; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_22, &__pyx_t_23, &__pyx_t_24); - if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_19, &__pyx_t_20, &__pyx_t_21) < 0)) __Pyx_ErrFetch(&__pyx_t_19, &__pyx_t_20, &__pyx_t_21); - __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_XGOTREF(__pyx_t_24); - __pyx_t_8 = __pyx_lineno; __pyx_t_17 = __pyx_clineno; __pyx_t_18 = __pyx_filename; - { - __Pyx_DECREF(__pyx_v_exc); - __pyx_v_exc = NULL; - } - if (PY_MAJOR_VERSION >= 3) { - __Pyx_XGIVEREF(__pyx_t_22); - __Pyx_XGIVEREF(__pyx_t_23); - __Pyx_XGIVEREF(__pyx_t_24); - __Pyx_ExceptionReset(__pyx_t_22, __pyx_t_23, __pyx_t_24); - } - __Pyx_XGIVEREF(__pyx_t_19); - __Pyx_XGIVEREF(__pyx_t_20); - __Pyx_XGIVEREF(__pyx_t_21); - __Pyx_ErrRestore(__pyx_t_19, __pyx_t_20, __pyx_t_21); - __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_lineno = __pyx_t_8; __pyx_clineno = __pyx_t_17; __pyx_filename = __pyx_t_18; - goto __pyx_L5_except_error; - } - __pyx_L13_return: { - __pyx_t_17 = __pyx_r; - __Pyx_DECREF(__pyx_v_exc); - __pyx_v_exc = NULL; - __pyx_r = __pyx_t_17; - goto __pyx_L6_except_return; - } - } - } - goto __pyx_L5_except_error; - __pyx_L5_except_error:; + /*else*/ { - /* "aiohttp/_http_parser.pyx":455 - * 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":521 + * else: + * ex = parser_error_from_errno( + * self._cparser.http_errno) # <<<<<<<<<<<<<< + * self._payload = None + * raise ex */ - __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; - } + __pyx_t_4 = __pyx_f_7aiohttp_12_http_parser_parser_error_from_errno(((enum http_errno)__pyx_v_self->_cparser->http_errno)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 520, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_v_ex = __pyx_t_4; + __pyx_t_4 = 0; + } + __pyx_L8:; - /* "aiohttp/_http_parser.pyx":451 - * + /* "aiohttp/_http_parser.pyx":522 + * ex = parser_error_from_errno( + * self._cparser.http_errno) + * self._payload = None # <<<<<<<<<<<<<< + * raise ex * - * cdef int cb_on_body(cparser.http_parser* parser, # <<<<<<<<<<<<<< - * const char *at, size_t length) except -1: - * cdef HttpParser pyparser = parser.data */ + __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; - /* 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_XDECREF(__pyx_t_16); - __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":468 - * + /* "aiohttp/_http_parser.pyx":523 + * self._cparser.http_errno) + * self._payload = None + * raise ex # <<<<<<<<<<<<<< * - * cdef int cb_on_message_complete(cparser.http_parser* parser) except -1: # <<<<<<<<<<<<<< - * cdef HttpParser pyparser = parser.data - * try: + * if self._messages: */ + __Pyx_Raise(__pyx_v_ex, 0, 0, 0); + __PYX_ERR(0, 523, __pyx_L1_error) -static int __pyx_f_7aiohttp_12_http_parser_cb_on_message_complete(struct http_parser *__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; - __Pyx_RefNannySetupContext("cb_on_message_complete", 0); + /* "aiohttp/_http_parser.pyx":515 + * (self._cparser.http_errno != cparser.HPE_INVALID_METHOD or + * self._cparser.method == 0)): + * if self._payload_error == 0: # <<<<<<<<<<<<<< + * if self._last_error is not None: + * ex = self._last_error + */ + } - /* "aiohttp/_http_parser.pyx":469 - * - * cdef int cb_on_message_complete(cparser.http_parser* 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":470 - * cdef int cb_on_message_complete(cparser.http_parser* parser) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * pyparser._started = False - * pyparser._on_message_complete() + /* "aiohttp/_http_parser.pyx":512 + * # seems get err for valid request + * # test_client_functional.py::test_post_data_with_bytesio_file + * if (self._cparser.http_errno != cparser.HPE_OK and # <<<<<<<<<<<<<< + * (self._cparser.http_errno != cparser.HPE_INVALID_METHOD or + * self._cparser.method == 0)): */ - { - __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":471 - * cdef HttpParser pyparser = parser.data - * try: - * pyparser._started = False # <<<<<<<<<<<<<< - * pyparser._on_message_complete() - * except BaseException as exc: + /* "aiohttp/_http_parser.pyx":525 + * raise ex + * + * if self._messages: # <<<<<<<<<<<<<< + * messages = self._messages + * self._messages = [] */ - __pyx_v_pyparser->_started = 0; + __pyx_t_3 = (__pyx_v_self->_messages != Py_None)&&(PyList_GET_SIZE(__pyx_v_self->_messages) != 0); + if (__pyx_t_3) { - /* "aiohttp/_http_parser.pyx":472 - * try: - * pyparser._started = False - * pyparser._on_message_complete() # <<<<<<<<<<<<<< - * except BaseException as exc: - * pyparser._last_error = exc + /* "aiohttp/_http_parser.pyx":526 + * + * if self._messages: + * messages = self._messages # <<<<<<<<<<<<<< + * self._messages = [] + * else: */ - __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, 472, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __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":470 - * cdef int cb_on_message_complete(cparser.http_parser* parser) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * pyparser._started = False - * pyparser._on_message_complete() + /* "aiohttp/_http_parser.pyx":527 + * if self._messages: + * messages = self._messages + * self._messages = [] # <<<<<<<<<<<<<< + * else: + * messages = () */ - } + __pyx_t_4 = PyList_New(0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 527, __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":477 - * return -1 - * else: - * return 0 # <<<<<<<<<<<<<< - * + /* "aiohttp/_http_parser.pyx":525 + * raise ex * + * if self._messages: # <<<<<<<<<<<<<< + * messages = self._messages + * self._messages = [] */ - /*else:*/ { - __pyx_r = 0; - goto __pyx_L6_except_return; - } - __pyx_L3_error:; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + goto __pyx_L9; + } - /* "aiohttp/_http_parser.pyx":473 - * pyparser._started = False - * pyparser._on_message_complete() - * except BaseException as exc: # <<<<<<<<<<<<<< - * pyparser._last_error = exc - * return -1 + /* "aiohttp/_http_parser.pyx":529 + * self._messages = [] + * else: + * messages = () # <<<<<<<<<<<<<< + * + * if self._upgraded: */ - __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, 473, __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:*/ { + /*else*/ { + __Pyx_INCREF(__pyx_empty_tuple); + __pyx_v_messages = __pyx_empty_tuple; + } + __pyx_L9:; - /* "aiohttp/_http_parser.pyx":474 - * pyparser._on_message_complete() - * except BaseException as exc: - * pyparser._last_error = exc # <<<<<<<<<<<<<< - * return -1 - * else: + /* "aiohttp/_http_parser.pyx":531 + * messages = () + * + * if self._upgraded: # <<<<<<<<<<<<<< + * return messages, True, data[nb:] + * 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; + __pyx_t_3 = (__pyx_v_self->_upgraded != 0); + if (__pyx_t_3) { - /* "aiohttp/_http_parser.pyx":475 - * except BaseException as exc: - * pyparser._last_error = exc - * return -1 # <<<<<<<<<<<<<< - * else: - * return 0 + /* "aiohttp/_http_parser.pyx":532 + * + * if self._upgraded: + * return messages, True, data[nb:] # <<<<<<<<<<<<<< + * else: + * return messages, False, b'' */ - __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; - } + __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, 532, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 532, __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":473 - * pyparser._started = False - * pyparser._on_message_complete() - * except BaseException as exc: # <<<<<<<<<<<<<< - * pyparser._last_error = exc - * return -1 + /* "aiohttp/_http_parser.pyx":531 + * messages = () + * + * if self._upgraded: # <<<<<<<<<<<<<< + * return messages, True, data[nb:] + * else: */ - /*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":470 - * cdef int cb_on_message_complete(cparser.http_parser* parser) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * pyparser._started = False - * pyparser._on_message_complete() + /* "aiohttp/_http_parser.pyx":534 + * return messages, True, data[nb:] + * else: + * return messages, False, b'' # <<<<<<<<<<<<<< + * + * */ - __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); + /*else*/ { + __Pyx_XDECREF(__pyx_r); + __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 534, __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":468 - * + /* "aiohttp/_http_parser.pyx":493 + * return self._messages[-1][0] * - * cdef int cb_on_message_complete(cparser.http_parser* parser) except -1: # <<<<<<<<<<<<<< - * cdef HttpParser pyparser = parser.data - * try: + * def feed_data(self, data): # <<<<<<<<<<<<<< + * cdef: + * size_t data_len */ /* 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_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((PyObject *)__pyx_v_pyparser); - __Pyx_XDECREF(__pyx_v_exc); + __Pyx_XDECREF(__pyx_v_ex); + __Pyx_XDECREF(__pyx_v_messages); + __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "aiohttp/_http_parser.pyx":480 - * - * - * cdef int cb_on_chunk_header(cparser.http_parser* parser) except -1: # <<<<<<<<<<<<<< - * cdef HttpParser pyparser = parser.data - * try: +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): */ -static int __pyx_f_7aiohttp_12_http_parser_cb_on_chunk_header(struct http_parser *__pyx_v_parser) { - struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_pyparser = 0; - PyObject *__pyx_v_exc = NULL; - int __pyx_r; +/* Python wrapper */ +static PyObject *__pyx_pw_7aiohttp_12_http_parser_10HttpParser_9__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw_7aiohttp_12_http_parser_10HttpParser_9__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; __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; - __Pyx_RefNannySetupContext("cb_on_chunk_header", 0); + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + __pyx_r = __pyx_pf_7aiohttp_12_http_parser_10HttpParser_8__reduce_cython__(((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)__pyx_v_self)); - /* "aiohttp/_http_parser.pyx":481 - * - * cdef int cb_on_chunk_header(cparser.http_parser* 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; + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "aiohttp/_http_parser.pyx":482 - * cdef int cb_on_chunk_header(cparser.http_parser* 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:*/ { +static PyObject *__pyx_pf_7aiohttp_12_http_parser_10HttpParser_8__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; + __Pyx_RefNannySetupContext("__reduce_cython__", 0); - /* "aiohttp/_http_parser.pyx":483 - * cdef HttpParser pyparser = parser.data - * try: - * pyparser._on_chunk_header() # <<<<<<<<<<<<<< - * except BaseException as exc: - * pyparser._last_error = exc + /* "(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 = ((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, 483, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __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) - /* "aiohttp/_http_parser.pyx":482 - * cdef int cb_on_chunk_header(cparser.http_parser* parser) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * pyparser._on_chunk_header() - * except BaseException as exc: + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): */ - } - /* "aiohttp/_http_parser.pyx":488 - * 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; + /* 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; +} - /* "aiohttp/_http_parser.pyx":484 - * try: - * pyparser._on_chunk_header() - * except BaseException as exc: # <<<<<<<<<<<<<< - * pyparser._last_error = exc - * return -1 +/* "(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__") */ - __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, 484, __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":485 - * 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; +/* Python wrapper */ +static PyObject *__pyx_pw_7aiohttp_12_http_parser_10HttpParser_11__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ +static PyObject *__pyx_pw_7aiohttp_12_http_parser_10HttpParser_11__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_10__setstate_cython__(((struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); - /* "aiohttp/_http_parser.pyx":486 - * 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; - } + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "aiohttp/_http_parser.pyx":484 - * 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:; +static PyObject *__pyx_pf_7aiohttp_12_http_parser_10HttpParser_10__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; + __Pyx_RefNannySetupContext("__setstate_cython__", 0); - /* "aiohttp/_http_parser.pyx":482 - * cdef int cb_on_chunk_header(cparser.http_parser* parser) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * pyparser._on_chunk_header() - * except BaseException as exc: + /* "(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_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; - } + __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) - /* "aiohttp/_http_parser.pyx":480 - * - * - * cdef int cb_on_chunk_header(cparser.http_parser* parser) except -1: # <<<<<<<<<<<<<< - * cdef HttpParser pyparser = parser.data - * try: + /* "(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_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_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":491 - * +/* "aiohttp/_http_parser.pyx":539 + * cdef class HttpRequestParser(HttpParser): * - * cdef int cb_on_chunk_complete(cparser.http_parser* parser) except -1: # <<<<<<<<<<<<<< - * cdef HttpParser pyparser = parser.data - * try: + * def __init__(self, protocol, loop, timer=None, # <<<<<<<<<<<<<< + * size_t max_line_size=8190, size_t max_headers=32768, + * size_t max_field_size=8190, payload_exception=None, */ -static int __pyx_f_7aiohttp_12_http_parser_cb_on_chunk_complete(struct http_parser *__pyx_v_parser) { - struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *__pyx_v_pyparser = 0; - PyObject *__pyx_v_exc = NULL; +/* 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; + 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; + CYTHON_UNUSED int __pyx_v_read_until_eof; 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; - __Pyx_RefNannySetupContext("cb_on_chunk_complete", 0); + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); + { + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_protocol,&__pyx_n_s_loop,&__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,0}; + PyObject* values[9] = {0,0,0,0,0,0,0,0,0}; + values[2] = ((PyObject *)Py_None); - /* "aiohttp/_http_parser.pyx":492 - * - * cdef int cb_on_chunk_complete(cparser.http_parser* parser) except -1: - * cdef HttpParser pyparser = parser.data # <<<<<<<<<<<<<< - * try: - * pyparser._on_chunk_complete() + /* "aiohttp/_http_parser.pyx":541 + * def __init__(self, protocol, loop, 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): + * self._init(cparser.HTTP_REQUEST, protocol, loop, timer, */ - __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":493 - * cdef int cb_on_chunk_complete(cparser.http_parser* 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":494 - * 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, 494, __pyx_L3_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + values[6] = ((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 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, 2, 9, 1); __PYX_ERR(0, 539, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 2: + if (kw_args > 0) { + PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_timer); + if (value) { values[2] = value; kw_args--; } + } + CYTHON_FALLTHROUGH; + case 3: + if (kw_args > 0) { + PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_max_line_size); + 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_headers); + 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_field_size); + 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_payload_exception); + 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_response_with_body); + 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_read_until_eof); + if (value) { values[8] = 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, 539, __pyx_L3_error) + } + } else { + switch (PyTuple_GET_SIZE(__pyx_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); + 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_timer = values[2]; + if (values[3]) { + __pyx_v_max_line_size = __Pyx_PyInt_As_size_t(values[3]); if (unlikely((__pyx_v_max_line_size == (size_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 540, __pyx_L3_error) + } else { + __pyx_v_max_line_size = ((size_t)0x1FFE); + } + if (values[4]) { + __pyx_v_max_headers = __Pyx_PyInt_As_size_t(values[4]); if (unlikely((__pyx_v_max_headers == (size_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 540, __pyx_L3_error) + } else { + __pyx_v_max_headers = ((size_t)0x8000); + } + if (values[5]) { + __pyx_v_max_field_size = __Pyx_PyInt_As_size_t(values[5]); if (unlikely((__pyx_v_max_field_size == (size_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 541, __pyx_L3_error) + } else { + __pyx_v_max_field_size = ((size_t)0x1FFE); + } + __pyx_v_payload_exception = values[6]; + if (values[7]) { + __pyx_v_response_with_body = __Pyx_PyObject_IsTrue(values[7]); if (unlikely((__pyx_v_response_with_body == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 542, __pyx_L3_error) + } else { - /* "aiohttp/_http_parser.pyx":493 - * cdef int cb_on_chunk_complete(cparser.http_parser* parser) except -1: - * cdef HttpParser pyparser = parser.data - * try: # <<<<<<<<<<<<<< - * pyparser._on_chunk_complete() - * except BaseException as exc: + /* "aiohttp/_http_parser.pyx":542 + * 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): # <<<<<<<<<<<<<< + * self._init(cparser.HTTP_REQUEST, protocol, loop, timer, + * max_line_size, max_headers, max_field_size, */ + __pyx_v_response_with_body = ((int)1); + } + if (values[8]) { + __pyx_v_read_until_eof = __Pyx_PyObject_IsTrue(values[8]); if (unlikely((__pyx_v_read_until_eof == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 542, __pyx_L3_error) + } else { + __pyx_v_read_until_eof = ((int)0); } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 0, 2, 9, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 539, __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_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); - /* "aiohttp/_http_parser.pyx":499 - * return -1 - * else: - * return 0 # <<<<<<<<<<<<<< - * + /* "aiohttp/_http_parser.pyx":539 + * cdef class HttpRequestParser(HttpParser): * + * def __init__(self, protocol, loop, timer=None, # <<<<<<<<<<<<<< + * size_t max_line_size=8190, size_t max_headers=32768, + * size_t max_field_size=8190, payload_exception=None, */ - /*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":495 - * try: - * pyparser._on_chunk_complete() - * except BaseException as exc: # <<<<<<<<<<<<<< - * pyparser._last_error = exc - * return -1 + /* 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, 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, CYTHON_UNUSED int __pyx_v_read_until_eof) { + int __pyx_r; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + struct __pyx_opt_args_7aiohttp_12_http_parser_10HttpParser__init __pyx_t_2; + __Pyx_RefNannySetupContext("__init__", 0); + + /* "aiohttp/_http_parser.pyx":543 + * size_t max_field_size=8190, payload_exception=None, + * bint response_with_body=True, bint read_until_eof=False): + * self._init(cparser.HTTP_REQUEST, protocol, loop, timer, # <<<<<<<<<<<<<< + * max_line_size, max_headers, max_field_size, + * payload_exception, response_with_body) */ - __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, 495, __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:*/ { + __pyx_t_2.__pyx_n = 6; + __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_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_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 543, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "aiohttp/_http_parser.pyx":496 - * pyparser._on_chunk_complete() - * except BaseException as exc: - * pyparser._last_error = exc # <<<<<<<<<<<<<< - * return -1 - * else: + /* "aiohttp/_http_parser.pyx":539 + * cdef class HttpRequestParser(HttpParser): + * + * def __init__(self, protocol, loop, timer=None, # <<<<<<<<<<<<<< + * size_t max_line_size=8190, size_t max_headers=32768, + * size_t max_field_size=8190, payload_exception=None, */ - __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":497 - * except BaseException as exc: - * pyparser._last_error = exc - * return -1 # <<<<<<<<<<<<<< - * else: - * return 0 + /* 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":547 + * payload_exception, response_with_body) + * + * cdef object _on_status_complete(self): # <<<<<<<<<<<<<< + * cdef Py_buffer py_buf + * if not self._buf: */ - __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":495 - * 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":493 - * cdef int cb_on_chunk_complete(cparser.http_parser* 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":491 - * - * - * cdef int cb_on_chunk_complete(cparser.http_parser* 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":502 - * - * - * cdef parser_error_from_errno(cparser.http_errno errno): # <<<<<<<<<<<<<< - * cdef bytes desc = cparser.http_errno_description(errno) - * - */ - -static PyObject *__pyx_f_7aiohttp_12_http_parser_parser_error_from_errno(enum http_errno __pyx_v_errno) { - PyObject *__pyx_v_desc = 0; - PyObject *__pyx_v_cls = NULL; +static PyObject *__pyx_f_7aiohttp_12_http_parser_17HttpRequestParser__on_status_complete(struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParser *__pyx_v_self) { + Py_buffer __pyx_v_py_buf; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; + int __pyx_t_1; + int __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; - __Pyx_RefNannySetupContext("parser_error_from_errno", 0); + int __pyx_t_6; + int __pyx_t_7; + char const *__pyx_t_8; + 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; + __Pyx_RefNannySetupContext("_on_status_complete", 0); - /* "aiohttp/_http_parser.pyx":503 - * - * cdef parser_error_from_errno(cparser.http_errno errno): - * cdef bytes desc = cparser.http_errno_description(errno) # <<<<<<<<<<<<<< - * - * if errno in (cparser.HPE_CB_message_begin, + /* "aiohttp/_http_parser.pyx":549 + * cdef object _on_status_complete(self): + * cdef Py_buffer py_buf + * if not self._buf: # <<<<<<<<<<<<<< + * return + * self._path = self._buf.decode('utf-8', 'surrogateescape') */ - __pyx_t_1 = __Pyx_PyBytes_FromString(http_errno_description(__pyx_v_errno)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 503, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_desc = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; + __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":505 - * cdef bytes desc = cparser.http_errno_description(errno) - * - * if errno in (cparser.HPE_CB_message_begin, # <<<<<<<<<<<<<< - * cparser.HPE_CB_url, - * cparser.HPE_CB_header_field, + /* "aiohttp/_http_parser.pyx":550 + * cdef Py_buffer py_buf + * if not self._buf: + * return # <<<<<<<<<<<<<< + * self._path = self._buf.decode('utf-8', 'surrogateescape') + * if self._cparser.method == 5: # CONNECT */ - switch (__pyx_v_errno) { - case HPE_CB_message_begin: + __Pyx_XDECREF(__pyx_r); + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; - /* "aiohttp/_http_parser.pyx":506 - * - * if errno in (cparser.HPE_CB_message_begin, - * cparser.HPE_CB_url, # <<<<<<<<<<<<<< - * cparser.HPE_CB_header_field, - * cparser.HPE_CB_header_value, + /* "aiohttp/_http_parser.pyx":549 + * cdef object _on_status_complete(self): + * cdef Py_buffer py_buf + * if not self._buf: # <<<<<<<<<<<<<< + * return + * self._path = self._buf.decode('utf-8', 'surrogateescape') */ - case HPE_CB_url: + } - /* "aiohttp/_http_parser.pyx":507 - * if errno in (cparser.HPE_CB_message_begin, - * cparser.HPE_CB_url, - * cparser.HPE_CB_header_field, # <<<<<<<<<<<<<< - * cparser.HPE_CB_header_value, - * cparser.HPE_CB_headers_complete, + /* "aiohttp/_http_parser.pyx":551 + * if not self._buf: + * return + * self._path = self._buf.decode('utf-8', 'surrogateescape') # <<<<<<<<<<<<<< + * if self._cparser.method == 5: # CONNECT + * self._url = URL(self._path) */ - case HPE_CB_header_field: + if (unlikely(__pyx_v_self->__pyx_base._buf == Py_None)) { + PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "decode"); + __PYX_ERR(0, 551, __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, 551, __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":508 - * cparser.HPE_CB_url, - * cparser.HPE_CB_header_field, - * cparser.HPE_CB_header_value, # <<<<<<<<<<<<<< - * cparser.HPE_CB_headers_complete, - * cparser.HPE_CB_body, + /* "aiohttp/_http_parser.pyx":552 + * return + * self._path = self._buf.decode('utf-8', 'surrogateescape') + * if self._cparser.method == 5: # CONNECT # <<<<<<<<<<<<<< + * self._url = URL(self._path) + * else: */ - case HPE_CB_header_value: + __pyx_t_2 = ((__pyx_v_self->__pyx_base._cparser->method == 5) != 0); + if (__pyx_t_2) { - /* "aiohttp/_http_parser.pyx":509 - * cparser.HPE_CB_header_field, - * cparser.HPE_CB_header_value, - * cparser.HPE_CB_headers_complete, # <<<<<<<<<<<<<< - * cparser.HPE_CB_body, - * cparser.HPE_CB_message_complete, + /* "aiohttp/_http_parser.pyx":553 + * self._path = self._buf.decode('utf-8', 'surrogateescape') + * if self._cparser.method == 5: # CONNECT + * self._url = URL(self._path) # <<<<<<<<<<<<<< + * else: + * PyObject_GetBuffer(self._buf, &py_buf, PyBUF_SIMPLE) */ - case HPE_CB_headers_complete: + __Pyx_INCREF(__pyx_v_7aiohttp_12_http_parser_URL); + __pyx_t_4 = __pyx_v_7aiohttp_12_http_parser_URL; __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_v_self->__pyx_base._path) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_v_self->__pyx_base._path); + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 553, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_GOTREF(__pyx_v_self->__pyx_base._url); + __Pyx_DECREF(__pyx_v_self->__pyx_base._url); + __pyx_v_self->__pyx_base._url = __pyx_t_3; + __pyx_t_3 = 0; - /* "aiohttp/_http_parser.pyx":510 - * cparser.HPE_CB_header_value, - * cparser.HPE_CB_headers_complete, - * cparser.HPE_CB_body, # <<<<<<<<<<<<<< - * cparser.HPE_CB_message_complete, - * cparser.HPE_CB_status, + /* "aiohttp/_http_parser.pyx":552 + * return + * self._path = self._buf.decode('utf-8', 'surrogateescape') + * if self._cparser.method == 5: # CONNECT # <<<<<<<<<<<<<< + * self._url = URL(self._path) + * else: */ - case HPE_CB_body: + goto __pyx_L4; + } - /* "aiohttp/_http_parser.pyx":511 - * cparser.HPE_CB_headers_complete, - * cparser.HPE_CB_body, - * cparser.HPE_CB_message_complete, # <<<<<<<<<<<<<< - * cparser.HPE_CB_status, - * cparser.HPE_CB_chunk_header, + /* "aiohttp/_http_parser.pyx":555 + * self._url = URL(self._path) + * else: + * PyObject_GetBuffer(self._buf, &py_buf, PyBUF_SIMPLE) # <<<<<<<<<<<<<< + * try: + * self._url = _parse_url(py_buf.buf, */ - case HPE_CB_message_complete: + /*else*/ { + __pyx_t_3 = __pyx_v_self->__pyx_base._buf; + __Pyx_INCREF(__pyx_t_3); + __pyx_t_6 = PyObject_GetBuffer(__pyx_t_3, (&__pyx_v_py_buf), PyBUF_SIMPLE); if (unlikely(__pyx_t_6 == ((int)-1))) __PYX_ERR(0, 555, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - /* "aiohttp/_http_parser.pyx":512 - * cparser.HPE_CB_body, - * cparser.HPE_CB_message_complete, - * cparser.HPE_CB_status, # <<<<<<<<<<<<<< - * cparser.HPE_CB_chunk_header, - * cparser.HPE_CB_chunk_complete): + /* "aiohttp/_http_parser.pyx":556 + * else: + * PyObject_GetBuffer(self._buf, &py_buf, PyBUF_SIMPLE) + * try: # <<<<<<<<<<<<<< + * self._url = _parse_url(py_buf.buf, + * py_buf.len) */ - case HPE_CB_status: + /*try:*/ { - /* "aiohttp/_http_parser.pyx":513 - * cparser.HPE_CB_message_complete, - * cparser.HPE_CB_status, - * cparser.HPE_CB_chunk_header, # <<<<<<<<<<<<<< - * cparser.HPE_CB_chunk_complete): - * cls = BadHttpMessage + /* "aiohttp/_http_parser.pyx":557 + * PyObject_GetBuffer(self._buf, &py_buf, PyBUF_SIMPLE) + * try: + * self._url = _parse_url(py_buf.buf, # <<<<<<<<<<<<<< + * py_buf.len) + * finally: */ - case HPE_CB_chunk_header: + __pyx_t_3 = __pyx_f_7aiohttp_12_http_parser__parse_url(((char *)__pyx_v_py_buf.buf), __pyx_v_py_buf.len); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 557, __pyx_L6_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_3); + __Pyx_GOTREF(__pyx_v_self->__pyx_base._url); + __Pyx_DECREF(__pyx_v_self->__pyx_base._url); + __pyx_v_self->__pyx_base._url = __pyx_t_3; + __pyx_t_3 = 0; + } - /* "aiohttp/_http_parser.pyx":514 - * cparser.HPE_CB_status, - * cparser.HPE_CB_chunk_header, - * cparser.HPE_CB_chunk_complete): # <<<<<<<<<<<<<< - * cls = BadHttpMessage - * - */ - case HPE_CB_chunk_complete: - - /* "aiohttp/_http_parser.pyx":515 - * cparser.HPE_CB_chunk_header, - * cparser.HPE_CB_chunk_complete): - * cls = BadHttpMessage # <<<<<<<<<<<<<< - * - * elif errno == cparser.HPE_INVALID_STATUS: - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_BadHttpMessage); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 515, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_cls = __pyx_t_1; - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":505 - * cdef bytes desc = cparser.http_errno_description(errno) - * - * if errno in (cparser.HPE_CB_message_begin, # <<<<<<<<<<<<<< - * cparser.HPE_CB_url, - * cparser.HPE_CB_header_field, - */ - break; - - /* "aiohttp/_http_parser.pyx":517 - * cls = BadHttpMessage - * - * elif errno == cparser.HPE_INVALID_STATUS: # <<<<<<<<<<<<<< - * cls = BadStatusLine - * - */ - case HPE_INVALID_STATUS: - - /* "aiohttp/_http_parser.pyx":518 - * - * elif errno == cparser.HPE_INVALID_STATUS: - * cls = BadStatusLine # <<<<<<<<<<<<<< - * - * elif errno == cparser.HPE_INVALID_METHOD: - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_BadStatusLine); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 518, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_cls = __pyx_t_1; - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":517 - * cls = BadHttpMessage - * - * elif errno == cparser.HPE_INVALID_STATUS: # <<<<<<<<<<<<<< - * cls = BadStatusLine - * - */ - break; - - /* "aiohttp/_http_parser.pyx":520 - * cls = BadStatusLine - * - * elif errno == cparser.HPE_INVALID_METHOD: # <<<<<<<<<<<<<< - * cls = BadStatusLine - * - */ - case HPE_INVALID_METHOD: - - /* "aiohttp/_http_parser.pyx":521 - * - * elif errno == cparser.HPE_INVALID_METHOD: - * cls = BadStatusLine # <<<<<<<<<<<<<< - * - * elif errno == cparser.HPE_INVALID_URL: - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_BadStatusLine); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 521, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_cls = __pyx_t_1; - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":520 - * cls = BadStatusLine - * - * elif errno == cparser.HPE_INVALID_METHOD: # <<<<<<<<<<<<<< - * cls = BadStatusLine - * - */ - break; - - /* "aiohttp/_http_parser.pyx":523 - * cls = BadStatusLine - * - * elif errno == cparser.HPE_INVALID_URL: # <<<<<<<<<<<<<< - * cls = InvalidURLError - * - */ - case HPE_INVALID_URL: - - /* "aiohttp/_http_parser.pyx":524 - * - * elif errno == cparser.HPE_INVALID_URL: - * cls = InvalidURLError # <<<<<<<<<<<<<< - * - * else: - */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_InvalidURLError); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 524, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_cls = __pyx_t_1; - __pyx_t_1 = 0; - - /* "aiohttp/_http_parser.pyx":523 - * cls = BadStatusLine - * - * elif errno == cparser.HPE_INVALID_URL: # <<<<<<<<<<<<<< - * cls = InvalidURLError - * - */ - break; - default: - - /* "aiohttp/_http_parser.pyx":527 - * - * else: - * cls = BadHttpMessage # <<<<<<<<<<<<<< + /* "aiohttp/_http_parser.pyx":560 + * py_buf.len) + * finally: + * PyBuffer_Release(&py_buf) # <<<<<<<<<<<<<< + * PyByteArray_Resize(self._buf, 0) * - * return cls(desc.decode('latin-1')) */ - __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_BadHttpMessage); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 527, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_cls = __pyx_t_1; - __pyx_t_1 = 0; - break; + /*finally:*/ { + /*normal exit:*/{ + PyBuffer_Release((&__pyx_v_py_buf)); + goto __pyx_L7; + } + __pyx_L6_error:; + /*exception exit:*/{ + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __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_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_12, &__pyx_t_13, &__pyx_t_14); + if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11) < 0)) __Pyx_ErrFetch(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); + __Pyx_XGOTREF(__pyx_t_9); + __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_t_6 = __pyx_lineno; __pyx_t_7 = __pyx_clineno; __pyx_t_8 = __pyx_filename; + { + PyBuffer_Release((&__pyx_v_py_buf)); + } + if (PY_MAJOR_VERSION >= 3) { + __Pyx_XGIVEREF(__pyx_t_12); + __Pyx_XGIVEREF(__pyx_t_13); + __Pyx_XGIVEREF(__pyx_t_14); + __Pyx_ExceptionReset(__pyx_t_12, __pyx_t_13, __pyx_t_14); + } + __Pyx_XGIVEREF(__pyx_t_9); + __Pyx_XGIVEREF(__pyx_t_10); + __Pyx_XGIVEREF(__pyx_t_11); + __Pyx_ErrRestore(__pyx_t_9, __pyx_t_10, __pyx_t_11); + __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_lineno = __pyx_t_6; __pyx_clineno = __pyx_t_7; __pyx_filename = __pyx_t_8; + goto __pyx_L1_error; + } + __pyx_L7:; + } } + __pyx_L4:; - /* "aiohttp/_http_parser.pyx":529 - * cls = BadHttpMessage - * - * return cls(desc.decode('latin-1')) # <<<<<<<<<<<<<< + /* "aiohttp/_http_parser.pyx":561 + * finally: + * PyBuffer_Release(&py_buf) + * PyByteArray_Resize(self._buf, 0) # <<<<<<<<<<<<<< * * */ - __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, 529, __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); - } - } - if (!__pyx_t_4) { - __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 529, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_GOTREF(__pyx_t_1); - } else { - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[2] = {__pyx_t_4, __pyx_t_2}; - __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 529, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[2] = {__pyx_t_4, __pyx_t_2}; - __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 529, __pyx_L1_error) - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - } else - #endif - { - __pyx_t_5 = PyTuple_New(1+1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 529, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __pyx_t_4 = NULL; - __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_5, 0+1, __pyx_t_2); - __pyx_t_2 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 529, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } - } + __pyx_t_3 = __pyx_v_self->__pyx_base._buf; + __Pyx_INCREF(__pyx_t_3); + __pyx_t_7 = PyByteArray_Resize(__pyx_t_3, 0); if (unlikely(__pyx_t_7 == ((int)-1))) __PYX_ERR(0, 561, __pyx_L1_error) __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":502 - * - * - * cdef parser_error_from_errno(cparser.http_errno errno): # <<<<<<<<<<<<<< - * cdef bytes desc = cparser.http_errno_description(errno) + /* "aiohttp/_http_parser.pyx":547 + * payload_exception, response_with_body) * + * cdef object _on_status_complete(self): # <<<<<<<<<<<<<< + * cdef Py_buffer py_buf + * 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_1); - __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.parser_error_from_errno", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("aiohttp._http_parser.HttpRequestParser._on_status_complete", __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; } -/* "aiohttp/_http_parser.pyx":532 - * - * - * def parse_url(url): # <<<<<<<<<<<<<< - * cdef: - * Py_buffer py_buf +/* "(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_1parse_url(PyObject *__pyx_self, PyObject *__pyx_v_url); /*proto*/ -static PyMethodDef __pyx_mdef_7aiohttp_12_http_parser_1parse_url = {"parse_url", (PyCFunction)__pyx_pw_7aiohttp_12_http_parser_1parse_url, METH_O, 0}; -static PyObject *__pyx_pw_7aiohttp_12_http_parser_1parse_url(PyObject *__pyx_self, PyObject *__pyx_v_url) { +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("parse_url (wrapper)", 0); - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_parse_url(__pyx_self, ((PyObject *)__pyx_v_url)); + __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_parse_url(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_url) { - Py_buffer __pyx_v_py_buf; - char *__pyx_v_buf_data; +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 - int __pyx_t_1; - 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; - 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; - __Pyx_RefNannySetupContext("parse_url", 0); + PyObject *__pyx_t_1 = NULL; + __Pyx_RefNannySetupContext("__reduce_cython__", 0); - /* "aiohttp/_http_parser.pyx":537 - * char* buf_data - * - * PyObject_GetBuffer(url, &py_buf, PyBUF_SIMPLE) # <<<<<<<<<<<<<< - * try: - * buf_data = py_buf.buf + /* "(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 = PyObject_GetBuffer(__pyx_v_url, (&__pyx_v_py_buf), PyBUF_SIMPLE); if (unlikely(__pyx_t_1 == ((int)-1))) __PYX_ERR(0, 537, __pyx_L1_error) + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__7, 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) - /* "aiohttp/_http_parser.pyx":538 - * - * PyObject_GetBuffer(url, &py_buf, PyBUF_SIMPLE) - * try: # <<<<<<<<<<<<<< - * buf_data = py_buf.buf - * return _parse_url(buf_data, py_buf.len) + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): */ - /*try:*/ { - /* "aiohttp/_http_parser.pyx":539 - * PyObject_GetBuffer(url, &py_buf, PyBUF_SIMPLE) - * try: - * buf_data = py_buf.buf # <<<<<<<<<<<<<< - * return _parse_url(buf_data, py_buf.len) - * finally: - */ - __pyx_v_buf_data = ((char *)__pyx_v_py_buf.buf); + /* 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; +} - /* "aiohttp/_http_parser.pyx":540 - * try: - * buf_data = py_buf.buf - * return _parse_url(buf_data, py_buf.len) # <<<<<<<<<<<<<< - * finally: - * PyBuffer_Release(&py_buf) +/* "(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__") */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_parse_url); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 540, __pyx_L4_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_buf_data); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 540, __pyx_L4_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyInt_FromSsize_t(__pyx_v_py_buf.len); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 540, __pyx_L4_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = NULL; - __pyx_t_1 = 0; - if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { - __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_3); - if (likely(__pyx_t_6)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); - __Pyx_INCREF(__pyx_t_6); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_3, function); - __pyx_t_1 = 1; - } - } - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[3] = {__pyx_t_6, __pyx_t_4, __pyx_t_5}; - __pyx_t_2 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_1, 2+__pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 540, __pyx_L4_error) - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_GOTREF(__pyx_t_2); - __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_3)) { - PyObject *__pyx_temp[3] = {__pyx_t_6, __pyx_t_4, __pyx_t_5}; - __pyx_t_2 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_1, 2+__pyx_t_1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 540, __pyx_L4_error) - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } else - #endif - { - __pyx_t_7 = PyTuple_New(2+__pyx_t_1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 540, __pyx_L4_error) - __Pyx_GOTREF(__pyx_t_7); - if (__pyx_t_6) { - __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_6); __pyx_t_6 = NULL; - } - __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_7, 0+__pyx_t_1, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_7, 1+__pyx_t_1, __pyx_t_5); - __pyx_t_4 = 0; - __pyx_t_5 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_7, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 540, __pyx_L4_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; - goto __pyx_L3_return; - } - /* "aiohttp/_http_parser.pyx":542 - * return _parse_url(buf_data, py_buf.len) - * finally: - * PyBuffer_Release(&py_buf) # <<<<<<<<<<<<<< - * - * +/* 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; + __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__") # <<<<<<<<<<<<<< */ - /*finally:*/ { - __pyx_L4_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_6); __pyx_t_6 = 0; - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 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_1 = __pyx_lineno; __pyx_t_8 = __pyx_clineno; __pyx_t_9 = __pyx_filename; - { - PyBuffer_Release((&__pyx_v_py_buf)); - } - 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_1; __pyx_clineno = __pyx_t_8; __pyx_filename = __pyx_t_9; - goto __pyx_L1_error; - } - __pyx_L3_return: { - __pyx_t_15 = __pyx_r; - __pyx_r = 0; - PyBuffer_Release((&__pyx_v_py_buf)); - __pyx_r = __pyx_t_15; - __pyx_t_15 = 0; - goto __pyx_L0; - } - } + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__8, 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) - /* "aiohttp/_http_parser.pyx":532 - * - * - * def parse_url(url): # <<<<<<<<<<<<<< - * cdef: - * Py_buffer py_buf + /* "(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_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_AddTraceback("aiohttp._http_parser.parse_url", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("aiohttp._http_parser.HttpRequestParser.__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":545 - * +/* "aiohttp/_http_parser.pyx":566 + * cdef class HttpResponseParser(HttpParser): * - * def _parse_url(char* buf_data, size_t length): # <<<<<<<<<<<<<< - * cdef: - * cparser.http_parser_url* parsed + * def __init__(self, protocol, loop, timer=None, # <<<<<<<<<<<<<< + * size_t max_line_size=8190, size_t max_headers=32768, + * size_t max_field_size=8190, payload_exception=None, */ /* Python wrapper */ -static PyObject *__pyx_pw_7aiohttp_12_http_parser_3_parse_url(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ -static PyMethodDef __pyx_mdef_7aiohttp_12_http_parser_3_parse_url = {"_parse_url", (PyCFunction)__pyx_pw_7aiohttp_12_http_parser_3_parse_url, METH_VARARGS|METH_KEYWORDS, 0}; -static PyObject *__pyx_pw_7aiohttp_12_http_parser_3_parse_url(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { - char *__pyx_v_buf_data; - size_t __pyx_v_length; - PyObject *__pyx_r = 0; +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; + 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; + CYTHON_UNUSED int __pyx_v_read_until_eof; + int __pyx_v_auto_decompress; + int __pyx_r; __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("_parse_url (wrapper)", 0); + __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); { - static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_buf_data,&__pyx_n_s_length,0}; - PyObject* values[2] = {0,0}; + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_protocol,&__pyx_n_s_loop,&__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[10] = {0,0,0,0,0,0,0,0,0,0}; + values[2] = ((PyObject *)Py_None); + + /* "aiohttp/_http_parser.pyx":568 + * def __init__(self, protocol, loop, 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[6] = ((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 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); @@ -10001,2382 +10319,9709 @@ kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: - if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_buf_data)) != 0)) kw_args--; + 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_length)) != 0)) kw_args--; + if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_loop)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("_parse_url", 1, 2, 2, 1); __PYX_ERR(0, 545, __pyx_L3_error) + __Pyx_RaiseArgtupleInvalid("__init__", 0, 2, 10, 1); __PYX_ERR(0, 566, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 2: + if (kw_args > 0) { + PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_timer); + if (value) { values[2] = value; kw_args--; } + } + CYTHON_FALLTHROUGH; + case 3: + if (kw_args > 0) { + PyObject* value = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_max_line_size); + 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_headers); + 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_field_size); + 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_payload_exception); + 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_response_with_body); + 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_read_until_eof); + 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_auto_decompress); + if (value) { values[9] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_parse_url") < 0)) __PYX_ERR(0, 545, __pyx_L3_error) + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) __PYX_ERR(0, 566, __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_buf_data = __Pyx_PyObject_AsWritableString(values[0]); if (unlikely((!__pyx_v_buf_data) && PyErr_Occurred())) __PYX_ERR(0, 545, __pyx_L3_error) - __pyx_v_length = __Pyx_PyInt_As_size_t(values[1]); if (unlikely((__pyx_v_length == (size_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 545, __pyx_L3_error) - } - goto __pyx_L4_argument_unpacking_done; - __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("_parse_url", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 545, __pyx_L3_error) - __pyx_L3_error:; - __Pyx_AddTraceback("aiohttp._http_parser._parse_url", __pyx_clineno, __pyx_lineno, __pyx_filename); - __Pyx_RefNannyFinishContext(); - return NULL; - __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_pf_7aiohttp_12_http_parser_2_parse_url(__pyx_self, __pyx_v_buf_data, __pyx_v_length); - - /* function exit code */ - __Pyx_RefNannyFinishContext(); - return __pyx_r; -} - -static PyObject *__pyx_pf_7aiohttp_12_http_parser_2_parse_url(CYTHON_UNUSED PyObject *__pyx_self, char *__pyx_v_buf_data, size_t __pyx_v_length) { - struct http_parser_url *__pyx_v_parsed; - int __pyx_v_res; - PyObject *__pyx_v_schema = 0; - PyObject *__pyx_v_host = 0; - PyObject *__pyx_v_port = 0; - PyObject *__pyx_v_path = 0; - PyObject *__pyx_v_query = 0; - PyObject *__pyx_v_fragment = 0; - PyObject *__pyx_v_user = 0; - PyObject *__pyx_v_password = 0; - PyObject *__pyx_v_userinfo = 0; - CYTHON_UNUSED PyObject *__pyx_v_result = 0; - int __pyx_v_off; - int __pyx_v_ln; - CYTHON_UNUSED PyObject *__pyx_v_sep = NULL; - PyObject *__pyx_r = NULL; - __Pyx_RefNannyDeclarations - int __pyx_t_1; - uint16_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 = NULL; - PyObject *(*__pyx_t_8)(PyObject *); - PyObject *__pyx_t_9 = NULL; - PyObject *__pyx_t_10 = NULL; - int __pyx_t_11; - int __pyx_t_12; - char const *__pyx_t_13; - 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; - __Pyx_RefNannySetupContext("_parse_url", 0); + switch (PyTuple_GET_SIZE(__pyx_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); + 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_timer = values[2]; + if (values[3]) { + __pyx_v_max_line_size = __Pyx_PyInt_As_size_t(values[3]); if (unlikely((__pyx_v_max_line_size == (size_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 567, __pyx_L3_error) + } else { + __pyx_v_max_line_size = ((size_t)0x1FFE); + } + if (values[4]) { + __pyx_v_max_headers = __Pyx_PyInt_As_size_t(values[4]); if (unlikely((__pyx_v_max_headers == (size_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 567, __pyx_L3_error) + } else { + __pyx_v_max_headers = ((size_t)0x8000); + } + if (values[5]) { + __pyx_v_max_field_size = __Pyx_PyInt_As_size_t(values[5]); if (unlikely((__pyx_v_max_field_size == (size_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 568, __pyx_L3_error) + } else { + __pyx_v_max_field_size = ((size_t)0x1FFE); + } + __pyx_v_payload_exception = values[6]; + if (values[7]) { + __pyx_v_response_with_body = __Pyx_PyObject_IsTrue(values[7]); if (unlikely((__pyx_v_response_with_body == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 569, __pyx_L3_error) + } else { - /* "aiohttp/_http_parser.pyx":549 - * cparser.http_parser_url* parsed - * int res - * str schema = None # <<<<<<<<<<<<<< - * str host = None - * object port = None + /* "aiohttp/_http_parser.pyx":569 + * 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, timer, */ - __Pyx_INCREF(Py_None); - __pyx_v_schema = ((PyObject*)Py_None); + __pyx_v_response_with_body = ((int)1); + } + if (values[8]) { + __pyx_v_read_until_eof = __Pyx_PyObject_IsTrue(values[8]); if (unlikely((__pyx_v_read_until_eof == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 569, __pyx_L3_error) + } else { + __pyx_v_read_until_eof = ((int)0); + } + if (values[9]) { + __pyx_v_auto_decompress = __Pyx_PyObject_IsTrue(values[9]); if (unlikely((__pyx_v_auto_decompress == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 570, __pyx_L3_error) + } else { - /* "aiohttp/_http_parser.pyx":550 - * int res - * str schema = None - * str host = None # <<<<<<<<<<<<<< - * object port = None - * str path = None + /* "aiohttp/_http_parser.pyx":570 + * 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, timer, + * max_line_size, max_headers, max_field_size, */ - __Pyx_INCREF(Py_None); - __pyx_v_host = ((PyObject*)Py_None); + __pyx_v_auto_decompress = ((int)1); + } + } + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__init__", 0, 2, 10, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 566, __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_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":551 - * str schema = None - * str host = None - * object port = None # <<<<<<<<<<<<<< - * str path = None - * str query = None + /* "aiohttp/_http_parser.pyx":566 + * cdef class HttpResponseParser(HttpParser): + * + * def __init__(self, protocol, loop, timer=None, # <<<<<<<<<<<<<< + * size_t max_line_size=8190, size_t max_headers=32768, + * size_t max_field_size=8190, payload_exception=None, */ - __Pyx_INCREF(Py_None); - __pyx_v_port = Py_None; - /* "aiohttp/_http_parser.pyx":552 - * str host = None - * object port = None - * str path = None # <<<<<<<<<<<<<< - * str query = None - * str fragment = None - */ - __Pyx_INCREF(Py_None); - __pyx_v_path = ((PyObject*)Py_None); + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "aiohttp/_http_parser.pyx":553 - * object port = None - * str path = None - * str query = None # <<<<<<<<<<<<<< - * str fragment = None - * str user = None - */ - __Pyx_INCREF(Py_None); - __pyx_v_query = ((PyObject*)Py_None); +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, 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, CYTHON_UNUSED 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; + __Pyx_RefNannySetupContext("__init__", 0); - /* "aiohttp/_http_parser.pyx":554 - * str path = None - * str query = None - * str fragment = None # <<<<<<<<<<<<<< - * str user = None - * str password = None + /* "aiohttp/_http_parser.pyx":571 + * bint response_with_body=True, bint read_until_eof=False, + * bint auto_decompress=True): + * self._init(cparser.HTTP_RESPONSE, protocol, loop, timer, # <<<<<<<<<<<<<< + * max_line_size, max_headers, max_field_size, + * payload_exception, response_with_body, auto_decompress) */ - __Pyx_INCREF(Py_None); - __pyx_v_fragment = ((PyObject*)Py_None); + __pyx_t_2.__pyx_n = 7; + __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.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_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 571, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "aiohttp/_http_parser.pyx":555 - * str query = None - * str fragment = None - * str user = None # <<<<<<<<<<<<<< - * str password = None - * str userinfo = None + /* "aiohttp/_http_parser.pyx":566 + * cdef class HttpResponseParser(HttpParser): + * + * def __init__(self, protocol, loop, timer=None, # <<<<<<<<<<<<<< + * size_t max_line_size=8190, size_t max_headers=32768, + * size_t max_field_size=8190, payload_exception=None, */ - __Pyx_INCREF(Py_None); - __pyx_v_user = ((PyObject*)Py_None); - /* "aiohttp/_http_parser.pyx":556 - * str fragment = None - * str user = None - * str password = None # <<<<<<<<<<<<<< - * str userinfo = None - * object result = None - */ - __Pyx_INCREF(Py_None); - __pyx_v_password = ((PyObject*)Py_None); + /* 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":557 - * str user = None - * str password = None - * str userinfo = None # <<<<<<<<<<<<<< - * object result = None - * int off +/* "aiohttp/_http_parser.pyx":575 + * payload_exception, response_with_body, auto_decompress) + * + * cdef object _on_status_complete(self): # <<<<<<<<<<<<<< + * if self._buf: + * self._reason = self._buf.decode('utf-8', 'surrogateescape') */ - __Pyx_INCREF(Py_None); - __pyx_v_userinfo = ((PyObject*)Py_None); - /* "aiohttp/_http_parser.pyx":558 - * str password = None - * str userinfo = None - * object result = None # <<<<<<<<<<<<<< - * int off - * int ln +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; + __Pyx_RefNannySetupContext("_on_status_complete", 0); + + /* "aiohttp/_http_parser.pyx":576 + * + * cdef object _on_status_complete(self): + * if self._buf: # <<<<<<<<<<<<<< + * self._reason = self._buf.decode('utf-8', 'surrogateescape') + * PyByteArray_Resize(self._buf, 0) */ - __Pyx_INCREF(Py_None); - __pyx_v_result = Py_None; + __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":562 - * int ln + /* "aiohttp/_http_parser.pyx":577 + * cdef object _on_status_complete(self): + * if self._buf: + * self._reason = self._buf.decode('utf-8', 'surrogateescape') # <<<<<<<<<<<<<< + * PyByteArray_Resize(self._buf, 0) * - * parsed = \ # <<<<<<<<<<<<<< - * PyMem_Malloc(sizeof(cparser.http_parser_url)) - * if parsed is NULL: */ - __pyx_v_parsed = ((struct http_parser_url *)PyMem_Malloc((sizeof(struct http_parser_url)))); + if (unlikely(__pyx_v_self->__pyx_base._buf == Py_None)) { + PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%.30s'", "decode"); + __PYX_ERR(0, 577, __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, 577, __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":564 - * parsed = \ - * PyMem_Malloc(sizeof(cparser.http_parser_url)) - * if parsed is NULL: # <<<<<<<<<<<<<< - * raise MemoryError() - * cparser.http_parser_url_init(parsed) + /* "aiohttp/_http_parser.pyx":578 + * if self._buf: + * self._reason = self._buf.decode('utf-8', 'surrogateescape') + * PyByteArray_Resize(self._buf, 0) # <<<<<<<<<<<<<< + * + * */ - __pyx_t_1 = ((__pyx_v_parsed == NULL) != 0); - if (unlikely(__pyx_t_1)) { + __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, 578, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "aiohttp/_http_parser.pyx":565 - * PyMem_Malloc(sizeof(cparser.http_parser_url)) - * if parsed is NULL: - * raise MemoryError() # <<<<<<<<<<<<<< - * cparser.http_parser_url_init(parsed) - * try: - */ - PyErr_NoMemory(); __PYX_ERR(0, 565, __pyx_L1_error) - - /* "aiohttp/_http_parser.pyx":564 - * parsed = \ - * PyMem_Malloc(sizeof(cparser.http_parser_url)) - * if parsed is NULL: # <<<<<<<<<<<<<< - * raise MemoryError() - * cparser.http_parser_url_init(parsed) + /* "aiohttp/_http_parser.pyx":576 + * + * cdef object _on_status_complete(self): + * if self._buf: # <<<<<<<<<<<<<< + * self._reason = self._buf.decode('utf-8', 'surrogateescape') + * PyByteArray_Resize(self._buf, 0) */ } - /* "aiohttp/_http_parser.pyx":566 - * if parsed is NULL: - * raise MemoryError() - * cparser.http_parser_url_init(parsed) # <<<<<<<<<<<<<< - * try: - * res = cparser.http_parser_parse_url(buf_data, length, 0, parsed) - */ - http_parser_url_init(__pyx_v_parsed); - - /* "aiohttp/_http_parser.pyx":567 - * raise MemoryError() - * cparser.http_parser_url_init(parsed) - * try: # <<<<<<<<<<<<<< - * res = cparser.http_parser_parse_url(buf_data, length, 0, parsed) + /* "aiohttp/_http_parser.pyx":575 + * payload_exception, response_with_body, auto_decompress) * + * cdef object _on_status_complete(self): # <<<<<<<<<<<<<< + * if self._buf: + * self._reason = self._buf.decode('utf-8', 'surrogateescape') */ - /*try:*/ { - /* "aiohttp/_http_parser.pyx":568 - * cparser.http_parser_url_init(parsed) - * try: - * res = cparser.http_parser_parse_url(buf_data, length, 0, parsed) # <<<<<<<<<<<<<< - * - * if res == 0: - */ - __pyx_v_res = http_parser_parse_url(__pyx_v_buf_data, __pyx_v_length, 0, __pyx_v_parsed); + /* 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; +} - /* "aiohttp/_http_parser.pyx":570 - * res = cparser.http_parser_parse_url(buf_data, length, 0, parsed) - * - * if res == 0: # <<<<<<<<<<<<<< - * if parsed.field_set & (1 << cparser.UF_SCHEMA): - * off = parsed.field_data[cparser.UF_SCHEMA].off +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): */ - __pyx_t_1 = ((__pyx_v_res == 0) != 0); - if (likely(__pyx_t_1)) { - /* "aiohttp/_http_parser.pyx":571 - * - * if res == 0: - * if parsed.field_set & (1 << cparser.UF_SCHEMA): # <<<<<<<<<<<<<< - * off = parsed.field_data[cparser.UF_SCHEMA].off - * ln = parsed.field_data[cparser.UF_SCHEMA].len - */ - __pyx_t_1 = ((__pyx_v_parsed->field_set & (1 << UF_SCHEMA)) != 0); - if (__pyx_t_1) { +/* 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)); - /* "aiohttp/_http_parser.pyx":572 - * if res == 0: - * if parsed.field_set & (1 << cparser.UF_SCHEMA): - * off = parsed.field_data[cparser.UF_SCHEMA].off # <<<<<<<<<<<<<< - * ln = parsed.field_data[cparser.UF_SCHEMA].len - * schema = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') - */ - __pyx_t_2 = (__pyx_v_parsed->field_data[((int)UF_SCHEMA)]).off; - __pyx_v_off = __pyx_t_2; + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "aiohttp/_http_parser.pyx":573 - * if parsed.field_set & (1 << cparser.UF_SCHEMA): - * off = parsed.field_data[cparser.UF_SCHEMA].off - * ln = parsed.field_data[cparser.UF_SCHEMA].len # <<<<<<<<<<<<<< - * schema = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') - * else: - */ - __pyx_t_2 = (__pyx_v_parsed->field_data[((int)UF_SCHEMA)]).len; - __pyx_v_ln = __pyx_t_2; +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; + __Pyx_RefNannySetupContext("__reduce_cython__", 0); - /* "aiohttp/_http_parser.pyx":574 - * off = parsed.field_data[cparser.UF_SCHEMA].off - * ln = parsed.field_data[cparser.UF_SCHEMA].len - * schema = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') # <<<<<<<<<<<<<< - * else: - * schema = '' + /* "(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_3 = __Pyx_decode_c_string(__pyx_v_buf_data, __pyx_v_off, (__pyx_v_off + __pyx_v_ln), NULL, ((char const *)"surrogateescape"), PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 574, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF_SET(__pyx_v_schema, ((PyObject*)__pyx_t_3)); - __pyx_t_3 = 0; + __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) - /* "aiohttp/_http_parser.pyx":571 - * - * if res == 0: - * if parsed.field_set & (1 << cparser.UF_SCHEMA): # <<<<<<<<<<<<<< - * off = parsed.field_data[cparser.UF_SCHEMA].off - * ln = parsed.field_data[cparser.UF_SCHEMA].len + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): */ - goto __pyx_L8; - } - /* "aiohttp/_http_parser.pyx":576 - * schema = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') - * else: - * schema = '' # <<<<<<<<<<<<<< - * - * if parsed.field_set & (1 << cparser.UF_HOST): - */ - /*else*/ { - __Pyx_INCREF(__pyx_kp_u__6); - __Pyx_DECREF_SET(__pyx_v_schema, __pyx_kp_u__6); - } - __pyx_L8:; + /* 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; +} - /* "aiohttp/_http_parser.pyx":578 - * schema = '' - * - * if parsed.field_set & (1 << cparser.UF_HOST): # <<<<<<<<<<<<<< - * off = parsed.field_data[cparser.UF_HOST].off - * ln = parsed.field_data[cparser.UF_HOST].len +/* "(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__") */ - __pyx_t_1 = ((__pyx_v_parsed->field_set & (1 << UF_HOST)) != 0); - if (__pyx_t_1) { - /* "aiohttp/_http_parser.pyx":579 - * - * if parsed.field_set & (1 << cparser.UF_HOST): - * off = parsed.field_data[cparser.UF_HOST].off # <<<<<<<<<<<<<< - * ln = parsed.field_data[cparser.UF_HOST].len - * host = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') - */ - __pyx_t_2 = (__pyx_v_parsed->field_data[((int)UF_HOST)]).off; - __pyx_v_off = __pyx_t_2; +/* 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)); - /* "aiohttp/_http_parser.pyx":580 - * if parsed.field_set & (1 << cparser.UF_HOST): - * off = parsed.field_data[cparser.UF_HOST].off - * ln = parsed.field_data[cparser.UF_HOST].len # <<<<<<<<<<<<<< - * host = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') - * else: - */ - __pyx_t_2 = (__pyx_v_parsed->field_data[((int)UF_HOST)]).len; - __pyx_v_ln = __pyx_t_2; + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} - /* "aiohttp/_http_parser.pyx":581 - * off = parsed.field_data[cparser.UF_HOST].off - * ln = parsed.field_data[cparser.UF_HOST].len - * host = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') # <<<<<<<<<<<<<< - * else: - * host = '' - */ - __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_buf_data, __pyx_v_off, (__pyx_v_off + __pyx_v_ln), NULL, ((char const *)"surrogateescape"), PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 581, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF_SET(__pyx_v_host, ((PyObject*)__pyx_t_3)); - __pyx_t_3 = 0; +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; + __Pyx_RefNannySetupContext("__setstate_cython__", 0); - /* "aiohttp/_http_parser.pyx":578 - * schema = '' - * - * if parsed.field_set & (1 << cparser.UF_HOST): # <<<<<<<<<<<<<< - * off = parsed.field_data[cparser.UF_HOST].off - * ln = parsed.field_data[cparser.UF_HOST].len + /* "(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__") # <<<<<<<<<<<<<< */ - goto __pyx_L9; - } + __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) - /* "aiohttp/_http_parser.pyx":583 - * host = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') - * else: - * host = '' # <<<<<<<<<<<<<< - * - * if parsed.field_set & (1 << cparser.UF_PORT): + /* "(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__") */ - /*else*/ { - __Pyx_INCREF(__pyx_kp_u__6); - __Pyx_DECREF_SET(__pyx_v_host, __pyx_kp_u__6); - } - __pyx_L9:; - /* "aiohttp/_http_parser.pyx":585 - * host = '' + /* 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":581 * - * if parsed.field_set & (1 << cparser.UF_PORT): # <<<<<<<<<<<<<< - * port = parsed.port + * + * cdef int cb_on_message_begin(cparser.http_parser* parser) except -1: # <<<<<<<<<<<<<< + * cdef HttpParser pyparser = parser.data * */ - __pyx_t_1 = ((__pyx_v_parsed->field_set & (1 << UF_PORT)) != 0); - if (__pyx_t_1) { - /* "aiohttp/_http_parser.pyx":586 +static int __pyx_f_7aiohttp_12_http_parser_cb_on_message_begin(struct http_parser *__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; + __Pyx_RefNannySetupContext("cb_on_message_begin", 0); + + /* "aiohttp/_http_parser.pyx":582 * - * if parsed.field_set & (1 << cparser.UF_PORT): - * port = parsed.port # <<<<<<<<<<<<<< + * cdef int cb_on_message_begin(cparser.http_parser* parser) except -1: + * cdef HttpParser pyparser = parser.data # <<<<<<<<<<<<<< * - * if parsed.field_set & (1 << cparser.UF_PATH): + * pyparser._started = True */ - __pyx_t_3 = __Pyx_PyInt_From_uint16_t(__pyx_v_parsed->port); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 586, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF_SET(__pyx_v_port, __pyx_t_3); - __pyx_t_3 = 0; + __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":585 - * host = '' - * - * if parsed.field_set & (1 << cparser.UF_PORT): # <<<<<<<<<<<<<< - * port = parsed.port + /* "aiohttp/_http_parser.pyx":584 + * cdef HttpParser pyparser = parser.data * + * pyparser._started = True # <<<<<<<<<<<<<< + * pyparser._headers = CIMultiDict() + * pyparser._raw_headers = [] */ - } + __pyx_v_pyparser->_started = 1; - /* "aiohttp/_http_parser.pyx":588 - * port = parsed.port + /* "aiohttp/_http_parser.pyx":585 * - * if parsed.field_set & (1 << cparser.UF_PATH): # <<<<<<<<<<<<<< - * off = parsed.field_data[cparser.UF_PATH].off - * ln = parsed.field_data[cparser.UF_PATH].len + * pyparser._started = True + * pyparser._headers = CIMultiDict() # <<<<<<<<<<<<<< + * pyparser._raw_headers = [] + * PyByteArray_Resize(pyparser._buf, 0) */ - __pyx_t_1 = ((__pyx_v_parsed->field_set & (1 << UF_PATH)) != 0); - if (__pyx_t_1) { + __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, 585, __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":589 - * - * if parsed.field_set & (1 << cparser.UF_PATH): - * off = parsed.field_data[cparser.UF_PATH].off # <<<<<<<<<<<<<< - * ln = parsed.field_data[cparser.UF_PATH].len - * path = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') + /* "aiohttp/_http_parser.pyx":586 + * pyparser._started = True + * pyparser._headers = CIMultiDict() + * pyparser._raw_headers = [] # <<<<<<<<<<<<<< + * PyByteArray_Resize(pyparser._buf, 0) + * pyparser._path = None */ - __pyx_t_2 = (__pyx_v_parsed->field_data[((int)UF_PATH)]).off; - __pyx_v_off = __pyx_t_2; + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 586, __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":590 - * if parsed.field_set & (1 << cparser.UF_PATH): - * off = parsed.field_data[cparser.UF_PATH].off - * ln = parsed.field_data[cparser.UF_PATH].len # <<<<<<<<<<<<<< - * path = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') - * else: + /* "aiohttp/_http_parser.pyx":587 + * pyparser._headers = CIMultiDict() + * pyparser._raw_headers = [] + * PyByteArray_Resize(pyparser._buf, 0) # <<<<<<<<<<<<<< + * pyparser._path = None + * pyparser._reason = None */ - __pyx_t_2 = (__pyx_v_parsed->field_data[((int)UF_PATH)]).len; - __pyx_v_ln = __pyx_t_2; + __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, 587, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "aiohttp/_http_parser.pyx":591 - * off = parsed.field_data[cparser.UF_PATH].off - * ln = parsed.field_data[cparser.UF_PATH].len - * path = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') # <<<<<<<<<<<<<< - * else: - * path = '' + /* "aiohttp/_http_parser.pyx":588 + * pyparser._raw_headers = [] + * PyByteArray_Resize(pyparser._buf, 0) + * pyparser._path = None # <<<<<<<<<<<<<< + * pyparser._reason = None + * return 0 */ - __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_buf_data, __pyx_v_off, (__pyx_v_off + __pyx_v_ln), NULL, ((char const *)"surrogateescape"), PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 591, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF_SET(__pyx_v_path, ((PyObject*)__pyx_t_3)); - __pyx_t_3 = 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":588 - * port = parsed.port + /* "aiohttp/_http_parser.pyx":589 + * PyByteArray_Resize(pyparser._buf, 0) + * pyparser._path = None + * pyparser._reason = None # <<<<<<<<<<<<<< + * return 0 * - * if parsed.field_set & (1 << cparser.UF_PATH): # <<<<<<<<<<<<<< - * off = parsed.field_data[cparser.UF_PATH].off - * ln = parsed.field_data[cparser.UF_PATH].len */ - goto __pyx_L11; - } + __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":593 - * path = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') - * else: - * path = '' # <<<<<<<<<<<<<< + /* "aiohttp/_http_parser.pyx":590 + * pyparser._path = None + * pyparser._reason = None + * return 0 # <<<<<<<<<<<<<< * - * if parsed.field_set & (1 << cparser.UF_QUERY): - */ - /*else*/ { - __Pyx_INCREF(__pyx_kp_u__6); - __Pyx_DECREF_SET(__pyx_v_path, __pyx_kp_u__6); - } - __pyx_L11:; - - /* "aiohttp/_http_parser.pyx":595 - * path = '' * - * if parsed.field_set & (1 << cparser.UF_QUERY): # <<<<<<<<<<<<<< - * off = parsed.field_data[cparser.UF_QUERY].off - * ln = parsed.field_data[cparser.UF_QUERY].len */ - __pyx_t_1 = ((__pyx_v_parsed->field_set & (1 << UF_QUERY)) != 0); - if (__pyx_t_1) { + __pyx_r = 0; + goto __pyx_L0; - /* "aiohttp/_http_parser.pyx":596 + /* "aiohttp/_http_parser.pyx":581 + * + * + * cdef int cb_on_message_begin(cparser.http_parser* parser) except -1: # <<<<<<<<<<<<<< + * cdef HttpParser pyparser = parser.data * - * if parsed.field_set & (1 << cparser.UF_QUERY): - * off = parsed.field_data[cparser.UF_QUERY].off # <<<<<<<<<<<<<< - * ln = parsed.field_data[cparser.UF_QUERY].len - * query = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') - */ - __pyx_t_2 = (__pyx_v_parsed->field_data[((int)UF_QUERY)]).off; - __pyx_v_off = __pyx_t_2; - - /* "aiohttp/_http_parser.pyx":597 - * if parsed.field_set & (1 << cparser.UF_QUERY): - * off = parsed.field_data[cparser.UF_QUERY].off - * ln = parsed.field_data[cparser.UF_QUERY].len # <<<<<<<<<<<<<< - * query = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') - * else: */ - __pyx_t_2 = (__pyx_v_parsed->field_data[((int)UF_QUERY)]).len; - __pyx_v_ln = __pyx_t_2; - /* "aiohttp/_http_parser.pyx":598 - * off = parsed.field_data[cparser.UF_QUERY].off - * ln = parsed.field_data[cparser.UF_QUERY].len - * query = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') # <<<<<<<<<<<<<< - * else: - * query = '' - */ - __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_buf_data, __pyx_v_off, (__pyx_v_off + __pyx_v_ln), NULL, ((char const *)"surrogateescape"), PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 598, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF_SET(__pyx_v_query, ((PyObject*)__pyx_t_3)); - __pyx_t_3 = 0; + /* 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":595 - * path = '' +/* "aiohttp/_http_parser.pyx":593 * - * if parsed.field_set & (1 << cparser.UF_QUERY): # <<<<<<<<<<<<<< - * off = parsed.field_data[cparser.UF_QUERY].off - * ln = parsed.field_data[cparser.UF_QUERY].len - */ - goto __pyx_L12; - } - - /* "aiohttp/_http_parser.pyx":600 - * query = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') - * else: - * query = '' # <<<<<<<<<<<<<< * - * if parsed.field_set & (1 << cparser.UF_FRAGMENT): + * cdef int cb_on_url(cparser.http_parser* parser, # <<<<<<<<<<<<<< + * const char *at, size_t length) except -1: + * cdef HttpParser pyparser = parser.data */ - /*else*/ { - __Pyx_INCREF(__pyx_kp_u__6); - __Pyx_DECREF_SET(__pyx_v_query, __pyx_kp_u__6); - } - __pyx_L12:; - /* "aiohttp/_http_parser.pyx":602 - * query = '' - * - * if parsed.field_set & (1 << cparser.UF_FRAGMENT): # <<<<<<<<<<<<<< - * off = parsed.field_data[cparser.UF_FRAGMENT].off - * ln = parsed.field_data[cparser.UF_FRAGMENT].len - */ - __pyx_t_1 = ((__pyx_v_parsed->field_set & (1 << UF_FRAGMENT)) != 0); - if (__pyx_t_1) { +static int __pyx_f_7aiohttp_12_http_parser_cb_on_url(struct http_parser *__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; + __Pyx_RefNannySetupContext("cb_on_url", 0); - /* "aiohttp/_http_parser.pyx":603 - * - * if parsed.field_set & (1 << cparser.UF_FRAGMENT): - * off = parsed.field_data[cparser.UF_FRAGMENT].off # <<<<<<<<<<<<<< - * ln = parsed.field_data[cparser.UF_FRAGMENT].len - * fragment = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') + /* "aiohttp/_http_parser.pyx":595 + * cdef int cb_on_url(cparser.http_parser* parser, + * const char *at, size_t length) except -1: + * cdef HttpParser pyparser = parser.data # <<<<<<<<<<<<<< + * try: + * if length > pyparser._max_line_size: */ - __pyx_t_2 = (__pyx_v_parsed->field_data[((int)UF_FRAGMENT)]).off; - __pyx_v_off = __pyx_t_2; + __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":604 - * if parsed.field_set & (1 << cparser.UF_FRAGMENT): - * off = parsed.field_data[cparser.UF_FRAGMENT].off - * ln = parsed.field_data[cparser.UF_FRAGMENT].len # <<<<<<<<<<<<<< - * fragment = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') - * else: + /* "aiohttp/_http_parser.pyx":596 + * const char *at, size_t length) except -1: + * cdef HttpParser pyparser = parser.data + * try: # <<<<<<<<<<<<<< + * if length > pyparser._max_line_size: + * raise LineTooLong( */ - __pyx_t_2 = (__pyx_v_parsed->field_data[((int)UF_FRAGMENT)]).len; - __pyx_v_ln = __pyx_t_2; + { + __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":605 - * off = parsed.field_data[cparser.UF_FRAGMENT].off - * ln = parsed.field_data[cparser.UF_FRAGMENT].len - * fragment = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') # <<<<<<<<<<<<<< - * else: - * fragment = '' + /* "aiohttp/_http_parser.pyx":597 + * 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_3 = __Pyx_decode_c_string(__pyx_v_buf_data, __pyx_v_off, (__pyx_v_off + __pyx_v_ln), NULL, ((char const *)"surrogateescape"), PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 605, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF_SET(__pyx_v_fragment, ((PyObject*)__pyx_t_3)); - __pyx_t_3 = 0; + __pyx_t_5 = ((__pyx_v_length > __pyx_v_pyparser->_max_line_size) != 0); + if (unlikely(__pyx_t_5)) { - /* "aiohttp/_http_parser.pyx":602 - * query = '' - * - * if parsed.field_set & (1 << cparser.UF_FRAGMENT): # <<<<<<<<<<<<<< - * off = parsed.field_data[cparser.UF_FRAGMENT].off - * ln = parsed.field_data[cparser.UF_FRAGMENT].len - */ - goto __pyx_L13; - } - - /* "aiohttp/_http_parser.pyx":607 - * fragment = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') - * else: - * fragment = '' # <<<<<<<<<<<<<< - * - * if parsed.field_set & (1 << cparser.UF_USERINFO): - */ - /*else*/ { - __Pyx_INCREF(__pyx_kp_u__6); - __Pyx_DECREF_SET(__pyx_v_fragment, __pyx_kp_u__6); - } - __pyx_L13:; - - /* "aiohttp/_http_parser.pyx":609 - * fragment = '' - * - * if parsed.field_set & (1 << cparser.UF_USERINFO): # <<<<<<<<<<<<<< - * off = parsed.field_data[cparser.UF_USERINFO].off - * ln = parsed.field_data[cparser.UF_USERINFO].len - */ - __pyx_t_1 = ((__pyx_v_parsed->field_set & (1 << UF_USERINFO)) != 0); - if (__pyx_t_1) { - - /* "aiohttp/_http_parser.pyx":610 - * - * if parsed.field_set & (1 << cparser.UF_USERINFO): - * off = parsed.field_data[cparser.UF_USERINFO].off # <<<<<<<<<<<<<< - * ln = parsed.field_data[cparser.UF_USERINFO].len - * userinfo = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') - */ - __pyx_t_2 = (__pyx_v_parsed->field_data[((int)UF_USERINFO)]).off; - __pyx_v_off = __pyx_t_2; - - /* "aiohttp/_http_parser.pyx":611 - * if parsed.field_set & (1 << cparser.UF_USERINFO): - * off = parsed.field_data[cparser.UF_USERINFO].off - * ln = parsed.field_data[cparser.UF_USERINFO].len # <<<<<<<<<<<<<< - * userinfo = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') - * - */ - __pyx_t_2 = (__pyx_v_parsed->field_data[((int)UF_USERINFO)]).len; - __pyx_v_ln = __pyx_t_2; - - /* "aiohttp/_http_parser.pyx":612 - * off = parsed.field_data[cparser.UF_USERINFO].off - * ln = parsed.field_data[cparser.UF_USERINFO].len - * userinfo = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') # <<<<<<<<<<<<<< - * - * user, sep, password = userinfo.partition(':') + /* "aiohttp/_http_parser.pyx":598 + * 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_t_3 = __Pyx_decode_c_string(__pyx_v_buf_data, __pyx_v_off, (__pyx_v_off + __pyx_v_ln), NULL, ((char const *)"surrogateescape"), PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 612, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF_SET(__pyx_v_userinfo, ((PyObject*)__pyx_t_3)); - __pyx_t_3 = 0; + __Pyx_GetModuleGlobalName(__pyx_t_6, __pyx_n_s_LineTooLong); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 598, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_6); - /* "aiohttp/_http_parser.pyx":614 - * userinfo = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') - * - * user, sep, password = userinfo.partition(':') # <<<<<<<<<<<<<< - * - * return URL_build(scheme=schema, + /* "aiohttp/_http_parser.pyx":599 + * 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_3 = __Pyx_CallUnboundCMethod1(&__pyx_umethod_PyUnicode_Type_partition, __pyx_v_userinfo, __pyx_kp_u__13); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 614, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_3); - 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 != 3)) { - if (size > 3) __Pyx_RaiseTooManyValuesError(3); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - __PYX_ERR(0, 614, __pyx_L5_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); - __pyx_t_6 = PyTuple_GET_ITEM(sequence, 2); - } else { - __pyx_t_4 = PyList_GET_ITEM(sequence, 0); - __pyx_t_5 = PyList_GET_ITEM(sequence, 1); - __pyx_t_6 = PyList_GET_ITEM(sequence, 2); + __pyx_t_7 = __Pyx_PyInt_FromSize_t(__pyx_v_pyparser->_max_line_size); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 599, __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, 599, __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; } - __Pyx_INCREF(__pyx_t_4); - __Pyx_INCREF(__pyx_t_5); - __Pyx_INCREF(__pyx_t_6); - #else - __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 614, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 614, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = PySequence_ITEM(sequence, 2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 614, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_6); - #endif - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_7 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 614, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_7); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_8 = Py_TYPE(__pyx_t_7)->tp_iternext; - index = 0; __pyx_t_4 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_4)) goto __pyx_L15_unpacking_failed; - __Pyx_GOTREF(__pyx_t_4); - index = 1; __pyx_t_5 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_5)) goto __pyx_L15_unpacking_failed; - __Pyx_GOTREF(__pyx_t_5); - index = 2; __pyx_t_6 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_6)) goto __pyx_L15_unpacking_failed; - __Pyx_GOTREF(__pyx_t_6); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_7), 3) < 0) __PYX_ERR(0, 614, __pyx_L5_error) - __pyx_t_8 = NULL; + } + #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, 598, __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; - goto __pyx_L16_unpacking_done; - __pyx_L15_unpacking_failed:; + __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, 598, __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_t_8 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - __PYX_ERR(0, 614, __pyx_L5_error) - __pyx_L16_unpacking_done:; + __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, 598, __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, 598, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; } - if (!(likely(PyUnicode_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "unicode", Py_TYPE(__pyx_t_4)->tp_name), 0))) __PYX_ERR(0, 614, __pyx_L5_error) - if (!(likely(PyUnicode_CheckExact(__pyx_t_6))||((__pyx_t_6) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "unicode", Py_TYPE(__pyx_t_6)->tp_name), 0))) __PYX_ERR(0, 614, __pyx_L5_error) - __Pyx_DECREF_SET(__pyx_v_user, ((PyObject*)__pyx_t_4)); - __pyx_t_4 = 0; - __pyx_v_sep = __pyx_t_5; - __pyx_t_5 = 0; - __Pyx_DECREF_SET(__pyx_v_password, ((PyObject*)__pyx_t_6)); - __pyx_t_6 = 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, 598, __pyx_L3_error) - /* "aiohttp/_http_parser.pyx":609 - * fragment = '' - * - * if parsed.field_set & (1 << cparser.UF_USERINFO): # <<<<<<<<<<<<<< - * off = parsed.field_data[cparser.UF_USERINFO].off - * ln = parsed.field_data[cparser.UF_USERINFO].len + /* "aiohttp/_http_parser.pyx":597 + * 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":616 - * user, sep, password = userinfo.partition(':') - * - * return URL_build(scheme=schema, # <<<<<<<<<<<<<< - * user=user, password=password, host=host, port=port, - * path=path, query=query, fragment=fragment) - */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = __Pyx_PyDict_NewPresized(8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 616, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_3); - if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_scheme, __pyx_v_schema) < 0) __PYX_ERR(0, 616, __pyx_L5_error) - - /* "aiohttp/_http_parser.pyx":617 - * - * return URL_build(scheme=schema, - * user=user, password=password, host=host, port=port, # <<<<<<<<<<<<<< - * path=path, query=query, fragment=fragment) - * else: + /* "aiohttp/_http_parser.pyx":600 + * 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 */ - if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_user, __pyx_v_user) < 0) __PYX_ERR(0, 616, __pyx_L5_error) - if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_password, __pyx_v_password) < 0) __PYX_ERR(0, 616, __pyx_L5_error) - if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_host, __pyx_v_host) < 0) __PYX_ERR(0, 616, __pyx_L5_error) - if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_port, __pyx_v_port) < 0) __PYX_ERR(0, 616, __pyx_L5_error) + __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, 600, __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":618 - * return URL_build(scheme=schema, - * user=user, password=password, host=host, port=port, - * path=path, query=query, fragment=fragment) # <<<<<<<<<<<<<< - * else: - * raise InvalidURLError("invalid url {!r}".format(buf_data)) + /* "aiohttp/_http_parser.pyx":596 + * const char *at, size_t length) except -1: + * cdef HttpParser pyparser = parser.data + * try: # <<<<<<<<<<<<<< + * if length > pyparser._max_line_size: + * raise LineTooLong( */ - if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_path, __pyx_v_path) < 0) __PYX_ERR(0, 616, __pyx_L5_error) - if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_query, __pyx_v_query) < 0) __PYX_ERR(0, 616, __pyx_L5_error) - if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_fragment, __pyx_v_fragment) < 0) __PYX_ERR(0, 616, __pyx_L5_error) + } - /* "aiohttp/_http_parser.pyx":616 - * user, sep, password = userinfo.partition(':') + /* "aiohttp/_http_parser.pyx":605 + * return -1 + * else: + * return 0 # <<<<<<<<<<<<<< * - * return URL_build(scheme=schema, # <<<<<<<<<<<<<< - * user=user, password=password, host=host, port=port, - * path=path, query=query, fragment=fragment) - */ - __pyx_t_6 = __Pyx_PyObject_Call(__pyx_v_7aiohttp_12_http_parser_URL_build, __pyx_empty_tuple, __pyx_t_3); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 616, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_r = __pyx_t_6; - __pyx_t_6 = 0; - goto __pyx_L4_return; - - /* "aiohttp/_http_parser.pyx":570 - * res = cparser.http_parser_parse_url(buf_data, length, 0, parsed) * - * if res == 0: # <<<<<<<<<<<<<< - * if parsed.field_set & (1 << cparser.UF_SCHEMA): - * off = parsed.field_data[cparser.UF_SCHEMA].off */ + /*else:*/ { + __pyx_r = 0; + goto __pyx_L6_except_return; } + __pyx_L3_error:; + __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - /* "aiohttp/_http_parser.pyx":620 - * path=path, query=query, fragment=fragment) - * else: - * raise InvalidURLError("invalid url {!r}".format(buf_data)) # <<<<<<<<<<<<<< - * finally: - * PyMem_Free(parsed) + /* "aiohttp/_http_parser.pyx":601 + * '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*/ { - __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_InvalidURLError); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 620, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_kp_u_invalid_url_r, __pyx_n_s_format); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 620, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_7 = __Pyx_PyBytes_FromString(__pyx_v_buf_data); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 620, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_9 = NULL; - if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_4))) { - __pyx_t_9 = PyMethod_GET_SELF(__pyx_t_4); - if (likely(__pyx_t_9)) { - PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); - __Pyx_INCREF(__pyx_t_9); - __Pyx_INCREF(function); - __Pyx_DECREF_SET(__pyx_t_4, function); - } - } - if (!__pyx_t_9) { - __pyx_t_5 = __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_7); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 620, __pyx_L5_error) - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_GOTREF(__pyx_t_5); - } else { - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_4)) { - PyObject *__pyx_temp[2] = {__pyx_t_9, __pyx_t_7}; - __pyx_t_5 = __Pyx_PyFunction_FastCall(__pyx_t_4, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 620, __pyx_L5_error) - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_4)) { - PyObject *__pyx_temp[2] = {__pyx_t_9, __pyx_t_7}; - __pyx_t_5 = __Pyx_PyCFunction_FastCall(__pyx_t_4, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 620, __pyx_L5_error) - __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - } else - #endif - { - __pyx_t_10 = PyTuple_New(1+1); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 620, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_GIVEREF(__pyx_t_9); PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_9); __pyx_t_9 = NULL; - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_10, 0+1, __pyx_t_7); - __pyx_t_7 = 0; - __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_10, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 620, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - } - } - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __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_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, 601, __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":602 + * 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":603 + * 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; } - if (!__pyx_t_4) { - __pyx_t_6 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_5); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 620, __pyx_L5_error) - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_GOTREF(__pyx_t_6); - } else { - #if CYTHON_FAST_PYCALL - if (PyFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[2] = {__pyx_t_4, __pyx_t_5}; - __pyx_t_6 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 620, __pyx_L5_error) - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } else - #endif - #if CYTHON_FAST_PYCCALL - if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { - PyObject *__pyx_temp[2] = {__pyx_t_4, __pyx_t_5}; - __pyx_t_6 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 620, __pyx_L5_error) - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - } else - #endif - { - __pyx_t_10 = PyTuple_New(1+1); if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 620, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_10); - __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_4); __pyx_t_4 = NULL; - __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_10, 0+1, __pyx_t_5); - __pyx_t_5 = 0; - __pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_10, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 620, __pyx_L5_error) - __Pyx_GOTREF(__pyx_t_6); - __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; + + /* "aiohttp/_http_parser.pyx":601 + * '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; } } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_Raise(__pyx_t_6, 0, 0, 0); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - __PYX_ERR(0, 620, __pyx_L5_error) } - } + goto __pyx_L5_except_error; + __pyx_L5_except_error:; - /* "aiohttp/_http_parser.pyx":622 - * raise InvalidURLError("invalid url {!r}".format(buf_data)) - * finally: - * PyMem_Free(parsed) # <<<<<<<<<<<<<< + /* "aiohttp/_http_parser.pyx":596 + * const char *at, size_t length) except -1: + * cdef HttpParser pyparser = parser.data + * try: # <<<<<<<<<<<<<< + * if length > pyparser._max_line_size: + * raise LineTooLong( */ - /*finally:*/ { - __pyx_L5_error:; - /*exception exit:*/{ - __Pyx_PyThreadState_declare - __Pyx_PyThreadState_assign - __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_XDECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; - __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_17, &__pyx_t_18, &__pyx_t_19); - if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_14, &__pyx_t_15, &__pyx_t_16) < 0)) __Pyx_ErrFetch(&__pyx_t_14, &__pyx_t_15, &__pyx_t_16); - __Pyx_XGOTREF(__pyx_t_14); - __Pyx_XGOTREF(__pyx_t_15); - __Pyx_XGOTREF(__pyx_t_16); - __Pyx_XGOTREF(__pyx_t_17); - __Pyx_XGOTREF(__pyx_t_18); - __Pyx_XGOTREF(__pyx_t_19); - __pyx_t_11 = __pyx_lineno; __pyx_t_12 = __pyx_clineno; __pyx_t_13 = __pyx_filename; - { - PyMem_Free(__pyx_v_parsed); - } - if (PY_MAJOR_VERSION >= 3) { - __Pyx_XGIVEREF(__pyx_t_17); - __Pyx_XGIVEREF(__pyx_t_18); - __Pyx_XGIVEREF(__pyx_t_19); - __Pyx_ExceptionReset(__pyx_t_17, __pyx_t_18, __pyx_t_19); - } - __Pyx_XGIVEREF(__pyx_t_14); - __Pyx_XGIVEREF(__pyx_t_15); - __Pyx_XGIVEREF(__pyx_t_16); - __Pyx_ErrRestore(__pyx_t_14, __pyx_t_15, __pyx_t_16); - __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_lineno = __pyx_t_11; __pyx_clineno = __pyx_t_12; __pyx_filename = __pyx_t_13; - goto __pyx_L1_error; - } - __pyx_L4_return: { - __pyx_t_19 = __pyx_r; - __pyx_r = 0; - PyMem_Free(__pyx_v_parsed); - __pyx_r = __pyx_t_19; - __pyx_t_19 = 0; - goto __pyx_L0; - } + __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":545 + /* "aiohttp/_http_parser.pyx":593 * * - * def _parse_url(char* buf_data, size_t length): # <<<<<<<<<<<<<< - * cdef: - * cparser.http_parser_url* parsed + * cdef int cb_on_url(cparser.http_parser* parser, # <<<<<<<<<<<<<< + * const char *at, size_t length) except -1: + * cdef HttpParser pyparser = parser.data */ /* 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_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_10); - __Pyx_AddTraceback("aiohttp._http_parser._parse_url", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + __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(__pyx_v_schema); - __Pyx_XDECREF(__pyx_v_host); - __Pyx_XDECREF(__pyx_v_port); - __Pyx_XDECREF(__pyx_v_path); - __Pyx_XDECREF(__pyx_v_query); - __Pyx_XDECREF(__pyx_v_fragment); - __Pyx_XDECREF(__pyx_v_user); - __Pyx_XDECREF(__pyx_v_password); - __Pyx_XDECREF(__pyx_v_userinfo); - __Pyx_XDECREF(__pyx_v_result); - __Pyx_XDECREF(__pyx_v_sep); - __Pyx_XGIVEREF(__pyx_r); + __Pyx_XDECREF((PyObject *)__pyx_v_pyparser); + __Pyx_XDECREF(__pyx_v_ex); __Pyx_RefNannyFinishContext(); return __pyx_r; } -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->_header_name = ((PyObject*)Py_None); Py_INCREF(Py_None); - p->_header_value = ((PyObject*)Py_None); Py_INCREF(Py_None); - p->_raw_header_name = ((PyObject*)Py_None); Py_INCREF(Py_None); - p->_raw_header_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 = ((PyObject*)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->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); - ++Py_REFCNT(o); - __pyx_pw_7aiohttp_12_http_parser_10HttpParser_3__dealloc__(o); - --Py_REFCNT(o); - PyErr_Restore(etype, eval, etb); - } - Py_CLEAR(p->_header_name); - Py_CLEAR(p->_header_value); - Py_CLEAR(p->_raw_header_name); - Py_CLEAR(p->_raw_header_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_TYPE(o)->tp_free)(o); -} +/* "aiohttp/_http_parser.pyx":608 + * + * + * cdef int cb_on_status(cparser.http_parser* parser, # <<<<<<<<<<<<<< + * const char *at, size_t length) except -1: + * cdef HttpParser pyparser = parser.data + */ -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; +static int __pyx_f_7aiohttp_12_http_parser_cb_on_status(struct http_parser *__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; + __Pyx_RefNannySetupContext("cb_on_status", 0); + + /* "aiohttp/_http_parser.pyx":610 + * cdef int cb_on_status(cparser.http_parser* 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":612 + * 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":613 + * 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":614 + * 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, 614, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_6); + + /* "aiohttp/_http_parser.pyx":615 + * 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, 615, __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, 615, __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, 614, __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, 614, __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, 614, __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, 614, __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, 614, __pyx_L3_error) + + /* "aiohttp/_http_parser.pyx":613 + * 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":616 + * 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, 616, __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":612 + * cdef HttpParser pyparser = parser.data + * cdef str reason + * try: # <<<<<<<<<<<<<< + * if length > pyparser._max_line_size: + * raise LineTooLong( + */ + } + + /* "aiohttp/_http_parser.pyx":621 + * return -1 + * else: + * return 0 # <<<<<<<<<<<<<< + * + * + */ + /*else:*/ { + __pyx_r = 0; + goto __pyx_L6_except_return; + } + __pyx_L3_error:; + __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_XDECREF(__pyx_t_11); __pyx_t_11 = 0; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + + /* "aiohttp/_http_parser.pyx":617 + * '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, 617, __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":618 + * 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":619 + * 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":617 + * '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":612 + * 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":608 + * + * + * cdef int cb_on_status(cparser.http_parser* 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":624 + * + * + * cdef int cb_on_header_field(cparser.http_parser* 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(struct http_parser *__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; + __Pyx_RefNannySetupContext("cb_on_header_field", 0); + + /* "aiohttp/_http_parser.pyx":626 + * cdef int cb_on_header_field(cparser.http_parser* 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":628 + * 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":629 + * 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, 629, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "aiohttp/_http_parser.pyx":630 + * 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, 630, __pyx_L3_error) + } + __pyx_t_5 = PyByteArray_GET_SIZE(__pyx_t_1); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(0, 630, __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":631 + * 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":632 + * 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, 632, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_7); + + /* "aiohttp/_http_parser.pyx":633 + * 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, 633, __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, 633, __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, 632, __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, 632, __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, 632, __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, 632, __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, 632, __pyx_L3_error) + + /* "aiohttp/_http_parser.pyx":631 + * 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":634 + * 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, 634, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "aiohttp/_http_parser.pyx":628 + * 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":639 + * return -1 + * else: + * return 0 # <<<<<<<<<<<<<< + * + * + */ + /*else:*/ { + __pyx_r = 0; + goto __pyx_L6_except_return; + } + __pyx_L3_error:; + __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_XDECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "aiohttp/_http_parser.pyx":635 + * '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, 635, __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":636 + * 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":637 + * 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":635 + * '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":628 + * 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":624 + * + * + * cdef int cb_on_header_field(cparser.http_parser* 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":642 + * + * + * cdef int cb_on_header_value(cparser.http_parser* 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(struct http_parser *__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; + __Pyx_RefNannySetupContext("cb_on_header_value", 0); + + /* "aiohttp/_http_parser.pyx":644 + * cdef int cb_on_header_value(cparser.http_parser* 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":646 + * 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":647 + * 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, 647, __pyx_L3_error) + } + __pyx_t_5 = PyByteArray_GET_SIZE(__pyx_t_1); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(0, 647, __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":648 + * 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":649 + * 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, 649, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_7); + + /* "aiohttp/_http_parser.pyx":650 + * 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, 650, __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, 650, __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, 649, __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, 649, __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, 649, __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, 649, __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, 649, __pyx_L3_error) + + /* "aiohttp/_http_parser.pyx":648 + * 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":651 + * 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, 651, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "aiohttp/_http_parser.pyx":646 + * 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":656 + * return -1 + * else: + * return 0 # <<<<<<<<<<<<<< + * + * + */ + /*else:*/ { + __pyx_r = 0; + goto __pyx_L6_except_return; + } + __pyx_L3_error:; + __Pyx_XDECREF(__pyx_t_10); __pyx_t_10 = 0; + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_XDECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "aiohttp/_http_parser.pyx":652 + * '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, 652, __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":653 + * 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":654 + * 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":652 + * '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":646 + * 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":642 + * + * + * cdef int cb_on_header_value(cparser.http_parser* 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":659 + * + * + * cdef int cb_on_headers_complete(cparser.http_parser* parser) except -1: # <<<<<<<<<<<<<< + * cdef HttpParser pyparser = parser.data + * try: + */ + +static int __pyx_f_7aiohttp_12_http_parser_cb_on_headers_complete(struct http_parser *__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; + __Pyx_RefNannySetupContext("cb_on_headers_complete", 0); + + /* "aiohttp/_http_parser.pyx":660 + * + * cdef int cb_on_headers_complete(cparser.http_parser* 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":661 + * cdef int cb_on_headers_complete(cparser.http_parser* 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":662 + * 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, 662, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "aiohttp/_http_parser.pyx":663 + * 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, 663, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "aiohttp/_http_parser.pyx":661 + * cdef int cb_on_headers_complete(cparser.http_parser* parser) except -1: + * cdef HttpParser pyparser = parser.data + * try: # <<<<<<<<<<<<<< + * pyparser._on_status_complete() + * pyparser._on_headers_complete() + */ + } + + /* "aiohttp/_http_parser.pyx":668 + * 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":669 + * 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":668 + * return -1 + * else: + * if pyparser._cparser.upgrade or pyparser._cparser.method == 5: # CONNECT # <<<<<<<<<<<<<< + * return 2 + * else: + */ + } + + /* "aiohttp/_http_parser.pyx":671 + * 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":664 + * 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, 664, __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":665 + * 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":666 + * 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":664 + * 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":661 + * cdef int cb_on_headers_complete(cparser.http_parser* 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":659 + * + * + * cdef int cb_on_headers_complete(cparser.http_parser* 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":674 + * + * + * cdef int cb_on_body(cparser.http_parser* 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(struct http_parser *__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; + __Pyx_RefNannySetupContext("cb_on_body", 0); + + /* "aiohttp/_http_parser.pyx":676 + * cdef int cb_on_body(cparser.http_parser* 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":677 + * 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, 677, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_body = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "aiohttp/_http_parser.pyx":678 + * 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":679 + * 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, 679, __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, 679, __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, 679, __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, 679, __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, 679, __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, 679, __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":678 + * 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":688 + * return -1 + * else: + * return 0 # <<<<<<<<<<<<<< + * + * + */ + /*else:*/ { + __pyx_r = 0; + goto __pyx_L6_except_return; + } + __pyx_L3_error:; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "aiohttp/_http_parser.pyx":680 + * 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, 680, __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":681 + * 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":682 + * 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, 682, __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, 682, __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, 682, __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, 682, __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":681 + * 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":684 + * 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, 684, __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, 684, __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":685 + * else: + * pyparser._payload.set_exception(exc) + * pyparser._payload_error = 1 # <<<<<<<<<<<<<< + * return -1 + * else: + */ + __pyx_v_pyparser->_payload_error = 1; + + /* "aiohttp/_http_parser.pyx":686 + * 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":680 + * 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_15); __pyx_t_15 = 0; + __Pyx_XDECREF(__pyx_t_13); __pyx_t_13 = 0; + __Pyx_XDECREF(__pyx_t_14); __pyx_t_14 = 0; + __Pyx_XDECREF(__pyx_t_12); __pyx_t_12 = 0; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 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":678 + * 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":674 + * + * + * cdef int cb_on_body(cparser.http_parser* 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":691 + * + * + * cdef int cb_on_message_complete(cparser.http_parser* parser) except -1: # <<<<<<<<<<<<<< + * cdef HttpParser pyparser = parser.data + * try: + */ + +static int __pyx_f_7aiohttp_12_http_parser_cb_on_message_complete(struct http_parser *__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; + __Pyx_RefNannySetupContext("cb_on_message_complete", 0); + + /* "aiohttp/_http_parser.pyx":692 + * + * cdef int cb_on_message_complete(cparser.http_parser* 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":693 + * cdef int cb_on_message_complete(cparser.http_parser* 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":694 + * 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":695 + * 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, 695, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "aiohttp/_http_parser.pyx":693 + * cdef int cb_on_message_complete(cparser.http_parser* parser) except -1: + * cdef HttpParser pyparser = parser.data + * try: # <<<<<<<<<<<<<< + * pyparser._started = False + * pyparser._on_message_complete() + */ + } + + /* "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; + + /* "aiohttp/_http_parser.pyx":696 + * 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, 696, __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":697 + * 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":698 + * 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":696 + * 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":693 + * cdef int cb_on_message_complete(cparser.http_parser* 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":691 + * + * + * cdef int cb_on_message_complete(cparser.http_parser* 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":703 + * + * + * cdef int cb_on_chunk_header(cparser.http_parser* parser) except -1: # <<<<<<<<<<<<<< + * cdef HttpParser pyparser = parser.data + * try: + */ + +static int __pyx_f_7aiohttp_12_http_parser_cb_on_chunk_header(struct http_parser *__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; + __Pyx_RefNannySetupContext("cb_on_chunk_header", 0); + + /* "aiohttp/_http_parser.pyx":704 + * + * cdef int cb_on_chunk_header(cparser.http_parser* 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":705 + * cdef int cb_on_chunk_header(cparser.http_parser* 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":706 + * 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, 706, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "aiohttp/_http_parser.pyx":705 + * cdef int cb_on_chunk_header(cparser.http_parser* parser) except -1: + * cdef HttpParser pyparser = parser.data + * try: # <<<<<<<<<<<<<< + * pyparser._on_chunk_header() + * except BaseException as exc: + */ + } + + /* "aiohttp/_http_parser.pyx":711 + * 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":707 + * 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, 707, __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":708 + * 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":709 + * 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":707 + * 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":705 + * cdef int cb_on_chunk_header(cparser.http_parser* 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":703 + * + * + * cdef int cb_on_chunk_header(cparser.http_parser* 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":714 + * + * + * cdef int cb_on_chunk_complete(cparser.http_parser* parser) except -1: # <<<<<<<<<<<<<< + * cdef HttpParser pyparser = parser.data + * try: + */ + +static int __pyx_f_7aiohttp_12_http_parser_cb_on_chunk_complete(struct http_parser *__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; + __Pyx_RefNannySetupContext("cb_on_chunk_complete", 0); + + /* "aiohttp/_http_parser.pyx":715 + * + * cdef int cb_on_chunk_complete(cparser.http_parser* 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":716 + * cdef int cb_on_chunk_complete(cparser.http_parser* 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":717 + * 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, 717, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "aiohttp/_http_parser.pyx":716 + * cdef int cb_on_chunk_complete(cparser.http_parser* parser) except -1: + * cdef HttpParser pyparser = parser.data + * try: # <<<<<<<<<<<<<< + * pyparser._on_chunk_complete() + * except BaseException as exc: + */ + } + + /* "aiohttp/_http_parser.pyx":722 + * 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":718 + * 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, 718, __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":719 + * 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":720 + * 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":718 + * 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":716 + * cdef int cb_on_chunk_complete(cparser.http_parser* 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":714 + * + * + * cdef int cb_on_chunk_complete(cparser.http_parser* 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":725 + * + * + * cdef parser_error_from_errno(cparser.http_errno errno): # <<<<<<<<<<<<<< + * cdef bytes desc = cparser.http_errno_description(errno) + * + */ + +static PyObject *__pyx_f_7aiohttp_12_http_parser_parser_error_from_errno(enum http_errno __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; + __Pyx_RefNannySetupContext("parser_error_from_errno", 0); + + /* "aiohttp/_http_parser.pyx":726 + * + * cdef parser_error_from_errno(cparser.http_errno errno): + * cdef bytes desc = cparser.http_errno_description(errno) # <<<<<<<<<<<<<< + * + * if errno in (cparser.HPE_CB_message_begin, + */ + __pyx_t_1 = __Pyx_PyBytes_FromString(http_errno_description(__pyx_v_errno)); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 726, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_desc = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; + + /* "aiohttp/_http_parser.pyx":728 + * cdef bytes desc = cparser.http_errno_description(errno) + * + * if errno in (cparser.HPE_CB_message_begin, # <<<<<<<<<<<<<< + * cparser.HPE_CB_url, + * cparser.HPE_CB_header_field, + */ + switch (__pyx_v_errno) { + case HPE_CB_message_begin: + case HPE_CB_url: + + /* "aiohttp/_http_parser.pyx":729 + * + * if errno in (cparser.HPE_CB_message_begin, + * cparser.HPE_CB_url, # <<<<<<<<<<<<<< + * cparser.HPE_CB_header_field, + * cparser.HPE_CB_header_value, + */ + case HPE_CB_header_field: + + /* "aiohttp/_http_parser.pyx":730 + * if errno in (cparser.HPE_CB_message_begin, + * cparser.HPE_CB_url, + * cparser.HPE_CB_header_field, # <<<<<<<<<<<<<< + * cparser.HPE_CB_header_value, + * cparser.HPE_CB_headers_complete, + */ + case HPE_CB_header_value: + + /* "aiohttp/_http_parser.pyx":731 + * cparser.HPE_CB_url, + * cparser.HPE_CB_header_field, + * cparser.HPE_CB_header_value, # <<<<<<<<<<<<<< + * cparser.HPE_CB_headers_complete, + * cparser.HPE_CB_body, + */ + case HPE_CB_headers_complete: + + /* "aiohttp/_http_parser.pyx":732 + * cparser.HPE_CB_header_field, + * cparser.HPE_CB_header_value, + * cparser.HPE_CB_headers_complete, # <<<<<<<<<<<<<< + * cparser.HPE_CB_body, + * cparser.HPE_CB_message_complete, + */ + case HPE_CB_body: + + /* "aiohttp/_http_parser.pyx":733 + * cparser.HPE_CB_header_value, + * cparser.HPE_CB_headers_complete, + * cparser.HPE_CB_body, # <<<<<<<<<<<<<< + * cparser.HPE_CB_message_complete, + * cparser.HPE_CB_status, + */ + case HPE_CB_message_complete: + + /* "aiohttp/_http_parser.pyx":734 + * cparser.HPE_CB_headers_complete, + * cparser.HPE_CB_body, + * cparser.HPE_CB_message_complete, # <<<<<<<<<<<<<< + * cparser.HPE_CB_status, + * cparser.HPE_CB_chunk_header, + */ + case HPE_CB_status: + + /* "aiohttp/_http_parser.pyx":735 + * cparser.HPE_CB_body, + * cparser.HPE_CB_message_complete, + * cparser.HPE_CB_status, # <<<<<<<<<<<<<< + * cparser.HPE_CB_chunk_header, + * cparser.HPE_CB_chunk_complete): + */ + case HPE_CB_chunk_header: + + /* "aiohttp/_http_parser.pyx":736 + * cparser.HPE_CB_message_complete, + * cparser.HPE_CB_status, + * cparser.HPE_CB_chunk_header, # <<<<<<<<<<<<<< + * cparser.HPE_CB_chunk_complete): + * cls = BadHttpMessage + */ + case HPE_CB_chunk_complete: + + /* "aiohttp/_http_parser.pyx":738 + * cparser.HPE_CB_chunk_header, + * cparser.HPE_CB_chunk_complete): + * 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, 738, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_cls = __pyx_t_1; + __pyx_t_1 = 0; + + /* "aiohttp/_http_parser.pyx":728 + * cdef bytes desc = cparser.http_errno_description(errno) + * + * if errno in (cparser.HPE_CB_message_begin, # <<<<<<<<<<<<<< + * cparser.HPE_CB_url, + * cparser.HPE_CB_header_field, + */ + break; + case HPE_INVALID_STATUS: + + /* "aiohttp/_http_parser.pyx":741 + * + * 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, 741, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_cls = __pyx_t_1; + __pyx_t_1 = 0; + + /* "aiohttp/_http_parser.pyx":740 + * cls = BadHttpMessage + * + * elif errno == cparser.HPE_INVALID_STATUS: # <<<<<<<<<<<<<< + * cls = BadStatusLine + * + */ + break; + case HPE_INVALID_METHOD: + + /* "aiohttp/_http_parser.pyx":744 + * + * elif errno == cparser.HPE_INVALID_METHOD: + * 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, 744, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_cls = __pyx_t_1; + __pyx_t_1 = 0; + + /* "aiohttp/_http_parser.pyx":743 + * cls = BadStatusLine + * + * elif errno == cparser.HPE_INVALID_METHOD: # <<<<<<<<<<<<<< + * cls = BadStatusLine + * + */ + break; + case HPE_INVALID_URL: + + /* "aiohttp/_http_parser.pyx":747 + * + * 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, 747, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_cls = __pyx_t_1; + __pyx_t_1 = 0; + + /* "aiohttp/_http_parser.pyx":746 + * cls = BadStatusLine + * + * elif errno == cparser.HPE_INVALID_URL: # <<<<<<<<<<<<<< + * cls = InvalidURLError + * + */ + break; + default: + + /* "aiohttp/_http_parser.pyx":750 + * + * 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, 750, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_cls = __pyx_t_1; + __pyx_t_1 = 0; + break; + } + + /* "aiohttp/_http_parser.pyx":752 + * 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, 752, __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, 752, __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":725 + * + * + * cdef parser_error_from_errno(cparser.http_errno errno): # <<<<<<<<<<<<<< + * cdef bytes desc = cparser.http_errno_description(errno) + * + */ + + /* 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; +} + +/* "aiohttp/_http_parser.pyx":755 + * + * + * def parse_url(url): # <<<<<<<<<<<<<< + * cdef: + * Py_buffer py_buf + */ + +/* Python wrapper */ +static PyObject *__pyx_pw_7aiohttp_12_http_parser_1parse_url(PyObject *__pyx_self, PyObject *__pyx_v_url); /*proto*/ +static PyMethodDef __pyx_mdef_7aiohttp_12_http_parser_1parse_url = {"parse_url", (PyCFunction)__pyx_pw_7aiohttp_12_http_parser_1parse_url, METH_O, 0}; +static PyObject *__pyx_pw_7aiohttp_12_http_parser_1parse_url(PyObject *__pyx_self, PyObject *__pyx_v_url) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("parse_url (wrapper)", 0); + __pyx_r = __pyx_pf_7aiohttp_12_http_parser_parse_url(__pyx_self, ((PyObject *)__pyx_v_url)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf_7aiohttp_12_http_parser_parse_url(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_url) { + Py_buffer __pyx_v_py_buf; + char *__pyx_v_buf_data; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + int __pyx_t_3; + char const *__pyx_t_4; + 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; + __Pyx_RefNannySetupContext("parse_url", 0); + + /* "aiohttp/_http_parser.pyx":760 + * char* buf_data + * + * PyObject_GetBuffer(url, &py_buf, PyBUF_SIMPLE) # <<<<<<<<<<<<<< + * try: + * buf_data = py_buf.buf + */ + __pyx_t_1 = PyObject_GetBuffer(__pyx_v_url, (&__pyx_v_py_buf), PyBUF_SIMPLE); if (unlikely(__pyx_t_1 == ((int)-1))) __PYX_ERR(0, 760, __pyx_L1_error) + + /* "aiohttp/_http_parser.pyx":761 + * + * PyObject_GetBuffer(url, &py_buf, PyBUF_SIMPLE) + * try: # <<<<<<<<<<<<<< + * buf_data = py_buf.buf + * return _parse_url(buf_data, py_buf.len) + */ + /*try:*/ { + + /* "aiohttp/_http_parser.pyx":762 + * PyObject_GetBuffer(url, &py_buf, PyBUF_SIMPLE) + * try: + * buf_data = py_buf.buf # <<<<<<<<<<<<<< + * return _parse_url(buf_data, py_buf.len) + * finally: + */ + __pyx_v_buf_data = ((char *)__pyx_v_py_buf.buf); + + /* "aiohttp/_http_parser.pyx":763 + * try: + * buf_data = py_buf.buf + * return _parse_url(buf_data, py_buf.len) # <<<<<<<<<<<<<< + * finally: + * PyBuffer_Release(&py_buf) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_2 = __pyx_f_7aiohttp_12_http_parser__parse_url(__pyx_v_buf_data, __pyx_v_py_buf.len); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 763, __pyx_L4_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; + goto __pyx_L3_return; + } + + /* "aiohttp/_http_parser.pyx":765 + * return _parse_url(buf_data, py_buf.len) + * finally: + * PyBuffer_Release(&py_buf) # <<<<<<<<<<<<<< + * + * + */ + /*finally:*/ { + __pyx_L4_error:; + /*exception exit:*/{ + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __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_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_8, &__pyx_t_9, &__pyx_t_10); + if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0)) __Pyx_ErrFetch(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7); + __Pyx_XGOTREF(__pyx_t_5); + __Pyx_XGOTREF(__pyx_t_6); + __Pyx_XGOTREF(__pyx_t_7); + __Pyx_XGOTREF(__pyx_t_8); + __Pyx_XGOTREF(__pyx_t_9); + __Pyx_XGOTREF(__pyx_t_10); + __pyx_t_1 = __pyx_lineno; __pyx_t_3 = __pyx_clineno; __pyx_t_4 = __pyx_filename; + { + PyBuffer_Release((&__pyx_v_py_buf)); + } + if (PY_MAJOR_VERSION >= 3) { + __Pyx_XGIVEREF(__pyx_t_8); + __Pyx_XGIVEREF(__pyx_t_9); + __Pyx_XGIVEREF(__pyx_t_10); + __Pyx_ExceptionReset(__pyx_t_8, __pyx_t_9, __pyx_t_10); + } + __Pyx_XGIVEREF(__pyx_t_5); + __Pyx_XGIVEREF(__pyx_t_6); + __Pyx_XGIVEREF(__pyx_t_7); + __Pyx_ErrRestore(__pyx_t_5, __pyx_t_6, __pyx_t_7); + __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_lineno = __pyx_t_1; __pyx_clineno = __pyx_t_3; __pyx_filename = __pyx_t_4; + goto __pyx_L1_error; + } + __pyx_L3_return: { + __pyx_t_10 = __pyx_r; + __pyx_r = 0; + PyBuffer_Release((&__pyx_v_py_buf)); + __pyx_r = __pyx_t_10; + __pyx_t_10 = 0; + goto __pyx_L0; + } + } + + /* "aiohttp/_http_parser.pyx":755 + * + * + * def parse_url(url): # <<<<<<<<<<<<<< + * cdef: + * Py_buffer py_buf + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_AddTraceback("aiohttp._http_parser.parse_url", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "aiohttp/_http_parser.pyx":768 + * + * + * cdef _parse_url(char* buf_data, size_t length): # <<<<<<<<<<<<<< + * cdef: + * cparser.http_parser_url* parsed + */ + +static PyObject *__pyx_f_7aiohttp_12_http_parser__parse_url(char *__pyx_v_buf_data, size_t __pyx_v_length) { + struct http_parser_url *__pyx_v_parsed; + int __pyx_v_res; + PyObject *__pyx_v_schema = 0; + PyObject *__pyx_v_host = 0; + PyObject *__pyx_v_port = 0; + PyObject *__pyx_v_path = 0; + PyObject *__pyx_v_query = 0; + PyObject *__pyx_v_fragment = 0; + PyObject *__pyx_v_user = 0; + PyObject *__pyx_v_password = 0; + PyObject *__pyx_v_userinfo = 0; + CYTHON_UNUSED PyObject *__pyx_v_result = 0; + int __pyx_v_off; + int __pyx_v_ln; + CYTHON_UNUSED PyObject *__pyx_v_sep = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + uint16_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 = NULL; + PyObject *(*__pyx_t_8)(PyObject *); + PyObject *__pyx_t_9 = NULL; + int __pyx_t_10; + int __pyx_t_11; + char const *__pyx_t_12; + 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; + __Pyx_RefNannySetupContext("_parse_url", 0); + + /* "aiohttp/_http_parser.pyx":772 + * cparser.http_parser_url* parsed + * int res + * str schema = None # <<<<<<<<<<<<<< + * str host = None + * object port = None + */ + __Pyx_INCREF(Py_None); + __pyx_v_schema = ((PyObject*)Py_None); + + /* "aiohttp/_http_parser.pyx":773 + * int res + * str schema = None + * str host = None # <<<<<<<<<<<<<< + * object port = None + * str path = None + */ + __Pyx_INCREF(Py_None); + __pyx_v_host = ((PyObject*)Py_None); + + /* "aiohttp/_http_parser.pyx":774 + * str schema = None + * str host = None + * object port = None # <<<<<<<<<<<<<< + * str path = None + * str query = None + */ + __Pyx_INCREF(Py_None); + __pyx_v_port = Py_None; + + /* "aiohttp/_http_parser.pyx":775 + * str host = None + * object port = None + * str path = None # <<<<<<<<<<<<<< + * str query = None + * str fragment = None + */ + __Pyx_INCREF(Py_None); + __pyx_v_path = ((PyObject*)Py_None); + + /* "aiohttp/_http_parser.pyx":776 + * object port = None + * str path = None + * str query = None # <<<<<<<<<<<<<< + * str fragment = None + * str user = None + */ + __Pyx_INCREF(Py_None); + __pyx_v_query = ((PyObject*)Py_None); + + /* "aiohttp/_http_parser.pyx":777 + * str path = None + * str query = None + * str fragment = None # <<<<<<<<<<<<<< + * str user = None + * str password = None + */ + __Pyx_INCREF(Py_None); + __pyx_v_fragment = ((PyObject*)Py_None); + + /* "aiohttp/_http_parser.pyx":778 + * str query = None + * str fragment = None + * str user = None # <<<<<<<<<<<<<< + * str password = None + * str userinfo = None + */ + __Pyx_INCREF(Py_None); + __pyx_v_user = ((PyObject*)Py_None); + + /* "aiohttp/_http_parser.pyx":779 + * str fragment = None + * str user = None + * str password = None # <<<<<<<<<<<<<< + * str userinfo = None + * object result = None + */ + __Pyx_INCREF(Py_None); + __pyx_v_password = ((PyObject*)Py_None); + + /* "aiohttp/_http_parser.pyx":780 + * str user = None + * str password = None + * str userinfo = None # <<<<<<<<<<<<<< + * object result = None + * int off + */ + __Pyx_INCREF(Py_None); + __pyx_v_userinfo = ((PyObject*)Py_None); + + /* "aiohttp/_http_parser.pyx":781 + * str password = None + * str userinfo = None + * object result = None # <<<<<<<<<<<<<< + * int off + * int ln + */ + __Pyx_INCREF(Py_None); + __pyx_v_result = Py_None; + + /* "aiohttp/_http_parser.pyx":785 + * int ln + * + * parsed = \ # <<<<<<<<<<<<<< + * PyMem_Malloc(sizeof(cparser.http_parser_url)) + * if parsed is NULL: + */ + __pyx_v_parsed = ((struct http_parser_url *)PyMem_Malloc((sizeof(struct http_parser_url)))); + + /* "aiohttp/_http_parser.pyx":787 + * parsed = \ + * PyMem_Malloc(sizeof(cparser.http_parser_url)) + * if parsed is NULL: # <<<<<<<<<<<<<< + * raise MemoryError() + * cparser.http_parser_url_init(parsed) + */ + __pyx_t_1 = ((__pyx_v_parsed == NULL) != 0); + if (unlikely(__pyx_t_1)) { + + /* "aiohttp/_http_parser.pyx":788 + * PyMem_Malloc(sizeof(cparser.http_parser_url)) + * if parsed is NULL: + * raise MemoryError() # <<<<<<<<<<<<<< + * cparser.http_parser_url_init(parsed) + * try: + */ + PyErr_NoMemory(); __PYX_ERR(0, 788, __pyx_L1_error) + + /* "aiohttp/_http_parser.pyx":787 + * parsed = \ + * PyMem_Malloc(sizeof(cparser.http_parser_url)) + * if parsed is NULL: # <<<<<<<<<<<<<< + * raise MemoryError() + * cparser.http_parser_url_init(parsed) + */ + } + + /* "aiohttp/_http_parser.pyx":789 + * if parsed is NULL: + * raise MemoryError() + * cparser.http_parser_url_init(parsed) # <<<<<<<<<<<<<< + * try: + * res = cparser.http_parser_parse_url(buf_data, length, 0, parsed) + */ + http_parser_url_init(__pyx_v_parsed); + + /* "aiohttp/_http_parser.pyx":790 + * raise MemoryError() + * cparser.http_parser_url_init(parsed) + * try: # <<<<<<<<<<<<<< + * res = cparser.http_parser_parse_url(buf_data, length, 0, parsed) + * + */ + /*try:*/ { + + /* "aiohttp/_http_parser.pyx":791 + * cparser.http_parser_url_init(parsed) + * try: + * res = cparser.http_parser_parse_url(buf_data, length, 0, parsed) # <<<<<<<<<<<<<< + * + * if res == 0: + */ + __pyx_v_res = http_parser_parse_url(__pyx_v_buf_data, __pyx_v_length, 0, __pyx_v_parsed); + + /* "aiohttp/_http_parser.pyx":793 + * res = cparser.http_parser_parse_url(buf_data, length, 0, parsed) + * + * if res == 0: # <<<<<<<<<<<<<< + * if parsed.field_set & (1 << cparser.UF_SCHEMA): + * off = parsed.field_data[cparser.UF_SCHEMA].off + */ + __pyx_t_1 = ((__pyx_v_res == 0) != 0); + if (likely(__pyx_t_1)) { + + /* "aiohttp/_http_parser.pyx":794 + * + * if res == 0: + * if parsed.field_set & (1 << cparser.UF_SCHEMA): # <<<<<<<<<<<<<< + * off = parsed.field_data[cparser.UF_SCHEMA].off + * ln = parsed.field_data[cparser.UF_SCHEMA].len + */ + __pyx_t_1 = ((__pyx_v_parsed->field_set & (1 << UF_SCHEMA)) != 0); + if (__pyx_t_1) { + + /* "aiohttp/_http_parser.pyx":795 + * if res == 0: + * if parsed.field_set & (1 << cparser.UF_SCHEMA): + * off = parsed.field_data[cparser.UF_SCHEMA].off # <<<<<<<<<<<<<< + * ln = parsed.field_data[cparser.UF_SCHEMA].len + * schema = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') + */ + __pyx_t_2 = (__pyx_v_parsed->field_data[((int)UF_SCHEMA)]).off; + __pyx_v_off = __pyx_t_2; + + /* "aiohttp/_http_parser.pyx":796 + * if parsed.field_set & (1 << cparser.UF_SCHEMA): + * off = parsed.field_data[cparser.UF_SCHEMA].off + * ln = parsed.field_data[cparser.UF_SCHEMA].len # <<<<<<<<<<<<<< + * schema = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') + * else: + */ + __pyx_t_2 = (__pyx_v_parsed->field_data[((int)UF_SCHEMA)]).len; + __pyx_v_ln = __pyx_t_2; + + /* "aiohttp/_http_parser.pyx":797 + * off = parsed.field_data[cparser.UF_SCHEMA].off + * ln = parsed.field_data[cparser.UF_SCHEMA].len + * schema = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') # <<<<<<<<<<<<<< + * else: + * schema = '' + */ + __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_buf_data, __pyx_v_off, (__pyx_v_off + __pyx_v_ln), NULL, ((char const *)"surrogateescape"), PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 797, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF_SET(__pyx_v_schema, ((PyObject*)__pyx_t_3)); + __pyx_t_3 = 0; + + /* "aiohttp/_http_parser.pyx":794 + * + * if res == 0: + * if parsed.field_set & (1 << cparser.UF_SCHEMA): # <<<<<<<<<<<<<< + * off = parsed.field_data[cparser.UF_SCHEMA].off + * ln = parsed.field_data[cparser.UF_SCHEMA].len + */ + goto __pyx_L8; + } + + /* "aiohttp/_http_parser.pyx":799 + * schema = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') + * else: + * schema = '' # <<<<<<<<<<<<<< + * + * if parsed.field_set & (1 << cparser.UF_HOST): + */ + /*else*/ { + __Pyx_INCREF(__pyx_kp_u__4); + __Pyx_DECREF_SET(__pyx_v_schema, __pyx_kp_u__4); + } + __pyx_L8:; + + /* "aiohttp/_http_parser.pyx":801 + * schema = '' + * + * if parsed.field_set & (1 << cparser.UF_HOST): # <<<<<<<<<<<<<< + * off = parsed.field_data[cparser.UF_HOST].off + * ln = parsed.field_data[cparser.UF_HOST].len + */ + __pyx_t_1 = ((__pyx_v_parsed->field_set & (1 << UF_HOST)) != 0); + if (__pyx_t_1) { + + /* "aiohttp/_http_parser.pyx":802 + * + * if parsed.field_set & (1 << cparser.UF_HOST): + * off = parsed.field_data[cparser.UF_HOST].off # <<<<<<<<<<<<<< + * ln = parsed.field_data[cparser.UF_HOST].len + * host = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') + */ + __pyx_t_2 = (__pyx_v_parsed->field_data[((int)UF_HOST)]).off; + __pyx_v_off = __pyx_t_2; + + /* "aiohttp/_http_parser.pyx":803 + * if parsed.field_set & (1 << cparser.UF_HOST): + * off = parsed.field_data[cparser.UF_HOST].off + * ln = parsed.field_data[cparser.UF_HOST].len # <<<<<<<<<<<<<< + * host = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') + * else: + */ + __pyx_t_2 = (__pyx_v_parsed->field_data[((int)UF_HOST)]).len; + __pyx_v_ln = __pyx_t_2; + + /* "aiohttp/_http_parser.pyx":804 + * off = parsed.field_data[cparser.UF_HOST].off + * ln = parsed.field_data[cparser.UF_HOST].len + * host = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') # <<<<<<<<<<<<<< + * else: + * host = '' + */ + __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_buf_data, __pyx_v_off, (__pyx_v_off + __pyx_v_ln), NULL, ((char const *)"surrogateescape"), PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 804, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF_SET(__pyx_v_host, ((PyObject*)__pyx_t_3)); + __pyx_t_3 = 0; + + /* "aiohttp/_http_parser.pyx":801 + * schema = '' + * + * if parsed.field_set & (1 << cparser.UF_HOST): # <<<<<<<<<<<<<< + * off = parsed.field_data[cparser.UF_HOST].off + * ln = parsed.field_data[cparser.UF_HOST].len + */ + goto __pyx_L9; + } + + /* "aiohttp/_http_parser.pyx":806 + * host = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') + * else: + * host = '' # <<<<<<<<<<<<<< + * + * if parsed.field_set & (1 << cparser.UF_PORT): + */ + /*else*/ { + __Pyx_INCREF(__pyx_kp_u__4); + __Pyx_DECREF_SET(__pyx_v_host, __pyx_kp_u__4); + } + __pyx_L9:; + + /* "aiohttp/_http_parser.pyx":808 + * host = '' + * + * if parsed.field_set & (1 << cparser.UF_PORT): # <<<<<<<<<<<<<< + * port = parsed.port + * + */ + __pyx_t_1 = ((__pyx_v_parsed->field_set & (1 << UF_PORT)) != 0); + if (__pyx_t_1) { + + /* "aiohttp/_http_parser.pyx":809 + * + * if parsed.field_set & (1 << cparser.UF_PORT): + * port = parsed.port # <<<<<<<<<<<<<< + * + * if parsed.field_set & (1 << cparser.UF_PATH): + */ + __pyx_t_3 = __Pyx_PyInt_From_uint16_t(__pyx_v_parsed->port); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 809, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF_SET(__pyx_v_port, __pyx_t_3); + __pyx_t_3 = 0; + + /* "aiohttp/_http_parser.pyx":808 + * host = '' + * + * if parsed.field_set & (1 << cparser.UF_PORT): # <<<<<<<<<<<<<< + * port = parsed.port + * + */ + } + + /* "aiohttp/_http_parser.pyx":811 + * port = parsed.port + * + * if parsed.field_set & (1 << cparser.UF_PATH): # <<<<<<<<<<<<<< + * off = parsed.field_data[cparser.UF_PATH].off + * ln = parsed.field_data[cparser.UF_PATH].len + */ + __pyx_t_1 = ((__pyx_v_parsed->field_set & (1 << UF_PATH)) != 0); + if (__pyx_t_1) { + + /* "aiohttp/_http_parser.pyx":812 + * + * if parsed.field_set & (1 << cparser.UF_PATH): + * off = parsed.field_data[cparser.UF_PATH].off # <<<<<<<<<<<<<< + * ln = parsed.field_data[cparser.UF_PATH].len + * path = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') + */ + __pyx_t_2 = (__pyx_v_parsed->field_data[((int)UF_PATH)]).off; + __pyx_v_off = __pyx_t_2; + + /* "aiohttp/_http_parser.pyx":813 + * if parsed.field_set & (1 << cparser.UF_PATH): + * off = parsed.field_data[cparser.UF_PATH].off + * ln = parsed.field_data[cparser.UF_PATH].len # <<<<<<<<<<<<<< + * path = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') + * else: + */ + __pyx_t_2 = (__pyx_v_parsed->field_data[((int)UF_PATH)]).len; + __pyx_v_ln = __pyx_t_2; + + /* "aiohttp/_http_parser.pyx":814 + * off = parsed.field_data[cparser.UF_PATH].off + * ln = parsed.field_data[cparser.UF_PATH].len + * path = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') # <<<<<<<<<<<<<< + * else: + * path = '' + */ + __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_buf_data, __pyx_v_off, (__pyx_v_off + __pyx_v_ln), NULL, ((char const *)"surrogateescape"), PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 814, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF_SET(__pyx_v_path, ((PyObject*)__pyx_t_3)); + __pyx_t_3 = 0; + + /* "aiohttp/_http_parser.pyx":811 + * port = parsed.port + * + * if parsed.field_set & (1 << cparser.UF_PATH): # <<<<<<<<<<<<<< + * off = parsed.field_data[cparser.UF_PATH].off + * ln = parsed.field_data[cparser.UF_PATH].len + */ + goto __pyx_L11; + } + + /* "aiohttp/_http_parser.pyx":816 + * path = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') + * else: + * path = '' # <<<<<<<<<<<<<< + * + * if parsed.field_set & (1 << cparser.UF_QUERY): + */ + /*else*/ { + __Pyx_INCREF(__pyx_kp_u__4); + __Pyx_DECREF_SET(__pyx_v_path, __pyx_kp_u__4); + } + __pyx_L11:; + + /* "aiohttp/_http_parser.pyx":818 + * path = '' + * + * if parsed.field_set & (1 << cparser.UF_QUERY): # <<<<<<<<<<<<<< + * off = parsed.field_data[cparser.UF_QUERY].off + * ln = parsed.field_data[cparser.UF_QUERY].len + */ + __pyx_t_1 = ((__pyx_v_parsed->field_set & (1 << UF_QUERY)) != 0); + if (__pyx_t_1) { + + /* "aiohttp/_http_parser.pyx":819 + * + * if parsed.field_set & (1 << cparser.UF_QUERY): + * off = parsed.field_data[cparser.UF_QUERY].off # <<<<<<<<<<<<<< + * ln = parsed.field_data[cparser.UF_QUERY].len + * query = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') + */ + __pyx_t_2 = (__pyx_v_parsed->field_data[((int)UF_QUERY)]).off; + __pyx_v_off = __pyx_t_2; + + /* "aiohttp/_http_parser.pyx":820 + * if parsed.field_set & (1 << cparser.UF_QUERY): + * off = parsed.field_data[cparser.UF_QUERY].off + * ln = parsed.field_data[cparser.UF_QUERY].len # <<<<<<<<<<<<<< + * query = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') + * else: + */ + __pyx_t_2 = (__pyx_v_parsed->field_data[((int)UF_QUERY)]).len; + __pyx_v_ln = __pyx_t_2; + + /* "aiohttp/_http_parser.pyx":821 + * off = parsed.field_data[cparser.UF_QUERY].off + * ln = parsed.field_data[cparser.UF_QUERY].len + * query = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') # <<<<<<<<<<<<<< + * else: + * query = '' + */ + __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_buf_data, __pyx_v_off, (__pyx_v_off + __pyx_v_ln), NULL, ((char const *)"surrogateescape"), PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 821, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF_SET(__pyx_v_query, ((PyObject*)__pyx_t_3)); + __pyx_t_3 = 0; + + /* "aiohttp/_http_parser.pyx":818 + * path = '' + * + * if parsed.field_set & (1 << cparser.UF_QUERY): # <<<<<<<<<<<<<< + * off = parsed.field_data[cparser.UF_QUERY].off + * ln = parsed.field_data[cparser.UF_QUERY].len + */ + goto __pyx_L12; + } + + /* "aiohttp/_http_parser.pyx":823 + * query = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') + * else: + * query = '' # <<<<<<<<<<<<<< + * + * if parsed.field_set & (1 << cparser.UF_FRAGMENT): + */ + /*else*/ { + __Pyx_INCREF(__pyx_kp_u__4); + __Pyx_DECREF_SET(__pyx_v_query, __pyx_kp_u__4); + } + __pyx_L12:; + + /* "aiohttp/_http_parser.pyx":825 + * query = '' + * + * if parsed.field_set & (1 << cparser.UF_FRAGMENT): # <<<<<<<<<<<<<< + * off = parsed.field_data[cparser.UF_FRAGMENT].off + * ln = parsed.field_data[cparser.UF_FRAGMENT].len + */ + __pyx_t_1 = ((__pyx_v_parsed->field_set & (1 << UF_FRAGMENT)) != 0); + if (__pyx_t_1) { + + /* "aiohttp/_http_parser.pyx":826 + * + * if parsed.field_set & (1 << cparser.UF_FRAGMENT): + * off = parsed.field_data[cparser.UF_FRAGMENT].off # <<<<<<<<<<<<<< + * ln = parsed.field_data[cparser.UF_FRAGMENT].len + * fragment = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') + */ + __pyx_t_2 = (__pyx_v_parsed->field_data[((int)UF_FRAGMENT)]).off; + __pyx_v_off = __pyx_t_2; + + /* "aiohttp/_http_parser.pyx":827 + * if parsed.field_set & (1 << cparser.UF_FRAGMENT): + * off = parsed.field_data[cparser.UF_FRAGMENT].off + * ln = parsed.field_data[cparser.UF_FRAGMENT].len # <<<<<<<<<<<<<< + * fragment = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') + * else: + */ + __pyx_t_2 = (__pyx_v_parsed->field_data[((int)UF_FRAGMENT)]).len; + __pyx_v_ln = __pyx_t_2; + + /* "aiohttp/_http_parser.pyx":828 + * off = parsed.field_data[cparser.UF_FRAGMENT].off + * ln = parsed.field_data[cparser.UF_FRAGMENT].len + * fragment = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') # <<<<<<<<<<<<<< + * else: + * fragment = '' + */ + __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_buf_data, __pyx_v_off, (__pyx_v_off + __pyx_v_ln), NULL, ((char const *)"surrogateescape"), PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 828, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF_SET(__pyx_v_fragment, ((PyObject*)__pyx_t_3)); + __pyx_t_3 = 0; + + /* "aiohttp/_http_parser.pyx":825 + * query = '' + * + * if parsed.field_set & (1 << cparser.UF_FRAGMENT): # <<<<<<<<<<<<<< + * off = parsed.field_data[cparser.UF_FRAGMENT].off + * ln = parsed.field_data[cparser.UF_FRAGMENT].len + */ + goto __pyx_L13; + } + + /* "aiohttp/_http_parser.pyx":830 + * fragment = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') + * else: + * fragment = '' # <<<<<<<<<<<<<< + * + * if parsed.field_set & (1 << cparser.UF_USERINFO): + */ + /*else*/ { + __Pyx_INCREF(__pyx_kp_u__4); + __Pyx_DECREF_SET(__pyx_v_fragment, __pyx_kp_u__4); + } + __pyx_L13:; + + /* "aiohttp/_http_parser.pyx":832 + * fragment = '' + * + * if parsed.field_set & (1 << cparser.UF_USERINFO): # <<<<<<<<<<<<<< + * off = parsed.field_data[cparser.UF_USERINFO].off + * ln = parsed.field_data[cparser.UF_USERINFO].len + */ + __pyx_t_1 = ((__pyx_v_parsed->field_set & (1 << UF_USERINFO)) != 0); + if (__pyx_t_1) { + + /* "aiohttp/_http_parser.pyx":833 + * + * if parsed.field_set & (1 << cparser.UF_USERINFO): + * off = parsed.field_data[cparser.UF_USERINFO].off # <<<<<<<<<<<<<< + * ln = parsed.field_data[cparser.UF_USERINFO].len + * userinfo = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') + */ + __pyx_t_2 = (__pyx_v_parsed->field_data[((int)UF_USERINFO)]).off; + __pyx_v_off = __pyx_t_2; + + /* "aiohttp/_http_parser.pyx":834 + * if parsed.field_set & (1 << cparser.UF_USERINFO): + * off = parsed.field_data[cparser.UF_USERINFO].off + * ln = parsed.field_data[cparser.UF_USERINFO].len # <<<<<<<<<<<<<< + * userinfo = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') + * + */ + __pyx_t_2 = (__pyx_v_parsed->field_data[((int)UF_USERINFO)]).len; + __pyx_v_ln = __pyx_t_2; + + /* "aiohttp/_http_parser.pyx":835 + * off = parsed.field_data[cparser.UF_USERINFO].off + * ln = parsed.field_data[cparser.UF_USERINFO].len + * userinfo = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') # <<<<<<<<<<<<<< + * + * user, sep, password = userinfo.partition(':') + */ + __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_buf_data, __pyx_v_off, (__pyx_v_off + __pyx_v_ln), NULL, ((char const *)"surrogateescape"), PyUnicode_DecodeUTF8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 835, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF_SET(__pyx_v_userinfo, ((PyObject*)__pyx_t_3)); + __pyx_t_3 = 0; + + /* "aiohttp/_http_parser.pyx":837 + * userinfo = buf_data[off:off+ln].decode('utf-8', 'surrogateescape') + * + * user, sep, password = userinfo.partition(':') # <<<<<<<<<<<<<< + * + * return URL_build(scheme=schema, + */ + __pyx_t_3 = __Pyx_CallUnboundCMethod1(&__pyx_umethod_PyUnicode_Type_partition, __pyx_v_userinfo, __pyx_kp_u__11); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 837, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_3); + 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 != 3)) { + if (size > 3) __Pyx_RaiseTooManyValuesError(3); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 837, __pyx_L5_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); + __pyx_t_6 = PyTuple_GET_ITEM(sequence, 2); + } else { + __pyx_t_4 = PyList_GET_ITEM(sequence, 0); + __pyx_t_5 = PyList_GET_ITEM(sequence, 1); + __pyx_t_6 = PyList_GET_ITEM(sequence, 2); + } + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(__pyx_t_6); + #else + __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 837, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 837, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PySequence_ITEM(sequence, 2); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 837, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_6); + #endif + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_7 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 837, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_8 = Py_TYPE(__pyx_t_7)->tp_iternext; + index = 0; __pyx_t_4 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_4)) goto __pyx_L15_unpacking_failed; + __Pyx_GOTREF(__pyx_t_4); + index = 1; __pyx_t_5 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_5)) goto __pyx_L15_unpacking_failed; + __Pyx_GOTREF(__pyx_t_5); + index = 2; __pyx_t_6 = __pyx_t_8(__pyx_t_7); if (unlikely(!__pyx_t_6)) goto __pyx_L15_unpacking_failed; + __Pyx_GOTREF(__pyx_t_6); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_8(__pyx_t_7), 3) < 0) __PYX_ERR(0, 837, __pyx_L5_error) + __pyx_t_8 = NULL; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + goto __pyx_L16_unpacking_done; + __pyx_L15_unpacking_failed:; + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_8 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 837, __pyx_L5_error) + __pyx_L16_unpacking_done:; + } + if (!(likely(PyUnicode_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "unicode", Py_TYPE(__pyx_t_4)->tp_name), 0))) __PYX_ERR(0, 837, __pyx_L5_error) + if (!(likely(PyUnicode_CheckExact(__pyx_t_6))||((__pyx_t_6) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "unicode", Py_TYPE(__pyx_t_6)->tp_name), 0))) __PYX_ERR(0, 837, __pyx_L5_error) + __Pyx_DECREF_SET(__pyx_v_user, ((PyObject*)__pyx_t_4)); + __pyx_t_4 = 0; + __pyx_v_sep = __pyx_t_5; + __pyx_t_5 = 0; + __Pyx_DECREF_SET(__pyx_v_password, ((PyObject*)__pyx_t_6)); + __pyx_t_6 = 0; + + /* "aiohttp/_http_parser.pyx":832 + * fragment = '' + * + * if parsed.field_set & (1 << cparser.UF_USERINFO): # <<<<<<<<<<<<<< + * off = parsed.field_data[cparser.UF_USERINFO].off + * ln = parsed.field_data[cparser.UF_USERINFO].len + */ + } + + /* "aiohttp/_http_parser.pyx":839 + * user, sep, password = userinfo.partition(':') + * + * return URL_build(scheme=schema, # <<<<<<<<<<<<<< + * user=user, password=password, host=host, port=port, + * path=path, query=query, fragment=fragment) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = __Pyx_PyDict_NewPresized(8); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 839, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_scheme, __pyx_v_schema) < 0) __PYX_ERR(0, 839, __pyx_L5_error) + + /* "aiohttp/_http_parser.pyx":840 + * + * return URL_build(scheme=schema, + * user=user, password=password, host=host, port=port, # <<<<<<<<<<<<<< + * path=path, query=query, fragment=fragment) + * else: + */ + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_user, __pyx_v_user) < 0) __PYX_ERR(0, 839, __pyx_L5_error) + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_password, __pyx_v_password) < 0) __PYX_ERR(0, 839, __pyx_L5_error) + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_host, __pyx_v_host) < 0) __PYX_ERR(0, 839, __pyx_L5_error) + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_port, __pyx_v_port) < 0) __PYX_ERR(0, 839, __pyx_L5_error) + + /* "aiohttp/_http_parser.pyx":841 + * return URL_build(scheme=schema, + * user=user, password=password, host=host, port=port, + * path=path, query=query, fragment=fragment) # <<<<<<<<<<<<<< + * else: + * raise InvalidURLError("invalid url {!r}".format(buf_data)) + */ + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_path, __pyx_v_path) < 0) __PYX_ERR(0, 839, __pyx_L5_error) + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_query, __pyx_v_query) < 0) __PYX_ERR(0, 839, __pyx_L5_error) + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_fragment, __pyx_v_fragment) < 0) __PYX_ERR(0, 839, __pyx_L5_error) + + /* "aiohttp/_http_parser.pyx":839 + * user, sep, password = userinfo.partition(':') + * + * return URL_build(scheme=schema, # <<<<<<<<<<<<<< + * user=user, password=password, host=host, port=port, + * path=path, query=query, fragment=fragment) + */ + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_v_7aiohttp_12_http_parser_URL_build, __pyx_empty_tuple, __pyx_t_3); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 839, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_6; + __pyx_t_6 = 0; + goto __pyx_L4_return; + + /* "aiohttp/_http_parser.pyx":793 + * res = cparser.http_parser_parse_url(buf_data, length, 0, parsed) + * + * if res == 0: # <<<<<<<<<<<<<< + * if parsed.field_set & (1 << cparser.UF_SCHEMA): + * off = parsed.field_data[cparser.UF_SCHEMA].off + */ + } + + /* "aiohttp/_http_parser.pyx":843 + * path=path, query=query, fragment=fragment) + * else: + * raise InvalidURLError("invalid url {!r}".format(buf_data)) # <<<<<<<<<<<<<< + * finally: + * PyMem_Free(parsed) + */ + /*else*/ { + __Pyx_GetModuleGlobalName(__pyx_t_3, __pyx_n_s_InvalidURLError); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 843, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_kp_u_invalid_url_r, __pyx_n_s_format); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 843, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_7 = __Pyx_PyBytes_FromString(__pyx_v_buf_data); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 843, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_7); + __pyx_t_9 = NULL; + if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_4))) { + __pyx_t_9 = PyMethod_GET_SELF(__pyx_t_4); + if (likely(__pyx_t_9)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); + __Pyx_INCREF(__pyx_t_9); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_4, function); + } + } + __pyx_t_5 = (__pyx_t_9) ? __Pyx_PyObject_Call2Args(__pyx_t_4, __pyx_t_9, __pyx_t_7) : __Pyx_PyObject_CallOneArg(__pyx_t_4, __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_5)) __PYX_ERR(0, 843, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __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_6 = (__pyx_t_4) ? __Pyx_PyObject_Call2Args(__pyx_t_3, __pyx_t_4, __pyx_t_5) : __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_5); + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 843, __pyx_L5_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_Raise(__pyx_t_6, 0, 0, 0); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __PYX_ERR(0, 843, __pyx_L5_error) + } + } + + /* "aiohttp/_http_parser.pyx":845 + * raise InvalidURLError("invalid url {!r}".format(buf_data)) + * finally: + * PyMem_Free(parsed) # <<<<<<<<<<<<<< + */ + /*finally:*/ { + __pyx_L5_error:; + /*exception exit:*/{ + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __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_XDECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_16, &__pyx_t_17, &__pyx_t_18); + if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_13, &__pyx_t_14, &__pyx_t_15) < 0)) __Pyx_ErrFetch(&__pyx_t_13, &__pyx_t_14, &__pyx_t_15); + __Pyx_XGOTREF(__pyx_t_13); + __Pyx_XGOTREF(__pyx_t_14); + __Pyx_XGOTREF(__pyx_t_15); + __Pyx_XGOTREF(__pyx_t_16); + __Pyx_XGOTREF(__pyx_t_17); + __Pyx_XGOTREF(__pyx_t_18); + __pyx_t_10 = __pyx_lineno; __pyx_t_11 = __pyx_clineno; __pyx_t_12 = __pyx_filename; + { + PyMem_Free(__pyx_v_parsed); + } + if (PY_MAJOR_VERSION >= 3) { + __Pyx_XGIVEREF(__pyx_t_16); + __Pyx_XGIVEREF(__pyx_t_17); + __Pyx_XGIVEREF(__pyx_t_18); + __Pyx_ExceptionReset(__pyx_t_16, __pyx_t_17, __pyx_t_18); + } + __Pyx_XGIVEREF(__pyx_t_13); + __Pyx_XGIVEREF(__pyx_t_14); + __Pyx_XGIVEREF(__pyx_t_15); + __Pyx_ErrRestore(__pyx_t_13, __pyx_t_14, __pyx_t_15); + __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_lineno = __pyx_t_10; __pyx_clineno = __pyx_t_11; __pyx_filename = __pyx_t_12; + goto __pyx_L1_error; + } + __pyx_L4_return: { + __pyx_t_18 = __pyx_r; + __pyx_r = 0; + PyMem_Free(__pyx_v_parsed); + __pyx_r = __pyx_t_18; + __pyx_t_18 = 0; + goto __pyx_L0; + } + } + + /* "aiohttp/_http_parser.pyx":768 + * + * + * cdef _parse_url(char* buf_data, size_t length): # <<<<<<<<<<<<<< + * cdef: + * cparser.http_parser_url* parsed + */ + + /* 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._parse_url", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_schema); + __Pyx_XDECREF(__pyx_v_host); + __Pyx_XDECREF(__pyx_v_port); + __Pyx_XDECREF(__pyx_v_path); + __Pyx_XDECREF(__pyx_v_query); + __Pyx_XDECREF(__pyx_v_fragment); + __Pyx_XDECREF(__pyx_v_user); + __Pyx_XDECREF(__pyx_v_password); + __Pyx_XDECREF(__pyx_v_userinfo); + __Pyx_XDECREF(__pyx_v_result); + __Pyx_XDECREF(__pyx_v_sep); + __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_3__pyx_unpickle_RawRequestMessage(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyMethodDef __pyx_mdef_7aiohttp_12_http_parser_3__pyx_unpickle_RawRequestMessage = {"__pyx_unpickle_RawRequestMessage", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_7aiohttp_12_http_parser_3__pyx_unpickle_RawRequestMessage, METH_VARARGS|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_7aiohttp_12_http_parser_3__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; + 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_2__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_2__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; + __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; + __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_5__pyx_unpickle_RawResponseMessage(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyMethodDef __pyx_mdef_7aiohttp_12_http_parser_5__pyx_unpickle_RawResponseMessage = {"__pyx_unpickle_RawResponseMessage", (PyCFunction)(void*)(PyCFunctionWithKeywords)__pyx_pw_7aiohttp_12_http_parser_5__pyx_unpickle_RawResponseMessage, METH_VARARGS|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_7aiohttp_12_http_parser_5__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; + 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_4__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_4__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; + __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; + __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*/ + 0, /*tp_print*/ + 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 +}; + +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*/ + 0, /*tp_print*/ + 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 +}; +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); + ++Py_REFCNT(o); + __pyx_pw_7aiohttp_12_http_parser_10HttpParser_3__dealloc__(o); + --Py_REFCNT(o); + 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->_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}, + {"__reduce_cython__", (PyCFunction)__pyx_pw_7aiohttp_12_http_parser_10HttpParser_9__reduce_cython__, METH_NOARGS, 0}, + {"__setstate_cython__", (PyCFunction)__pyx_pw_7aiohttp_12_http_parser_10HttpParser_11__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*/ + 0, /*tp_print*/ + 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 +}; +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*/ + 0, /*tp_print*/ + 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 +}; +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*/ + 0, /*tp_print*/ + 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 +}; + +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); } - if (p->_timer) { - e = (*v)(p->_timer, a); if (e) return e; +} + +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; } - if (p->_url) { - e = (*v)(p->_url, 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*/ + 0, /*tp_print*/ + 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 +}; + +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*/ + 0, /*tp_print*/ + 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 +}; + +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*/ + 0, /*tp_print*/ + 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 +}; + +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; } - if (p->_headers) { - e = (*v)(p->_headers, a); if (e) return e; + 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); } - if (p->_raw_headers) { - e = (*v)(p->_raw_headers, a); if (e) return e; +} + +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->_messages) { - e = (*v)(p->_messages, a); if (e) return e; + if (p->__pyx_v_name) { + e = (*v)(p->__pyx_v_name, a); if (e) return e; } - if (p->_payload) { - e = (*v)(p->_payload, a); if (e) return e; + if (p->__pyx_v_val) { + e = (*v)(p->__pyx_v_val, a); if (e) return e; } - if (p->_payload_exception) { - e = (*v)(p->_payload_exception, 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*/ + 0, /*tp_print*/ + 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 +}; + +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_WEBSOCKET, __pyx_k_WEBSOCKET, sizeof(__pyx_k_WEBSOCKET), 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__11, __pyx_k__11, sizeof(__pyx_k__11), 0, 1, 0, 0}, + {&__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_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_kp_s_aiohttp__http_parser_pyx, __pyx_k_aiohttp__http_parser_pyx, sizeof(__pyx_k_aiohttp__http_parser_pyx), 0, 0, 1, 0}, + {&__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_buf_data, __pyx_k_buf_data, sizeof(__pyx_k_buf_data), 0, 0, 1, 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_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_format, __pyx_k_format, sizeof(__pyx_k_format), 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_host, __pyx_k_host, sizeof(__pyx_k_host), 0, 0, 1, 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_kp_u_invalid_url_r, __pyx_k_invalid_url_r, sizeof(__pyx_k_invalid_url_r), 0, 1, 0, 0}, + {&__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_parse_url, __pyx_k_parse_url, sizeof(__pyx_k_parse_url), 0, 0, 1, 1}, + {&__pyx_n_s_partition, __pyx_k_partition, sizeof(__pyx_k_partition), 0, 0, 1, 1}, + {&__pyx_n_s_password, __pyx_k_password, sizeof(__pyx_k_password), 0, 0, 1, 1}, + {&__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_port, __pyx_k_port, sizeof(__pyx_k_port), 0, 0, 1, 1}, + {&__pyx_n_s_protocol, __pyx_k_protocol, sizeof(__pyx_k_protocol), 0, 0, 1, 1}, + {&__pyx_n_s_py_buf, __pyx_k_py_buf, sizeof(__pyx_k_py_buf), 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, __pyx_k_query, sizeof(__pyx_k_query), 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_scheme, __pyx_k_scheme, sizeof(__pyx_k_scheme), 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_user, __pyx_k_user, sizeof(__pyx_k_user), 0, 0, 1, 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, 70, __pyx_L1_error) + __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) __PYX_ERR(0, 297, __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, 601, __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__7 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__7)) __PYX_ERR(1, 2, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__7); + __Pyx_GIVEREF(__pyx_tuple__7); + + /* "(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__8 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__8); + __Pyx_GIVEREF(__pyx_tuple__8); + + /* "(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); + + /* "aiohttp/_http_parser.pyx":40 + * char* PyByteArray_AsString(object) + * + * __all__ = ('HttpRequestParser', 'HttpResponseParser', # <<<<<<<<<<<<<< + * 'RawRequestMessage', 'RawResponseMessage') + * + */ + __pyx_tuple__12 = 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__12)) __PYX_ERR(0, 40, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__12); + __Pyx_GIVEREF(__pyx_tuple__12); + + /* "aiohttp/_http_parser.pyx":755 + * + * + * def parse_url(url): # <<<<<<<<<<<<<< + * cdef: + * Py_buffer py_buf + */ + __pyx_tuple__13 = PyTuple_Pack(3, __pyx_n_s_url, __pyx_n_s_py_buf, __pyx_n_s_buf_data); if (unlikely(!__pyx_tuple__13)) __PYX_ERR(0, 755, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__13); + __Pyx_GIVEREF(__pyx_tuple__13); + __pyx_codeobj__14 = (PyObject*)__Pyx_PyCode_New(1, 0, 3, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__13, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_aiohttp__http_parser_pyx, __pyx_n_s_parse_url, 755, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__14)) __PYX_ERR(0, 755, __pyx_L1_error) + + /* "(tree fragment)":1 + * def __pyx_unpickle_RawRequestMessage(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< + * cdef object __pyx_PickleError + * cdef object __pyx_result + */ + __pyx_tuple__15 = 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__15)) __PYX_ERR(1, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__15); + __Pyx_GIVEREF(__pyx_tuple__15); + __pyx_codeobj__16 = (PyObject*)__Pyx_PyCode_New(3, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__15, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_stringsource, __pyx_n_s_pyx_unpickle_RawRequestMessage, 1, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__16)) __PYX_ERR(1, 1, __pyx_L1_error) + __pyx_tuple__17 = 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__17)) __PYX_ERR(1, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__17); + __Pyx_GIVEREF(__pyx_tuple__17); + __pyx_codeobj__18 = (PyObject*)__Pyx_PyCode_New(3, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__17, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_stringsource, __pyx_n_s_pyx_unpickle_RawResponseMessag, 1, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__18)) __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) { + __pyx_umethod_PyUnicode_Type_partition.type = (PyObject*)&PyUnicode_Type; + 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 + __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, 93, __pyx_L1_error) + __pyx_type_7aiohttp_12_http_parser_RawRequestMessage.tp_print = 0; + 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, 93, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject*)&__pyx_type_7aiohttp_12_http_parser_RawRequestMessage) < 0) __PYX_ERR(0, 93, __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, 193, __pyx_L1_error) + __pyx_type_7aiohttp_12_http_parser_RawResponseMessage.tp_print = 0; + 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, 193, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject*)&__pyx_type_7aiohttp_12_http_parser_RawResponseMessage) < 0) __PYX_ERR(0, 193, __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 http_parser_type, PyObject *, PyObject *, 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, 255, __pyx_L1_error) + __pyx_type_7aiohttp_12_http_parser_HttpParser.tp_print = 0; + 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 (p->_last_error) { - e = (*v)(p->_last_error, a); if (e) return e; + if (__Pyx_SetVtable(__pyx_type_7aiohttp_12_http_parser_HttpParser.tp_dict, __pyx_vtabptr_7aiohttp_12_http_parser_HttpParser) < 0) __PYX_ERR(0, 255, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject*)&__pyx_type_7aiohttp_12_http_parser_HttpParser) < 0) __PYX_ERR(0, 255, __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, 537, __pyx_L1_error) + __pyx_type_7aiohttp_12_http_parser_HttpRequestParser.tp_print = 0; + 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, 537, __pyx_L1_error) + if (PyObject_SetAttr(__pyx_m, __pyx_n_s_HttpRequestParser, (PyObject *)&__pyx_type_7aiohttp_12_http_parser_HttpRequestParser) < 0) __PYX_ERR(0, 537, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject*)&__pyx_type_7aiohttp_12_http_parser_HttpRequestParser) < 0) __PYX_ERR(0, 537, __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, 564, __pyx_L1_error) + __pyx_type_7aiohttp_12_http_parser_HttpResponseParser.tp_print = 0; + 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, 564, __pyx_L1_error) + if (PyObject_SetAttr(__pyx_m, __pyx_n_s_HttpResponseParser, (PyObject *)&__pyx_type_7aiohttp_12_http_parser_HttpResponseParser) < 0) __PYX_ERR(0, 564, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject*)&__pyx_type_7aiohttp_12_http_parser_HttpResponseParser) < 0) __PYX_ERR(0, 564, __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, 118, __pyx_L1_error) + __pyx_type_7aiohttp_12_http_parser___pyx_scope_struct____repr__.tp_print = 0; + 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, 130, __pyx_L1_error) + __pyx_type_7aiohttp_12_http_parser___pyx_scope_struct_1_genexpr.tp_print = 0; + 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, 216, __pyx_L1_error) + __pyx_type_7aiohttp_12_http_parser___pyx_scope_struct_2___repr__.tp_print = 0; + 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, 227, __pyx_L1_error) + __pyx_type_7aiohttp_12_http_parser___pyx_scope_struct_3_genexpr.tp_print = 0; + 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; } - if (p->py_buf.obj) { - e = (*v)(p->py_buf.obj, a); if (e) return e; + __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; + __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; +} + + +#if PY_MAJOR_VERSION < 3 +#ifdef CYTHON_NO_PYINIT_EXPORT +#define __Pyx_PyMODINIT_FUNC void +#else +#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC +#endif +#else +#ifdef CYTHON_NO_PYINIT_EXPORT +#define __Pyx_PyMODINIT_FUNC PyObject * +#else +#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC +#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; + PyObject *__pyx_t_79 = NULL; + long __pyx_t_80; + enum http_method __pyx_t_81; + char const *__pyx_t_82; + int __pyx_t_83; + __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; } - return 0; + #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(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + #ifdef WITH_THREAD /* Python build with threading support? */ + PyEval_InitThreads(); + #endif + #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) + __pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); + #endif + 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)) goto __pyx_L1_error; + if (unlikely(__Pyx_modinit_type_import_code() != 0)) goto __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":11 + * Py_buffer, PyBytes_AsString, PyBytes_AsStringAndSize) + * + * 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, 11, __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, 11, __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, 11, __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, 11, __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, 11, __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, 12, __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":13 + * 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, 13, __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, 13, __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, 13, __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, 13, __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":15 + * from yarl import URL as _URL + * + * from aiohttp import hdrs # <<<<<<<<<<<<<< + * from .http_exceptions import ( + * BadHttpMessage, BadStatusLine, InvalidHeader, LineTooLong, InvalidURLError, + */ + __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 15, __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, 15, __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, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_hdrs, __pyx_t_1) < 0) __PYX_ERR(0, 15, __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":17 + * from aiohttp import hdrs + * from .http_exceptions import ( + * BadHttpMessage, BadStatusLine, InvalidHeader, LineTooLong, InvalidURLError, # <<<<<<<<<<<<<< + * PayloadEncodingError, ContentLengthError, TransferEncodingError) + * from .http_writer import (HttpVersion as _HttpVersion, + */ + __pyx_t_2 = PyList_New(8); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 17, __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_InvalidHeader); + __Pyx_GIVEREF(__pyx_n_s_InvalidHeader); + PyList_SET_ITEM(__pyx_t_2, 2, __pyx_n_s_InvalidHeader); + __Pyx_INCREF(__pyx_n_s_LineTooLong); + __Pyx_GIVEREF(__pyx_n_s_LineTooLong); + PyList_SET_ITEM(__pyx_t_2, 3, __pyx_n_s_LineTooLong); + __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_PayloadEncodingError); + __Pyx_GIVEREF(__pyx_n_s_PayloadEncodingError); + PyList_SET_ITEM(__pyx_t_2, 5, __pyx_n_s_PayloadEncodingError); + __Pyx_INCREF(__pyx_n_s_ContentLengthError); + __Pyx_GIVEREF(__pyx_n_s_ContentLengthError); + PyList_SET_ITEM(__pyx_t_2, 6, __pyx_n_s_ContentLengthError); + __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":16 + * + * from aiohttp import hdrs + * from .http_exceptions import ( # <<<<<<<<<<<<<< + * BadHttpMessage, BadStatusLine, InvalidHeader, LineTooLong, InvalidURLError, + * PayloadEncodingError, ContentLengthError, TransferEncodingError) + */ + __pyx_t_1 = __Pyx_Import(__pyx_n_s_http_exceptions, __pyx_t_2, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 16, __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, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_BadHttpMessage, __pyx_t_2) < 0) __PYX_ERR(0, 17, __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, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_BadStatusLine, __pyx_t_2) < 0) __PYX_ERR(0, 17, __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, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_InvalidHeader, __pyx_t_2) < 0) __PYX_ERR(0, 17, __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, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_LineTooLong, __pyx_t_2) < 0) __PYX_ERR(0, 17, __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, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_InvalidURLError, __pyx_t_2) < 0) __PYX_ERR(0, 17, __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, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_PayloadEncodingError, __pyx_t_2) < 0) __PYX_ERR(0, 18, __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, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_ContentLengthError, __pyx_t_2) < 0) __PYX_ERR(0, 18, __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, 16, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_TransferEncodingError, __pyx_t_2) < 0) __PYX_ERR(0, 18, __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":19 + * BadHttpMessage, BadStatusLine, InvalidHeader, LineTooLong, InvalidURLError, + * PayloadEncodingError, ContentLengthError, TransferEncodingError) + * from .http_writer import (HttpVersion as _HttpVersion, # <<<<<<<<<<<<<< + * HttpVersion10 as _HttpVersion10, + * HttpVersion11 as _HttpVersion11) + */ + __pyx_t_1 = PyList_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 19, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_n_s_HttpVersion); + __Pyx_GIVEREF(__pyx_n_s_HttpVersion); + PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_HttpVersion); + __Pyx_INCREF(__pyx_n_s_HttpVersion10); + __Pyx_GIVEREF(__pyx_n_s_HttpVersion10); + PyList_SET_ITEM(__pyx_t_1, 1, __pyx_n_s_HttpVersion10); + __Pyx_INCREF(__pyx_n_s_HttpVersion11); + __Pyx_GIVEREF(__pyx_n_s_HttpVersion11); + PyList_SET_ITEM(__pyx_t_1, 2, __pyx_n_s_HttpVersion11); + __pyx_t_2 = __Pyx_Import(__pyx_n_s_http_writer, __pyx_t_1, 1); 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_HttpVersion); 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_HttpVersion_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_HttpVersion10); 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_HttpVersion10_2, __pyx_t_1) < 0) __PYX_ERR(0, 20, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_HttpVersion11); 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_HttpVersion11_2, __pyx_t_1) < 0) __PYX_ERR(0, 21, __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":22 + * HttpVersion10 as _HttpVersion10, + * HttpVersion11 as _HttpVersion11) + * from .http_parser import DeflateBuffer as _DeflateBuffer # <<<<<<<<<<<<<< + * from .streams import (EMPTY_PAYLOAD as _EMPTY_PAYLOAD, + * StreamReader as _StreamReader) + */ + __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 22, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_n_s_DeflateBuffer); + __Pyx_GIVEREF(__pyx_n_s_DeflateBuffer); + PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_DeflateBuffer); + __pyx_t_1 = __Pyx_Import(__pyx_n_s_http_parser, __pyx_t_2, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 22, __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_DeflateBuffer); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 22, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_DeflateBuffer_2, __pyx_t_2) < 0) __PYX_ERR(0, 22, __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":23 + * HttpVersion11 as _HttpVersion11) + * from .http_parser import DeflateBuffer as _DeflateBuffer + * from .streams import (EMPTY_PAYLOAD as _EMPTY_PAYLOAD, # <<<<<<<<<<<<<< + * StreamReader as _StreamReader) + * + */ + __pyx_t_1 = PyList_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 23, __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, 23, __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, 23, __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, 23, __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, 23, __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, 24, __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; -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 = ((PyObject*)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; -} + /* "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; -static PyMethodDef __pyx_methods_7aiohttp_12_http_parser_HttpParser[] = { - {"http_version", (PyCFunction)__pyx_pw_7aiohttp_12_http_parser_10HttpParser_5http_version, METH_NOARGS, 0}, - {"feed_eof", (PyCFunction)__pyx_pw_7aiohttp_12_http_parser_10HttpParser_7feed_eof, METH_NOARGS, 0}, - {"feed_data", (PyCFunction)__pyx_pw_7aiohttp_12_http_parser_10HttpParser_9feed_data, 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} -}; + /* "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; -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*/ - 0, /*tp_print*/ - 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 -}; -static struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpRequestParserC __pyx_vtable_7aiohttp_12_http_parser_HttpRequestParserC; + /* "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; -static PyObject *__pyx_tp_new_7aiohttp_12_http_parser_HttpRequestParserC(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParserC *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_HttpRequestParserC *)o); - p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser*)__pyx_vtabptr_7aiohttp_12_http_parser_HttpRequestParserC; - return o; -} + /* "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; -static PyMethodDef __pyx_methods_7aiohttp_12_http_parser_HttpRequestParserC[] = { - {"__reduce_cython__", (PyCFunction)__pyx_pw_7aiohttp_12_http_parser_18HttpRequestParserC_3__reduce_cython__, METH_NOARGS, 0}, - {"__setstate_cython__", (PyCFunction)__pyx_pw_7aiohttp_12_http_parser_18HttpRequestParserC_5__setstate_cython__, METH_O, 0}, - {0, 0, 0, 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; -static PyTypeObject __pyx_type_7aiohttp_12_http_parser_HttpRequestParserC = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._http_parser.HttpRequestParserC", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_12_http_parser_HttpRequestParserC), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_12_http_parser_HttpParser, /*tp_dealloc*/ - 0, /*tp_print*/ - 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_HttpRequestParserC, /*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_18HttpRequestParserC_1__init__, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_12_http_parser_HttpRequestParserC, /*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 -}; -static struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpResponseParserC __pyx_vtable_7aiohttp_12_http_parser_HttpResponseParserC; + /* "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; -static PyObject *__pyx_tp_new_7aiohttp_12_http_parser_HttpResponseParserC(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParserC *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_HttpResponseParserC *)o); - p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_7aiohttp_12_http_parser_HttpParser*)__pyx_vtabptr_7aiohttp_12_http_parser_HttpResponseParserC; - return o; -} + /* "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; -static PyMethodDef __pyx_methods_7aiohttp_12_http_parser_HttpResponseParserC[] = { - {"__reduce_cython__", (PyCFunction)__pyx_pw_7aiohttp_12_http_parser_19HttpResponseParserC_3__reduce_cython__, METH_NOARGS, 0}, - {"__setstate_cython__", (PyCFunction)__pyx_pw_7aiohttp_12_http_parser_19HttpResponseParserC_5__setstate_cython__, METH_O, 0}, - {0, 0, 0, 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; -static PyTypeObject __pyx_type_7aiohttp_12_http_parser_HttpResponseParserC = { - PyVarObject_HEAD_INIT(0, 0) - "aiohttp._http_parser.HttpResponseParserC", /*tp_name*/ - sizeof(struct __pyx_obj_7aiohttp_12_http_parser_HttpResponseParserC), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - __pyx_tp_dealloc_7aiohttp_12_http_parser_HttpParser, /*tp_dealloc*/ - 0, /*tp_print*/ - 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_HttpResponseParserC, /*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_19HttpResponseParserC_1__init__, /*tp_init*/ - 0, /*tp_alloc*/ - __pyx_tp_new_7aiohttp_12_http_parser_HttpResponseParserC, /*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 -}; + /* "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; -static PyMethodDef __pyx_methods[] = { - {0, 0, 0, 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; -#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 + /* "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; -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 + /* "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; -static __Pyx_StringTabEntry __pyx_string_tab[] = { - {&__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_CIMultiDict, __pyx_k_CIMultiDict, sizeof(__pyx_k_CIMultiDict), 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_ContentLengthError, __pyx_k_ContentLengthError, sizeof(__pyx_k_ContentLengthError), 0, 0, 1, 1}, - {&__pyx_n_s_DeflateBuffer, __pyx_k_DeflateBuffer, sizeof(__pyx_k_DeflateBuffer), 0, 0, 1, 1}, - {&__pyx_n_s_EMPTY_PAYLOAD, __pyx_k_EMPTY_PAYLOAD, sizeof(__pyx_k_EMPTY_PAYLOAD), 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_u_HttpRequestParserC, __pyx_k_HttpRequestParserC, sizeof(__pyx_k_HttpRequestParserC), 0, 1, 0, 1}, - {&__pyx_n_u_HttpResponseMessageC, __pyx_k_HttpResponseMessageC, sizeof(__pyx_k_HttpResponseMessageC), 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_HttpVersion11, __pyx_k_HttpVersion11, sizeof(__pyx_k_HttpVersion11), 0, 0, 1, 1}, - {&__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_LineTooLong, __pyx_k_LineTooLong, sizeof(__pyx_k_LineTooLong), 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_PayloadEncodingError, __pyx_k_PayloadEncodingError, sizeof(__pyx_k_PayloadEncodingError), 0, 0, 1, 1}, - {&__pyx_n_s_RawRequestMessage, __pyx_k_RawRequestMessage, sizeof(__pyx_k_RawRequestMessage), 0, 0, 1, 1}, - {&__pyx_n_s_RawResponseMessage, __pyx_k_RawResponseMessage, sizeof(__pyx_k_RawResponseMessage), 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_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_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_URL, __pyx_k_URL, sizeof(__pyx_k_URL), 0, 0, 1, 1}, - {&__pyx_kp_u__13, __pyx_k__13, sizeof(__pyx_k__13), 0, 1, 0, 0}, - {&__pyx_kp_b__6, __pyx_k__6, sizeof(__pyx_k__6), 0, 0, 0, 0}, - {&__pyx_kp_u__6, __pyx_k__6, sizeof(__pyx_k__6), 0, 1, 0, 0}, - {&__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_kp_s_aiohttp__http_parser_pyx, __pyx_k_aiohttp__http_parser_pyx, sizeof(__pyx_k_aiohttp__http_parser_pyx), 0, 0, 1, 0}, - {&__pyx_n_s_all, __pyx_k_all, sizeof(__pyx_k_all), 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_buf_data, __pyx_k_buf_data, sizeof(__pyx_k_buf_data), 0, 0, 1, 1}, - {&__pyx_n_s_build, __pyx_k_build, sizeof(__pyx_k_build), 0, 0, 1, 1}, - {&__pyx_n_s_clear, __pyx_k_clear, sizeof(__pyx_k_clear), 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_decode, __pyx_k_decode, sizeof(__pyx_k_decode), 0, 0, 1, 1}, - {&__pyx_n_u_deflate, __pyx_k_deflate, sizeof(__pyx_k_deflate), 0, 1, 0, 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_extend, __pyx_k_extend, sizeof(__pyx_k_extend), 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_format, __pyx_k_format, sizeof(__pyx_k_format), 0, 0, 1, 1}, - {&__pyx_n_s_fragment, __pyx_k_fragment, sizeof(__pyx_k_fragment), 0, 0, 1, 1}, - {&__pyx_n_s_get, __pyx_k_get, sizeof(__pyx_k_get), 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_host, __pyx_k_host, sizeof(__pyx_k_host), 0, 0, 1, 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_version, __pyx_k_http_version, sizeof(__pyx_k_http_version), 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_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, - {&__pyx_kp_u_invalid_url_r, __pyx_k_invalid_url_r, sizeof(__pyx_k_invalid_url_r), 0, 1, 0, 0}, - {&__pyx_n_s_length, __pyx_k_length, sizeof(__pyx_k_length), 0, 0, 1, 1}, - {&__pyx_n_s_ln, __pyx_k_ln, sizeof(__pyx_k_ln), 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_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_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_off, __pyx_k_off, sizeof(__pyx_k_off), 0, 0, 1, 1}, - {&__pyx_n_s_parse_url, __pyx_k_parse_url, sizeof(__pyx_k_parse_url), 0, 0, 1, 1}, - {&__pyx_n_s_parse_url_2, __pyx_k_parse_url_2, sizeof(__pyx_k_parse_url_2), 0, 0, 1, 1}, - {&__pyx_n_u_parse_url_2, __pyx_k_parse_url_2, sizeof(__pyx_k_parse_url_2), 0, 1, 0, 1}, - {&__pyx_n_s_parsed, __pyx_k_parsed, sizeof(__pyx_k_parsed), 0, 0, 1, 1}, - {&__pyx_n_s_partition, __pyx_k_partition, sizeof(__pyx_k_partition), 0, 0, 1, 1}, - {&__pyx_n_s_password, __pyx_k_password, sizeof(__pyx_k_password), 0, 0, 1, 1}, - {&__pyx_n_s_path, __pyx_k_path, sizeof(__pyx_k_path), 0, 0, 1, 1}, - {&__pyx_n_s_payload_exception, __pyx_k_payload_exception, sizeof(__pyx_k_payload_exception), 0, 0, 1, 1}, - {&__pyx_n_s_port, __pyx_k_port, sizeof(__pyx_k_port), 0, 0, 1, 1}, - {&__pyx_n_s_protocol, __pyx_k_protocol, sizeof(__pyx_k_protocol), 0, 0, 1, 1}, - {&__pyx_n_s_py_buf, __pyx_k_py_buf, sizeof(__pyx_k_py_buf), 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, __pyx_k_query, sizeof(__pyx_k_query), 0, 0, 1, 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_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_res, __pyx_k_res, sizeof(__pyx_k_res), 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_result, __pyx_k_result, sizeof(__pyx_k_result), 0, 0, 1, 1}, - {&__pyx_n_s_schema, __pyx_k_schema, sizeof(__pyx_k_schema), 0, 0, 1, 1}, - {&__pyx_n_s_scheme, __pyx_k_scheme, sizeof(__pyx_k_scheme), 0, 0, 1, 1}, - {&__pyx_n_s_sep, __pyx_k_sep, sizeof(__pyx_k_sep), 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_streams, __pyx_k_streams, sizeof(__pyx_k_streams), 0, 0, 1, 1}, - {&__pyx_n_u_surrogateescape, __pyx_k_surrogateescape, sizeof(__pyx_k_surrogateescape), 0, 1, 0, 1}, - {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, - {&__pyx_n_s_timer, __pyx_k_timer, sizeof(__pyx_k_timer), 0, 0, 1, 1}, - {&__pyx_n_s_url, __pyx_k_url, sizeof(__pyx_k_url), 0, 0, 1, 1}, - {&__pyx_n_s_user, __pyx_k_user, sizeof(__pyx_k_user), 0, 0, 1, 1}, - {&__pyx_n_s_userinfo, __pyx_k_userinfo, sizeof(__pyx_k_userinfo), 0, 0, 1, 1}, - {&__pyx_kp_u_utf_8, __pyx_k_utf_8, sizeof(__pyx_k_utf_8), 0, 1, 0, 0}, - {&__pyx_n_s_yarl, __pyx_k_yarl, sizeof(__pyx_k_yarl), 0, 0, 1, 1}, - {0, 0, 0, 0, 0, 0, 0} -}; -static int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) __PYX_ERR(0, 72, __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, 375, __pyx_L1_error) - return 0; - __pyx_L1_error:; - return -1; -} + /* "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; -static int __Pyx_InitCachedConstants(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 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/_http_parser.pyx":168 - * CONTENT_ENCODING=hdrs.CONTENT_ENCODING, - * SEC_WEBSOCKET_KEY1=hdrs.SEC_WEBSOCKET_KEY1, - * SUPPORTED=('gzip', 'deflate', 'br')): # <<<<<<<<<<<<<< - * self._process_header() - * + /* "aiohttp/_headers.pxi":40 + * hdrs.EXPECT, + * hdrs.EXPIRES, + * hdrs.FORWARDED, # <<<<<<<<<<<<<< + * hdrs.FROM, + * hdrs.HOST, */ - __pyx_tuple__3 = PyTuple_Pack(3, __pyx_n_u_gzip, __pyx_n_u_deflate, __pyx_n_u_br); if (unlikely(!__pyx_tuple__3)) __PYX_ERR(0, 168, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__3); - __Pyx_GIVEREF(__pyx_tuple__3); + __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/_http_parser.pyx":251 - * 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_CONTENTLENGTH: + /* "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_tuple__4 = PyTuple_Pack(1, __pyx_kp_u_Not_enough_data_for_satisfy_tran); if (unlikely(!__pyx_tuple__4)) __PYX_ERR(0, 251, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__4); - __Pyx_GIVEREF(__pyx_tuple__4); + __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/_http_parser.pyx":254 - * "Not enough data for satisfy transfer length header.") - * elif self._cparser.flags & cparser.F_CONTENTLENGTH: - * raise ContentLengthError( # <<<<<<<<<<<<<< - * "Not enough data for satisfy content length header.") - * elif self._cparser.http_errno != cparser.HPE_OK: + /* "aiohttp/_headers.pxi":43 + * hdrs.FROM, + * hdrs.HOST, + * hdrs.IF_MATCH, # <<<<<<<<<<<<<< + * hdrs.IF_MODIFIED_SINCE, + * hdrs.IF_NONE_MATCH, */ - __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_u_Not_enough_data_for_satisfy_cont); if (unlikely(!__pyx_tuple__5)) __PYX_ERR(0, 254, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__5); - __Pyx_GIVEREF(__pyx_tuple__5); + __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; - /* "(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__") + /* "aiohttp/_headers.pxi":49 + * hdrs.IF_UNMODIFIED_SINCE, + * hdrs.KEEP_ALIVE, + * hdrs.LAST_EVENT_ID, # <<<<<<<<<<<<<< + * hdrs.LAST_MODIFIED, + * hdrs.LINK, */ - __pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__7)) __PYX_ERR(1, 2, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__7); - __Pyx_GIVEREF(__pyx_tuple__7); + __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; - /* "(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__") # <<<<<<<<<<<<<< + /* "aiohttp/_headers.pxi":50 + * hdrs.KEEP_ALIVE, + * hdrs.LAST_EVENT_ID, + * hdrs.LAST_MODIFIED, # <<<<<<<<<<<<<< + * hdrs.LINK, + * hdrs.LOCATION, */ - __pyx_tuple__8 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(1, 4, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__8); - __Pyx_GIVEREF(__pyx_tuple__8); + __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; - /* "(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__") + /* "aiohttp/_headers.pxi":51 + * hdrs.LAST_EVENT_ID, + * hdrs.LAST_MODIFIED, + * hdrs.LINK, # <<<<<<<<<<<<<< + * hdrs.LOCATION, + * hdrs.MAX_FORWARDS, */ - __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); + __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; - /* "(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__") # <<<<<<<<<<<<<< + /* "aiohttp/_headers.pxi":52 + * hdrs.LAST_MODIFIED, + * hdrs.LINK, + * hdrs.LOCATION, # <<<<<<<<<<<<<< + * hdrs.MAX_FORWARDS, + * hdrs.ORIGIN, */ - __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); + __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; - /* "(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__") + /* "aiohttp/_headers.pxi":53 + * hdrs.LINK, + * hdrs.LOCATION, + * hdrs.MAX_FORWARDS, # <<<<<<<<<<<<<< + * hdrs.ORIGIN, + * hdrs.PRAGMA, */ - __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); + __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; - /* "(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__") # <<<<<<<<<<<<<< + /* "aiohttp/_headers.pxi":54 + * hdrs.LOCATION, + * hdrs.MAX_FORWARDS, + * hdrs.ORIGIN, # <<<<<<<<<<<<<< + * hdrs.PRAGMA, + * hdrs.PROXY_AUTHENTICATE, */ - __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); + __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/_http_parser.pyx":25 - * - * - * __all__ = ('HttpRequestParserC', 'HttpResponseMessageC', 'parse_url') # <<<<<<<<<<<<<< - * - * + /* "aiohttp/_headers.pxi":55 + * hdrs.MAX_FORWARDS, + * hdrs.ORIGIN, + * hdrs.PRAGMA, # <<<<<<<<<<<<<< + * hdrs.PROXY_AUTHENTICATE, + * hdrs.PROXY_AUTHORIZATION, */ - __pyx_tuple__14 = PyTuple_Pack(3, __pyx_n_u_HttpRequestParserC, __pyx_n_u_HttpResponseMessageC, __pyx_n_u_parse_url_2); if (unlikely(!__pyx_tuple__14)) __PYX_ERR(0, 25, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__14); - __Pyx_GIVEREF(__pyx_tuple__14); + __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/_http_parser.pyx":532 - * - * - * def parse_url(url): # <<<<<<<<<<<<<< - * cdef: - * Py_buffer py_buf + /* "aiohttp/_headers.pxi":56 + * hdrs.ORIGIN, + * hdrs.PRAGMA, + * hdrs.PROXY_AUTHENTICATE, # <<<<<<<<<<<<<< + * hdrs.PROXY_AUTHORIZATION, + * hdrs.RANGE, */ - __pyx_tuple__15 = PyTuple_Pack(3, __pyx_n_s_url, __pyx_n_s_py_buf, __pyx_n_s_buf_data); if (unlikely(!__pyx_tuple__15)) __PYX_ERR(0, 532, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__15); - __Pyx_GIVEREF(__pyx_tuple__15); - __pyx_codeobj__16 = (PyObject*)__Pyx_PyCode_New(1, 0, 3, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__15, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_aiohttp__http_parser_pyx, __pyx_n_s_parse_url_2, 532, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__16)) __PYX_ERR(0, 532, __pyx_L1_error) + __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/_http_parser.pyx":545 - * - * - * def _parse_url(char* buf_data, size_t length): # <<<<<<<<<<<<<< - * cdef: - * cparser.http_parser_url* parsed + /* "aiohttp/_headers.pxi":57 + * hdrs.PRAGMA, + * hdrs.PROXY_AUTHENTICATE, + * hdrs.PROXY_AUTHORIZATION, # <<<<<<<<<<<<<< + * hdrs.RANGE, + * hdrs.REFERER, */ - __pyx_tuple__17 = PyTuple_Pack(17, __pyx_n_s_buf_data, __pyx_n_s_length, __pyx_n_s_parsed, __pyx_n_s_res, __pyx_n_s_schema, __pyx_n_s_host, __pyx_n_s_port, __pyx_n_s_path, __pyx_n_s_query, __pyx_n_s_fragment, __pyx_n_s_user, __pyx_n_s_password, __pyx_n_s_userinfo, __pyx_n_s_result, __pyx_n_s_off, __pyx_n_s_ln, __pyx_n_s_sep); if (unlikely(!__pyx_tuple__17)) __PYX_ERR(0, 545, __pyx_L1_error) - __Pyx_GOTREF(__pyx_tuple__17); - __Pyx_GIVEREF(__pyx_tuple__17); - __pyx_codeobj__18 = (PyObject*)__Pyx_PyCode_New(2, 0, 17, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__17, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_aiohttp__http_parser_pyx, __pyx_n_s_parse_url, 545, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__18)) __PYX_ERR(0, 545, __pyx_L1_error) - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_RefNannyFinishContext(); - return -1; -} + __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; -static int __Pyx_InitGlobals(void) { - __pyx_umethod_PyUnicode_Type_partition.type = (PyObject*)&PyUnicode_Type; - if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error); - return 0; - __pyx_L1_error:; - return -1; -} + /* "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; -static int __Pyx_modinit_global_init_code(void); /*proto*/ -static int __Pyx_modinit_variable_export_code(void); /*proto*/ -static int __Pyx_modinit_function_export_code(void); /*proto*/ -static int __Pyx_modinit_type_init_code(void); /*proto*/ -static int __Pyx_modinit_type_import_code(void); /*proto*/ -static int __Pyx_modinit_variable_import_code(void); /*proto*/ -static int __Pyx_modinit_function_import_code(void); /*proto*/ + /* "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; -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_URL_build = Py_None; Py_INCREF(Py_None); - __Pyx_RefNannyFinishContext(); - return 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; -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; -} + /* "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; -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; -} + /* "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; -static int __Pyx_modinit_type_init_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_type_init_code", 0); - /*--- Type init code ---*/ - __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 http_parser_type, PyObject *, PyObject *, 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 *, PyObject *, PyObject *))__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 *, PyObject *, PyObject *))__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 *, struct __pyx_opt_args_7aiohttp_12_http_parser_10HttpParser__on_headers_complete *__pyx_optional_args))__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; - if (PyType_Ready(&__pyx_type_7aiohttp_12_http_parser_HttpParser) < 0) __PYX_ERR(0, 31, __pyx_L1_error) - __pyx_type_7aiohttp_12_http_parser_HttpParser.tp_print = 0; - 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, 31, __pyx_L1_error) - if (__Pyx_setup_reduce((PyObject*)&__pyx_type_7aiohttp_12_http_parser_HttpParser) < 0) __PYX_ERR(0, 31, __pyx_L1_error) - __pyx_ptype_7aiohttp_12_http_parser_HttpParser = &__pyx_type_7aiohttp_12_http_parser_HttpParser; - __pyx_vtabptr_7aiohttp_12_http_parser_HttpRequestParserC = &__pyx_vtable_7aiohttp_12_http_parser_HttpRequestParserC; - __pyx_vtable_7aiohttp_12_http_parser_HttpRequestParserC.__pyx_base = *__pyx_vtabptr_7aiohttp_12_http_parser_HttpParser; - __pyx_vtable_7aiohttp_12_http_parser_HttpRequestParserC.__pyx_base._on_status_complete = (PyObject *(*)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *))__pyx_f_7aiohttp_12_http_parser_18HttpRequestParserC__on_status_complete; - __pyx_type_7aiohttp_12_http_parser_HttpRequestParserC.tp_base = __pyx_ptype_7aiohttp_12_http_parser_HttpParser; - if (PyType_Ready(&__pyx_type_7aiohttp_12_http_parser_HttpRequestParserC) < 0) __PYX_ERR(0, 311, __pyx_L1_error) - __pyx_type_7aiohttp_12_http_parser_HttpRequestParserC.tp_print = 0; - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_7aiohttp_12_http_parser_HttpRequestParserC.tp_dictoffset && __pyx_type_7aiohttp_12_http_parser_HttpRequestParserC.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type_7aiohttp_12_http_parser_HttpRequestParserC.tp_getattro = __Pyx_PyObject_GenericGetAttr; - } - if (__Pyx_SetVtable(__pyx_type_7aiohttp_12_http_parser_HttpRequestParserC.tp_dict, __pyx_vtabptr_7aiohttp_12_http_parser_HttpRequestParserC) < 0) __PYX_ERR(0, 311, __pyx_L1_error) - if (PyObject_SetAttrString(__pyx_m, "HttpRequestParserC", (PyObject *)&__pyx_type_7aiohttp_12_http_parser_HttpRequestParserC) < 0) __PYX_ERR(0, 311, __pyx_L1_error) - if (__Pyx_setup_reduce((PyObject*)&__pyx_type_7aiohttp_12_http_parser_HttpRequestParserC) < 0) __PYX_ERR(0, 311, __pyx_L1_error) - __pyx_ptype_7aiohttp_12_http_parser_HttpRequestParserC = &__pyx_type_7aiohttp_12_http_parser_HttpRequestParserC; - __pyx_vtabptr_7aiohttp_12_http_parser_HttpResponseParserC = &__pyx_vtable_7aiohttp_12_http_parser_HttpResponseParserC; - __pyx_vtable_7aiohttp_12_http_parser_HttpResponseParserC.__pyx_base = *__pyx_vtabptr_7aiohttp_12_http_parser_HttpParser; - __pyx_vtable_7aiohttp_12_http_parser_HttpResponseParserC.__pyx_base._on_status_complete = (PyObject *(*)(struct __pyx_obj_7aiohttp_12_http_parser_HttpParser *))__pyx_f_7aiohttp_12_http_parser_19HttpResponseParserC__on_status_complete; - __pyx_type_7aiohttp_12_http_parser_HttpResponseParserC.tp_base = __pyx_ptype_7aiohttp_12_http_parser_HttpParser; - if (PyType_Ready(&__pyx_type_7aiohttp_12_http_parser_HttpResponseParserC) < 0) __PYX_ERR(0, 338, __pyx_L1_error) - __pyx_type_7aiohttp_12_http_parser_HttpResponseParserC.tp_print = 0; - if ((CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP) && likely(!__pyx_type_7aiohttp_12_http_parser_HttpResponseParserC.tp_dictoffset && __pyx_type_7aiohttp_12_http_parser_HttpResponseParserC.tp_getattro == PyObject_GenericGetAttr)) { - __pyx_type_7aiohttp_12_http_parser_HttpResponseParserC.tp_getattro = __Pyx_PyObject_GenericGetAttr; - } - if (__Pyx_SetVtable(__pyx_type_7aiohttp_12_http_parser_HttpResponseParserC.tp_dict, __pyx_vtabptr_7aiohttp_12_http_parser_HttpResponseParserC) < 0) __PYX_ERR(0, 338, __pyx_L1_error) - if (PyObject_SetAttrString(__pyx_m, "HttpResponseParserC", (PyObject *)&__pyx_type_7aiohttp_12_http_parser_HttpResponseParserC) < 0) __PYX_ERR(0, 338, __pyx_L1_error) - if (__Pyx_setup_reduce((PyObject*)&__pyx_type_7aiohttp_12_http_parser_HttpResponseParserC) < 0) __PYX_ERR(0, 338, __pyx_L1_error) - __pyx_ptype_7aiohttp_12_http_parser_HttpResponseParserC = &__pyx_type_7aiohttp_12_http_parser_HttpResponseParserC; - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_RefNannyFinishContext(); - return -1; -} + /* "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; -static int __Pyx_modinit_type_import_code(void) { - __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); - /*--- Type import code ---*/ - __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", - #if CYTHON_COMPILING_IN_PYPY - sizeof(PyTypeObject), - #else - sizeof(PyHeapTypeObject), - #endif - 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) __PYX_ERR(2, 9, __pyx_L1_error) - __pyx_ptype_7cpython_4bool_bool = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "bool", sizeof(PyBoolObject), 0); if (unlikely(!__pyx_ptype_7cpython_4bool_bool)) __PYX_ERR(3, 8, __pyx_L1_error) - __pyx_ptype_7cpython_7complex_complex = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "complex", sizeof(PyComplexObject), 0); if (unlikely(!__pyx_ptype_7cpython_7complex_complex)) __PYX_ERR(4, 15, __pyx_L1_error) - __Pyx_RefNannyFinishContext(); - return 0; - __pyx_L1_error:; - __Pyx_RefNannyFinishContext(); - return -1; -} + /* "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; -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; -} + /* "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; -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; -} + /* "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; -#if PY_MAJOR_VERSION < 3 -#ifdef CYTHON_NO_PYINIT_EXPORT -#define __Pyx_PyMODINIT_FUNC void -#else -#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC -#endif -#else -#ifdef CYTHON_NO_PYINIT_EXPORT -#define __Pyx_PyMODINIT_FUNC PyObject * -#else -#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC -#endif -#endif -#ifndef CYTHON_SMALL_CODE -#if defined(__clang__) - #define CYTHON_SMALL_CODE -#elif defined(__GNUC__) - #define CYTHON_SMALL_CODE __attribute__((optimize("Os"))) -#else - #define CYTHON_SMALL_CODE -#endif -#endif + /* "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; -#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 int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name) { - PyObject *value = PyObject_GetAttrString(spec, from_name); - int result = 0; - if (likely(value)) { - result = PyDict_SetItemString(moddict, to_name, value); - Py_DECREF(value); - } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Clear(); - } else { - result = -1; - } - return result; -} -static PyObject* __pyx_pymod_create(PyObject *spec, CYTHON_UNUSED PyModuleDef *def) { - PyObject *module = NULL, *moddict, *modname; - 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__") < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__") < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__") < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__") < 0)) goto bad; - return module; -bad: - Py_XDECREF(module); - return NULL; -} + /* "aiohttp/_headers.pxi":70 + * hdrs.SET_COOKIE, + * hdrs.TE, + * hdrs.TRAILER, # <<<<<<<<<<<<<< + * hdrs.TRANSFER_ENCODING, + * hdrs.UPGRADE, + */ + __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.UPGRADE, + * hdrs.URI, + */ + __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; -static int __pyx_pymod_exec__http_parser(PyObject *__pyx_pyinit_module) -#endif -#endif -{ - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - __Pyx_RefNannyDeclarations - #if CYTHON_PEP489_MULTI_PHASE_INIT - if (__pyx_m && __pyx_m == __pyx_pyinit_module) return 0; - #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) - __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(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS - #ifdef WITH_THREAD /* Python build with threading support? */ - PyEval_InitThreads(); - #endif - #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) - __pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) - #if CYTHON_COMPILING_IN_PYPY - Py_INCREF(__pyx_b); - #endif - 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_SetAttrString(__pyx_m, "__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)) goto __pyx_L1_error; - if (unlikely(__Pyx_modinit_type_import_code() != 0)) goto __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/_headers.pxi":72 + * hdrs.TRAILER, + * hdrs.TRANSFER_ENCODING, + * hdrs.UPGRADE, # <<<<<<<<<<<<<< + * hdrs.URI, + * 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_UPGRADE); 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/_http_parser.pyx":10 - * Py_buffer, PyBytes_AsString - * - * from multidict import CIMultiDict # <<<<<<<<<<<<<< - * from yarl import URL - * + /* "aiohttp/_headers.pxi":73 + * hdrs.TRANSFER_ENCODING, + * hdrs.UPGRADE, + * hdrs.URI, # <<<<<<<<<<<<<< + * hdrs.USER_AGENT, + * hdrs.VARY, */ - __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 10, __pyx_L1_error) + __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_INCREF(__pyx_n_s_CIMultiDict); - __Pyx_GIVEREF(__pyx_n_s_CIMultiDict); - PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_CIMultiDict); - __pyx_t_2 = __Pyx_Import(__pyx_n_s_multidict, __pyx_t_1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 10, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); + __pyx_t_69 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_URI); 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; - __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_CIMultiDict); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 10, __pyx_L1_error) + + /* "aiohttp/_headers.pxi":74 + * hdrs.UPGRADE, + * hdrs.URI, + * 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); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_CIMultiDict, __pyx_t_1) < 0) __PYX_ERR(0, 10, __pyx_L1_error) + __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; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "aiohttp/_http_parser.pyx":11 - * - * from multidict import CIMultiDict - * from yarl import URL # <<<<<<<<<<<<<< - * - * from aiohttp import hdrs + /* "aiohttp/_headers.pxi":75 + * hdrs.URI, + * hdrs.USER_AGENT, + * hdrs.VARY, # <<<<<<<<<<<<<< + * hdrs.VIA, + * hdrs.WANT_DIGEST, */ - __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 11, __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, 11, __pyx_L1_error) + __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_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, 11, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_URL, __pyx_t_2) < 0) __PYX_ERR(0, 11, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __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/_http_parser.pyx":13 - * from yarl import URL - * - * from aiohttp import hdrs # <<<<<<<<<<<<<< - * from .http_exceptions import ( - * BadHttpMessage, BadStatusLine, InvalidHeader, LineTooLong, InvalidURLError, + /* "aiohttp/_headers.pxi":76 + * hdrs.USER_AGENT, + * hdrs.VARY, + * hdrs.VIA, # <<<<<<<<<<<<<< + * hdrs.WANT_DIGEST, + * hdrs.WARNING, */ - __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 13, __pyx_L1_error) + __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_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, 13, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); + __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; - __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 13, __pyx_L1_error) + + /* "aiohttp/_headers.pxi":77 + * hdrs.VARY, + * hdrs.VIA, + * hdrs.WANT_DIGEST, # <<<<<<<<<<<<<< + * hdrs.WARNING, + * hdrs.WEBSOCKET, + */ + __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); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_hdrs, __pyx_t_1) < 0) __PYX_ERR(0, 13, __pyx_L1_error) + __pyx_t_73 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_WANT_DIGEST); 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; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "aiohttp/_http_parser.pyx":15 - * from aiohttp import hdrs - * from .http_exceptions import ( - * BadHttpMessage, BadStatusLine, InvalidHeader, LineTooLong, InvalidURLError, # <<<<<<<<<<<<<< - * PayloadEncodingError, ContentLengthError, TransferEncodingError) - * from .http_writer import HttpVersion, HttpVersion10, HttpVersion11 + /* "aiohttp/_headers.pxi":78 + * hdrs.VIA, + * hdrs.WANT_DIGEST, + * hdrs.WARNING, # <<<<<<<<<<<<<< + * hdrs.WEBSOCKET, + * hdrs.WWW_AUTHENTICATE, */ - __pyx_t_2 = PyList_New(8); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 15, __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_InvalidHeader); - __Pyx_GIVEREF(__pyx_n_s_InvalidHeader); - PyList_SET_ITEM(__pyx_t_2, 2, __pyx_n_s_InvalidHeader); - __Pyx_INCREF(__pyx_n_s_LineTooLong); - __Pyx_GIVEREF(__pyx_n_s_LineTooLong); - PyList_SET_ITEM(__pyx_t_2, 3, __pyx_n_s_LineTooLong); - __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_PayloadEncodingError); - __Pyx_GIVEREF(__pyx_n_s_PayloadEncodingError); - PyList_SET_ITEM(__pyx_t_2, 5, __pyx_n_s_PayloadEncodingError); - __Pyx_INCREF(__pyx_n_s_ContentLengthError); - __Pyx_GIVEREF(__pyx_n_s_ContentLengthError); - PyList_SET_ITEM(__pyx_t_2, 6, __pyx_n_s_ContentLengthError); - __Pyx_INCREF(__pyx_n_s_TransferEncodingError); - __Pyx_GIVEREF(__pyx_n_s_TransferEncodingError); - PyList_SET_ITEM(__pyx_t_2, 7, __pyx_n_s_TransferEncodingError); + __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_WARNING); 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/_http_parser.pyx":14 - * - * from aiohttp import hdrs - * from .http_exceptions import ( # <<<<<<<<<<<<<< - * BadHttpMessage, BadStatusLine, InvalidHeader, LineTooLong, InvalidURLError, - * PayloadEncodingError, ContentLengthError, TransferEncodingError) + /* "aiohttp/_headers.pxi":79 + * hdrs.WANT_DIGEST, + * hdrs.WARNING, + * hdrs.WEBSOCKET, # <<<<<<<<<<<<<< + * hdrs.WWW_AUTHENTICATE, + * hdrs.X_FORWARDED_FOR, */ - __pyx_t_1 = __Pyx_Import(__pyx_n_s_http_exceptions, __pyx_t_2, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 14, __pyx_L1_error) + __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_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, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_BadHttpMessage, __pyx_t_2) < 0) __PYX_ERR(0, 15, __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, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_BadStatusLine, __pyx_t_2) < 0) __PYX_ERR(0, 15, __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, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_InvalidHeader, __pyx_t_2) < 0) __PYX_ERR(0, 15, __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, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_LineTooLong, __pyx_t_2) < 0) __PYX_ERR(0, 15, __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, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_InvalidURLError, __pyx_t_2) < 0) __PYX_ERR(0, 15, __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, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_PayloadEncodingError, __pyx_t_2) < 0) __PYX_ERR(0, 16, __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, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_ContentLengthError, __pyx_t_2) < 0) __PYX_ERR(0, 16, __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, 14, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_TransferEncodingError, __pyx_t_2) < 0) __PYX_ERR(0, 16, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_75 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_WEBSOCKET); 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.WARNING, + * hdrs.WEBSOCKET, + * hdrs.WWW_AUTHENTICATE, # <<<<<<<<<<<<<< + * 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, 80, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_76 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_WWW_AUTHENTICATE); 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.WEBSOCKET, + * hdrs.WWW_AUTHENTICATE, + * 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_FOR); 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.WWW_AUTHENTICATE, + * 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_HOST); 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":83 + * 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, 83, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_79 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_X_FORWARDED_PROTO); if (unlikely(!__pyx_t_79)) __PYX_ERR(5, 83, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_79); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "aiohttp/_http_parser.pyx":17 - * BadHttpMessage, BadStatusLine, InvalidHeader, LineTooLong, InvalidURLError, - * PayloadEncodingError, ContentLengthError, TransferEncodingError) - * from .http_writer import HttpVersion, HttpVersion10, HttpVersion11 # <<<<<<<<<<<<<< - * from .http_parser import RawRequestMessage, RawResponseMessage, DeflateBuffer - * from .streams import EMPTY_PAYLOAD, StreamReader + /* "aiohttp/_headers.pxi":6 + * from . import hdrs + * cdef tuple headers = ( + * hdrs.ACCEPT, # <<<<<<<<<<<<<< + * hdrs.ACCEPT_CHARSET, + * hdrs.ACCEPT_ENCODING, + */ + __pyx_t_1 = PyTuple_New(78); 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_GIVEREF(__pyx_t_79); + PyTuple_SET_ITEM(__pyx_t_1, 77, __pyx_t_79); + __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_t_79 = 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":40 + * char* PyByteArray_AsString(object) + * + * __all__ = ('HttpRequestParser', 'HttpResponseParser', # <<<<<<<<<<<<<< + * 'RawRequestMessage', 'RawResponseMessage') + * + */ + if (PyDict_SetItem(__pyx_d, __pyx_n_s_all, __pyx_tuple__12) < 0) __PYX_ERR(0, 40, __pyx_L1_error) + + /* "aiohttp/_http_parser.pyx":43 + * '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, 43, __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":44 + * + * 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, 44, __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":45 + * 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, 45, __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":46 + * 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, 46, __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":47 + * 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, 47, __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":48 + * 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, 48, __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":49 + * 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_t_1 = PyList_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 17, __pyx_L1_error) + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_HttpVersion11_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 49, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - __Pyx_INCREF(__pyx_n_s_HttpVersion); - __Pyx_GIVEREF(__pyx_n_s_HttpVersion); - PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_HttpVersion); - __Pyx_INCREF(__pyx_n_s_HttpVersion10); - __Pyx_GIVEREF(__pyx_n_s_HttpVersion10); - PyList_SET_ITEM(__pyx_t_1, 1, __pyx_n_s_HttpVersion10); - __Pyx_INCREF(__pyx_n_s_HttpVersion11); - __Pyx_GIVEREF(__pyx_n_s_HttpVersion11); - PyList_SET_ITEM(__pyx_t_1, 2, __pyx_n_s_HttpVersion11); - __pyx_t_2 = __Pyx_Import(__pyx_n_s_http_writer, __pyx_t_1, 1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 17, __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_HttpVersion); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 17, __pyx_L1_error) + __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":50 + * 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, 50, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_HttpVersion, __pyx_t_1) < 0) __PYX_ERR(0, 17, __pyx_L1_error) + __pyx_t_79 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_SEC_WEBSOCKET_KEY1); if (unlikely(!__pyx_t_79)) __PYX_ERR(0, 50, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_79); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_HttpVersion10); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 17, __pyx_L1_error) + __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_79); + __Pyx_GIVEREF(__pyx_t_79); + __pyx_t_79 = 0; + + /* "aiohttp/_http_parser.pyx":51 + * 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_79, __pyx_n_s_hdrs); if (unlikely(!__pyx_t_79)) __PYX_ERR(0, 51, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_79); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_79, __pyx_n_s_CONTENT_ENCODING); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 51, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_HttpVersion10, __pyx_t_1) < 0) __PYX_ERR(0, 17, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_HttpVersion11); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 17, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_79); __pyx_t_79 = 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":52 + * 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, 52, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_HttpVersion11, __pyx_t_1) < 0) __PYX_ERR(0, 17, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __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":18 - * PayloadEncodingError, ContentLengthError, TransferEncodingError) - * from .http_writer import HttpVersion, HttpVersion10, HttpVersion11 - * from .http_parser import RawRequestMessage, RawResponseMessage, DeflateBuffer # <<<<<<<<<<<<<< - * from .streams import EMPTY_PAYLOAD, StreamReader + /* "aiohttp/_http_parser.pyx":53 + * cdef object CONTENT_ENCODING = hdrs.CONTENT_ENCODING + * cdef object EMPTY_PAYLOAD = _EMPTY_PAYLOAD + * cdef object StreamReader = _StreamReader # <<<<<<<<<<<<<< + * cdef object DeflateBuffer = _DeflateBuffer * */ - __pyx_t_2 = PyList_New(3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 18, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __Pyx_INCREF(__pyx_n_s_RawRequestMessage); - __Pyx_GIVEREF(__pyx_n_s_RawRequestMessage); - PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_RawRequestMessage); - __Pyx_INCREF(__pyx_n_s_RawResponseMessage); - __Pyx_GIVEREF(__pyx_n_s_RawResponseMessage); - PyList_SET_ITEM(__pyx_t_2, 1, __pyx_n_s_RawResponseMessage); - __Pyx_INCREF(__pyx_n_s_DeflateBuffer); - __Pyx_GIVEREF(__pyx_n_s_DeflateBuffer); - PyList_SET_ITEM(__pyx_t_2, 2, __pyx_n_s_DeflateBuffer); - __pyx_t_1 = __Pyx_Import(__pyx_n_s_http_parser, __pyx_t_2, 1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 18, __pyx_L1_error) + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_StreamReader_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 53, __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_RawRequestMessage); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 18, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_RawRequestMessage, __pyx_t_2) < 0) __PYX_ERR(0, 18, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s_RawResponseMessage); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 18, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_RawResponseMessage, __pyx_t_2) < 0) __PYX_ERR(0, 18, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s_DeflateBuffer); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 18, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_DeflateBuffer, __pyx_t_2) < 0) __PYX_ERR(0, 18, __pyx_L1_error) - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __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":19 - * from .http_writer import HttpVersion, HttpVersion10, HttpVersion11 - * from .http_parser import RawRequestMessage, RawResponseMessage, DeflateBuffer - * from .streams import EMPTY_PAYLOAD, StreamReader # <<<<<<<<<<<<<< + /* "aiohttp/_http_parser.pyx":54 + * cdef object EMPTY_PAYLOAD = _EMPTY_PAYLOAD + * cdef object StreamReader = _StreamReader + * cdef object DeflateBuffer = _DeflateBuffer # <<<<<<<<<<<<<< + * * - * cimport cython */ - __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_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, 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_EMPTY_PAYLOAD); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 19, __pyx_L1_error) + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_DeflateBuffer_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 54, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_EMPTY_PAYLOAD, __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_StreamReader); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 19, __pyx_L1_error) + __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":68 + * DEF METHODS_COUNT = 34; + * + * cdef list _http_method = [] # <<<<<<<<<<<<<< + * + * for i in range(METHODS_COUNT): + */ + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 68, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_StreamReader, __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; + __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":70 + * cdef list _http_method = [] + * + * for i in range(METHODS_COUNT): # <<<<<<<<<<<<<< + * _http_method.append( + * cparser.http_method_str( i).decode('ascii')) + */ + for (__pyx_t_80 = 0; __pyx_t_80 < 34; __pyx_t_80+=1) { + __pyx_t_1 = __Pyx_PyInt_From_long(__pyx_t_80); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 70, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_i, __pyx_t_1) < 0) __PYX_ERR(0, 70, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "aiohttp/_http_parser.pyx":25 + /* "aiohttp/_http_parser.pyx":71 * + * for i in range(METHODS_COUNT): + * _http_method.append( # <<<<<<<<<<<<<< + * cparser.http_method_str( i).decode('ascii')) * - * __all__ = ('HttpRequestParserC', 'HttpResponseMessageC', 'parse_url') # <<<<<<<<<<<<<< + */ + 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, 71, __pyx_L1_error) + } + + /* "aiohttp/_http_parser.pyx":72 + * for i in range(METHODS_COUNT): + * _http_method.append( + * cparser.http_method_str( i).decode('ascii')) # <<<<<<<<<<<<<< * * */ - if (PyDict_SetItem(__pyx_d, __pyx_n_s_all, __pyx_tuple__14) < 0) __PYX_ERR(0, 25, __pyx_L1_error) + __Pyx_GetModuleGlobalName(__pyx_t_1, __pyx_n_s_i); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 72, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_81 = ((enum http_method)__Pyx_PyInt_As_enum__http_method(__pyx_t_1)); if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 72, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_t_82 = http_method_str(((enum http_method)__pyx_t_81)); + __pyx_t_1 = __Pyx_decode_c_string(__pyx_t_82, 0, strlen(__pyx_t_82), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 72, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); - /* "aiohttp/_http_parser.pyx":28 + /* "aiohttp/_http_parser.pyx":71 * + * for i in range(METHODS_COUNT): + * _http_method.append( # <<<<<<<<<<<<<< + * cparser.http_method_str( i).decode('ascii')) * - * cdef object URL_build = URL.build # <<<<<<<<<<<<<< + */ + __pyx_t_83 = __Pyx_PyList_Append(__pyx_v_7aiohttp_12_http_parser__http_method, __pyx_t_1); if (unlikely(__pyx_t_83 == ((int)-1))) __PYX_ERR(0, 71, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } + + /* "aiohttp/_http_parser.pyx":755 * - * @cython.internal + * + * def parse_url(url): # <<<<<<<<<<<<<< + * cdef: + * Py_buffer py_buf */ - __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_URL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 28, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_build); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 28, __pyx_L1_error) + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7aiohttp_12_http_parser_1parse_url, NULL, __pyx_n_s_aiohttp__http_parser); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 755, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __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; + if (PyDict_SetItem(__pyx_d, __pyx_n_s_parse_url, __pyx_t_1) < 0) __PYX_ERR(0, 755, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "aiohttp/_http_parser.pyx":166 - * ENCODING='utf-8', - * ENCODING_ERR='surrogateescape', - * CONTENT_ENCODING=hdrs.CONTENT_ENCODING, # <<<<<<<<<<<<<< - * SEC_WEBSOCKET_KEY1=hdrs.SEC_WEBSOCKET_KEY1, - * SUPPORTED=('gzip', 'deflate', 'br')): + /* "(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 = __Pyx_GetModuleGlobalName(__pyx_n_s_hdrs); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 166, __pyx_L1_error) + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7aiohttp_12_http_parser_3__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); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_CONTENT_ENCODING); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 166, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); + 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; - __pyx_k_ = __pyx_t_2; - __Pyx_GIVEREF(__pyx_t_2); - __pyx_t_2 = 0; - /* "aiohttp/_http_parser.pyx":167 - * ENCODING_ERR='surrogateescape', - * CONTENT_ENCODING=hdrs.CONTENT_ENCODING, - * SEC_WEBSOCKET_KEY1=hdrs.SEC_WEBSOCKET_KEY1, # <<<<<<<<<<<<<< - * SUPPORTED=('gzip', 'deflate', 'br')): - * self._process_header() + /* "(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_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_hdrs); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 167, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_SEC_WEBSOCKET_KEY1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 167, __pyx_L1_error) + __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7aiohttp_12_http_parser_5__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); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_k__2 = __pyx_t_1; - __Pyx_GIVEREF(__pyx_t_1); - __pyx_t_1 = 0; + 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":532 - * - * - * def parse_url(url): # <<<<<<<<<<<<<< - * cdef: - * Py_buffer py_buf + /* "aiohttp/_http_parser.pyx":1 + * #cython: language_level=3 # <<<<<<<<<<<<<< + * # + * # Based on https://github.com/MagicStack/httptools */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7aiohttp_12_http_parser_1parse_url, NULL, __pyx_n_s_aiohttp__http_parser); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 532, __pyx_L1_error) + __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_parse_url_2, __pyx_t_1) < 0) __PYX_ERR(0, 532, __pyx_L1_error) + 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; - /* "aiohttp/_http_parser.pyx":545 - * - * - * def _parse_url(char* buf_data, size_t length): # <<<<<<<<<<<<<< - * cdef: - * cparser.http_parser_url* parsed - */ - __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_7aiohttp_12_http_parser_3_parse_url, NULL, __pyx_n_s_aiohttp__http_parser); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 545, __pyx_L1_error) - __Pyx_GOTREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_parse_url, __pyx_t_1) < 0) __PYX_ERR(0, 545, __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); + __Pyx_XDECREF(__pyx_t_79); + 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; + length = stop - start; + if (unlikely(length <= 0)) + return PyUnicode_FromUnicode(NULL, 0); + cstring += start; + if (decode_func) { + return decode_func(cstring, length, errors); + } else { + return PyUnicode_Decode(cstring, length, encoding, errors); + } +} - /* "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; +/* 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); +} - /*--- Wrapped vars code ---*/ +/* 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 +} - 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_parser", 0, __pyx_lineno, __pyx_filename); +/* 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_CheckExact(key)) || 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 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(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 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(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; + } } - Py_DECREF(__pyx_m); __pyx_m = 0; - } 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 + 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; } -/* --- 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((char *)modname); - if (!m) goto end; - p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); - if (!p) goto end; - r = PyLong_AsVoidPtr(p); -end: - Py_XDECREF(p); - Py_XDECREF(m); - return (__Pyx_RefNannyAPIStruct *)r; +/* None */ +static CYTHON_INLINE void __Pyx_RaiseClosureNameError(const char *varname) { + PyErr_Format(PyExc_NameError, "free variable '%s' referenced before assignment in enclosing scope", varname); } -#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); +/* 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"); } -#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); +/* 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 - "name '%.200s' is not defined", PyString_AS_STRING(name)); -#endif + if (unlikely(PyErr_Occurred())) { + if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { + PyErr_Clear(); + return 0; + } else { + return -1; + } } - return result; + return 0; +#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"; +/* UnpackItemEndCheck */ +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; } else { - num_expected = num_max; - more_or_less = "at most"; - } - if (exact) { - more_or_less = "exactly"; + return __Pyx_IterFinish(); } - 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); + return 0; } /* KeywordStringCheck */ @@ -12419,9 +20064,157 @@ 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); +} + +/* 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 -#include "frameobject.h" static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na, PyObject *globals) { PyFrameObject *f; @@ -12439,7 +20232,7 @@ if (f == NULL) { return NULL; } - fastlocals = f->f_localsplus; + fastlocals = __Pyx_PyFrame_GetLocalsplus(f); for (i = 0; i < na; i++) { Py_INCREF(*args); fastlocals[i] = *args++; @@ -12588,10 +20381,11 @@ } #endif #ifdef __Pyx_CyFunction_USED - if (likely(PyCFunction_Check(func) || __Pyx_TypeCheck(func, __pyx_CyFunctionType))) { + if (likely(PyCFunction_Check(func) || __Pyx_CyFunction_Check(func))) #else - if (likely(PyCFunction_Check(func))) { + if (likely(PyCFunction_Check(func))) #endif + { if (likely(PyCFunction_GET_FLAGS(func) & METH_NOARGS)) { return __Pyx_PyObject_CallMethO(func, NULL); } @@ -12600,42 +20394,15 @@ } #endif -/* GetModuleGlobalName */ - static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { - 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); - if (likely(result)) { - Py_INCREF(result); - } else if (unlikely(PyErr_Occurred())) { - result = NULL; - } else { -#else - result = PyDict_GetItem(__pyx_d, name); - if (likely(result)) { - Py_INCREF(result); - } else { -#endif -#else - result = PyObject_GetItem(__pyx_d, name); - if (!result) { - PyErr_Clear(); -#endif - result = __Pyx_GetBuiltinName(name); - } - return result; -} - /* PyCFunctionFastCall */ - #if CYTHON_FAST_PYCCALL +#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))); + 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, @@ -12643,15 +20410,15 @@ caller loses its exception */ assert(!PyErr_Occurred()); if ((PY_VERSION_HEX < 0x030700A0) || unlikely(flags & METH_KEYWORDS)) { - return (*((__Pyx_PyCFunctionFastWithKeywords)meth)) (self, args, nargs, NULL); + return (*((__Pyx_PyCFunctionFastWithKeywords)(void*)meth)) (self, args, nargs, NULL); } else { - return (*((__Pyx_PyCFunctionFast)meth)) (self, args, nargs); + return (*((__Pyx_PyCFunctionFast)(void*)meth)) (self, args, nargs); } } #endif /* PyObjectCallOneArg */ - #if CYTHON_COMPILING_IN_CPYTHON +#if CYTHON_COMPILING_IN_CPYTHON static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { PyObject *result; PyObject *args = PyTuple_New(1); @@ -12690,32 +20457,37 @@ } #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; +/* 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; } -#endif /* RaiseException */ - #if PY_MAJOR_VERSION < 3 +#if PY_MAJOR_VERSION < 3 static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, CYTHON_UNUSED PyObject *cause) { __Pyx_PyThreadState_declare @@ -12873,122 +20645,157 @@ } #endif -/* 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; +/* 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); } - if (stop < 0) - stop += length; - } - if (stop > length) - stop = length; - length = stop - start; - if (unlikely(length <= 0)) - return PyUnicode_FromUnicode(NULL, 0); - cstring += start; - if (decode_func) { - return decode_func(cstring, length, errors); + } 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 { - return PyUnicode_Decode(cstring, length, encoding, errors); + 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 } -/* 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((0 <= wrapped_i) & (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)); +/* 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 - return PySequence_GetItem(o, i); +#if PY_MAJOR_VERSION < 3 + PyObject* owned_ref = NULL; #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); + int s1_is_unicode, s2_is_unicode; + if (s1 == s2) { + goto return_eq; } - if ((!boundscheck) || likely((0 <= wrapped_i) & (wrapped_i < PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, wrapped_i); - Py_INCREF(r); - return r; + 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); } - 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((n >= 0) & (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((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, n); - Py_INCREF(r); - return r; + 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; } - } 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(); - } +#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; } - return m->sq_item(o, i); } +#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; } -#else - if (is_list || PySequence_Check(o)) { - return PySequence_GetItem(o, i); - } +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 - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); } /* SliceObject */ - static CYTHON_INLINE PyObject* __Pyx_PyObject_GetSlice(PyObject* obj, +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) { @@ -13084,128 +20891,13 @@ return NULL; } -/* 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_CheckExact(key)) || 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 - (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(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 - (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(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; -} - /* GetException */ - #if CYTHON_FAST_THREAD_STATE -static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { +#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) { +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; @@ -13238,13 +20930,16 @@ *value = local_value; *tb = local_tb; #if CYTHON_FAST_THREAD_STATE - #if PY_VERSION_HEX >= 0x030700A2 - tmp_type = tstate->exc_state.exc_type; - tmp_value = tstate->exc_state.exc_value; - tmp_tb = tstate->exc_state.exc_traceback; - tstate->exc_state.exc_type = local_type; - tstate->exc_state.exc_value = local_value; - tstate->exc_state.exc_traceback = local_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 = 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; @@ -13271,16 +20966,17 @@ } /* SwapException */ - #if CYTHON_FAST_THREAD_STATE +#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 PY_VERSION_HEX >= 0x030700A2 - tmp_type = tstate->exc_state.exc_type; - tmp_value = tstate->exc_state.exc_value; - tmp_tb = tstate->exc_state.exc_traceback; - tstate->exc_state.exc_type = *type; - tstate->exc_state.exc_value = *value; - tstate->exc_state.exc_traceback = *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; @@ -13304,13 +21000,29 @@ } #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 +#if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { - #if PY_VERSION_HEX >= 0x030700A2 - *type = tstate->exc_state.exc_type; - *value = tstate->exc_state.exc_value; - *tb = tstate->exc_state.exc_traceback; + #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; @@ -13322,54 +21034,30 @@ } static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; - #if PY_VERSION_HEX >= 0x030700A2 - tmp_type = tstate->exc_state.exc_type; - tmp_value = tstate->exc_state.exc_value; - tmp_tb = tstate->exc_state.exc_traceback; - tstate->exc_state.exc_type = type; - tstate->exc_state.exc_value = value; - tstate->exc_state.exc_traceback = 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); + 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 /* decode_c_string */ - static CYTHON_INLINE PyObject* __Pyx_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)) { @@ -13402,7 +21090,7 @@ } /* UnpackUnboundCMethod */ - static int __Pyx_TryUnpackUnboundCMethod(__Pyx_CachedCFunction* target) { +static int __Pyx_TryUnpackUnboundCMethod(__Pyx_CachedCFunction* target) { PyObject *method; method = __Pyx_PyObject_GetAttrStr(target->type, *target->method_name); if (unlikely(!method)) @@ -13415,14 +21103,14 @@ { PyMethodDescrObject *descr = (PyMethodDescrObject*) method; target->func = descr->d_method->ml_meth; - target->flag = descr->d_method->ml_flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST); + target->flag = descr->d_method->ml_flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_STACKLESS); } #endif return 0; } /* CallUnboundCMethod1 */ - #if CYTHON_COMPILING_IN_CPYTHON +#if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_CallUnboundCMethod1(__Pyx_CachedCFunction* cfunc, PyObject* self, PyObject* arg) { if (likely(cfunc->func)) { int flag = cfunc->flag; @@ -13430,12 +21118,12 @@ return (*(cfunc->func))(self, arg); } else if (PY_VERSION_HEX >= 0x030600B1 && flag == METH_FASTCALL) { if (PY_VERSION_HEX >= 0x030700A0) { - return (*(__Pyx_PyCFunctionFast)cfunc->func)(self, &arg, 1); + return (*(__Pyx_PyCFunctionFast)(void*)(PyCFunction)cfunc->func)(self, &arg, 1); } else { - return (*(__Pyx_PyCFunctionFastWithKeywords)cfunc->func)(self, &arg, 1, NULL); + return (*(__Pyx_PyCFunctionFastWithKeywords)(void*)(PyCFunction)cfunc->func)(self, &arg, 1, NULL); } } else if (PY_VERSION_HEX >= 0x030700A0 && flag == (METH_FASTCALL | METH_KEYWORDS)) { - return (*(__Pyx_PyCFunctionFastWithKeywords)cfunc->func)(self, &arg, 1, NULL); + return (*(__Pyx_PyCFunctionFastWithKeywords)(void*)(PyCFunction)cfunc->func)(self, &arg, 1, NULL); } } return __Pyx__CallUnboundCMethod1(cfunc, self, arg); @@ -13451,7 +21139,7 @@ Py_INCREF(arg); PyTuple_SET_ITEM(args, 0, arg); if (cfunc->flag & METH_KEYWORDS) - result = (*(PyCFunctionWithKeywords)cfunc->func)(self, args, NULL); + result = (*(PyCFunctionWithKeywords)(void*)(PyCFunction)cfunc->func)(self, args, NULL); else result = (*cfunc->func)(self, args); } else { @@ -13473,68 +21161,105 @@ return result; } -/* 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; - } +/* 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; } - return 0; -#else - if (unlikely(PyErr_Occurred())) { - if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { - PyErr_Clear(); - return 0; - } else { - return -1; + 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 (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 } } - return 0; -#endif +bad: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); + Py_XDECREF(empty_dict); + return module; } -/* UnpackItemEndCheck */ - static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { - if (unlikely(retval)) { - Py_DECREF(retval); - __Pyx_RaiseTooManyValuesError(expected); +/* 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 { - return __Pyx_IterFinish(); + Py_DECREF(r); + return 1; } - return 0; } /* PyObject_GenericGetAttrNoDict */ - #if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 +#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 @@ -13574,7 +21299,7 @@ #endif /* PyObject_GenericGetAttr */ - #if CYTHON_USE_TYPE_SLOTS && CYTHON_USE_PYTYPE_LOOKUP && PY_VERSION_HEX < 0x03070000 +#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); @@ -13583,26 +21308,8 @@ } #endif -/* 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; -} - /* SetupReduce */ - static int __Pyx_setup_reduce_is_named(PyObject* meth, PyObject* name) { +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); @@ -13677,98 +21384,103 @@ return ret; } -/* 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) +/* 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; - empty_dict = PyDict_New(); - if (!empty_dict) + if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0) goto bad; - { - #if PY_MAJOR_VERSION >= 3 - if (level == -1) { - if (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, NULL); - Py_DECREF(py_level); - #else - module = PyImport_ImportModuleLevelObject( - name, global_dict, empty_dict, list, level); - #endif - } - } + Py_DECREF(ob); + return 0; bad: - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(py_import); - #endif - Py_XDECREF(empty_list); - Py_XDECREF(empty_dict); - return module; + Py_XDECREF(ob); + return -1; } -/* 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 +/* 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; } - return value; + 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 /* CLineInTraceback */ - #ifndef CYTHON_CLINE_IN_TRACEBACK -static int __Pyx_CLineForTraceback(CYTHON_UNUSED PyThreadState *tstate, int c_line) { +#ifndef CYTHON_CLINE_IN_TRACEBACK +static int __Pyx_CLineForTraceback(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)) { - use_cline = __Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_n_s_cline_in_traceback); + __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 { @@ -13785,7 +21497,7 @@ c_line = 0; PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False); } - else if (PyObject_Not(use_cline) != 0) { + else if (use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { c_line = 0; } __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); @@ -13794,7 +21506,7 @@ #endif /* CodeObjectCache */ - static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { +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; @@ -13874,7 +21586,7 @@ } /* AddTraceback */ - #include "compile.h" +#include "compile.h" #include "frameobject.h" #include "traceback.h" static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( @@ -13958,8 +21670,39 @@ Py_XDECREF(py_frame); } +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { + const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 0; + 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); + } +} + /* CIntFromPyVerify */ - #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ +#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) @@ -13981,163 +21724,510 @@ } /* CIntToPy */ - static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { - const int neg_one = (int) -1, const_zero = (int) 0; +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_unsigned_int(unsigned int value) { + const unsigned int neg_one = (unsigned int) ((unsigned int) 0 - (unsigned int) 1), const_zero = (unsigned int) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { - if (sizeof(int) < sizeof(long)) { + if (sizeof(unsigned int) < sizeof(long)) { return PyInt_FromLong((long) value); - } else if (sizeof(int) <= sizeof(unsigned long)) { + } else if (sizeof(unsigned int) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG - } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { + } else if (sizeof(unsigned int) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(unsigned int) <= sizeof(long)) { + return PyInt_FromLong((long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(unsigned 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(unsigned int), + little, !is_unsigned); + } +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_unsigned_short(unsigned short value) { + const unsigned short neg_one = (unsigned short) ((unsigned short) 0 - (unsigned short) 1), const_zero = (unsigned short) 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(unsigned short) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(unsigned short) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(unsigned short) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(unsigned short) <= sizeof(long)) { + return PyInt_FromLong((long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(unsigned short) <= 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(unsigned short), + little, !is_unsigned); + } +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { + const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0; + 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); + } +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_uint16_t(uint16_t value) { + const uint16_t neg_one = (uint16_t) ((uint16_t) 0 - (uint16_t) 1), const_zero = (uint16_t) 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(uint16_t) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(uint16_t) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(uint16_t) <= 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); + } + } else { + if (sizeof(uint16_t) <= sizeof(long)) { + return PyInt_FromLong((long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(uint16_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(uint16_t), + little, !is_unsigned); + } +} + +/* CIntFromPy */ +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { + const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 0; + 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)) { - return PyLong_FromLongLong((PY_LONG_LONG) value); + } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { + __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) #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); - } -} - -/* CIntToPy */ - static CYTHON_INLINE PyObject* __Pyx_PyInt_From_unsigned_int(unsigned int value) { - const unsigned int neg_one = (unsigned int) -1, const_zero = (unsigned int) 0; - const int is_unsigned = neg_one > const_zero; - if (is_unsigned) { - if (sizeof(unsigned int) < sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof(unsigned int) <= sizeof(unsigned long)) { - return PyLong_FromUnsignedLong((unsigned long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(unsigned int) <= sizeof(unsigned PY_LONG_LONG)) { - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); + { +#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 { - if (sizeof(unsigned int) <= sizeof(long)) { - return PyInt_FromLong((long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(unsigned 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(unsigned int), - little, !is_unsigned); + 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; } -/* CIntToPy */ - static CYTHON_INLINE PyObject* __Pyx_PyInt_From_unsigned_short(unsigned short value) { - const unsigned short neg_one = (unsigned short) -1, const_zero = (unsigned short) 0; +/* CIntFromPy */ +static CYTHON_INLINE enum http_method __Pyx_PyInt_As_enum__http_method(PyObject *x) { + const enum http_method neg_one = (enum http_method) ((enum http_method) 0 - (enum http_method) 1), const_zero = (enum http_method) 0; const int is_unsigned = neg_one > const_zero; - if (is_unsigned) { - if (sizeof(unsigned short) < sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof(unsigned short) <= sizeof(unsigned long)) { - return PyLong_FromUnsignedLong((unsigned long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(unsigned short) <= sizeof(unsigned PY_LONG_LONG)) { - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); -#endif +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(enum http_method) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(enum http_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 http_method) val; } - } else { - if (sizeof(unsigned short) <= sizeof(long)) { - return PyInt_FromLong((long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(unsigned short) <= sizeof(PY_LONG_LONG)) { - return PyLong_FromLongLong((PY_LONG_LONG) value); + } else #endif - } - } - { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&value; - return _PyLong_FromByteArray(bytes, sizeof(unsigned short), - little, !is_unsigned); - } -} - -/* CIntToPy */ - static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { - const long neg_one = (long) -1, const_zero = (long) 0; - 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); + 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 http_method) 0; + case 1: __PYX_VERIFY_RETURN_INT(enum http_method, digit, digits[0]) + case 2: + if (8 * sizeof(enum http_method) > 1 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(enum http_method, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(enum http_method) >= 2 * PyLong_SHIFT) { + return (enum http_method) (((((enum http_method)digits[1]) << PyLong_SHIFT) | (enum http_method)digits[0])); + } + } + break; + case 3: + if (8 * sizeof(enum http_method) > 2 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(enum http_method, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(enum http_method) >= 3 * PyLong_SHIFT) { + return (enum http_method) (((((((enum http_method)digits[2]) << PyLong_SHIFT) | (enum http_method)digits[1]) << PyLong_SHIFT) | (enum http_method)digits[0])); + } + } + break; + case 4: + if (8 * sizeof(enum http_method) > 3 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(enum http_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 http_method) >= 4 * PyLong_SHIFT) { + return (enum http_method) (((((((((enum http_method)digits[3]) << PyLong_SHIFT) | (enum http_method)digits[2]) << PyLong_SHIFT) | (enum http_method)digits[1]) << PyLong_SHIFT) | (enum http_method)digits[0])); + } + } + break; + } #endif - } - } else { - if (sizeof(long) <= sizeof(long)) { - return PyInt_FromLong((long) value); +#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 http_method) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if (sizeof(enum http_method) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT_EXC(enum http_method, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG - } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { - return PyLong_FromLongLong((PY_LONG_LONG) value); + } else if (sizeof(enum http_method) <= sizeof(unsigned PY_LONG_LONG)) { + __PYX_VERIFY_RETURN_INT_EXC(enum http_method, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #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); - } -} - -/* CIntToPy */ - static CYTHON_INLINE PyObject* __Pyx_PyInt_From_uint16_t(uint16_t value) { - const uint16_t neg_one = (uint16_t) -1, const_zero = (uint16_t) 0; - const int is_unsigned = neg_one > const_zero; - if (is_unsigned) { - if (sizeof(uint16_t) < sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof(uint16_t) <= sizeof(unsigned long)) { - return PyLong_FromUnsignedLong((unsigned long) value); + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + const digit* digits = ((PyLongObject*)x)->ob_digit; + switch (Py_SIZE(x)) { + case 0: return (enum http_method) 0; + case -1: __PYX_VERIFY_RETURN_INT(enum http_method, sdigit, (sdigit) (-(sdigit)digits[0])) + case 1: __PYX_VERIFY_RETURN_INT(enum http_method, digit, +digits[0]) + case -2: + if (8 * sizeof(enum http_method) - 1 > 1 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(enum http_method, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(enum http_method) - 1 > 2 * PyLong_SHIFT) { + return (enum http_method) (((enum http_method)-1)*(((((enum http_method)digits[1]) << PyLong_SHIFT) | (enum http_method)digits[0]))); + } + } + break; + case 2: + if (8 * sizeof(enum http_method) > 1 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(enum http_method, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(enum http_method) - 1 > 2 * PyLong_SHIFT) { + return (enum http_method) ((((((enum http_method)digits[1]) << PyLong_SHIFT) | (enum http_method)digits[0]))); + } + } + break; + case -3: + if (8 * sizeof(enum http_method) - 1 > 2 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(enum http_method, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(enum http_method) - 1 > 3 * PyLong_SHIFT) { + return (enum http_method) (((enum http_method)-1)*(((((((enum http_method)digits[2]) << PyLong_SHIFT) | (enum http_method)digits[1]) << PyLong_SHIFT) | (enum http_method)digits[0]))); + } + } + break; + case 3: + if (8 * sizeof(enum http_method) > 2 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(enum http_method, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(enum http_method) - 1 > 3 * PyLong_SHIFT) { + return (enum http_method) ((((((((enum http_method)digits[2]) << PyLong_SHIFT) | (enum http_method)digits[1]) << PyLong_SHIFT) | (enum http_method)digits[0]))); + } + } + break; + case -4: + if (8 * sizeof(enum http_method) - 1 > 3 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(enum http_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 http_method) - 1 > 4 * PyLong_SHIFT) { + return (enum http_method) (((enum http_method)-1)*(((((((((enum http_method)digits[3]) << PyLong_SHIFT) | (enum http_method)digits[2]) << PyLong_SHIFT) | (enum http_method)digits[1]) << PyLong_SHIFT) | (enum http_method)digits[0]))); + } + } + break; + case 4: + if (8 * sizeof(enum http_method) > 3 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(enum http_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 http_method) - 1 > 4 * PyLong_SHIFT) { + return (enum http_method) ((((((((((enum http_method)digits[3]) << PyLong_SHIFT) | (enum http_method)digits[2]) << PyLong_SHIFT) | (enum http_method)digits[1]) << PyLong_SHIFT) | (enum http_method)digits[0]))); + } + } + break; + } +#endif + if (sizeof(enum http_method) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT_EXC(enum http_method, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG - } else if (sizeof(uint16_t) <= sizeof(unsigned PY_LONG_LONG)) { - return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); + } else if (sizeof(enum http_method) <= sizeof(PY_LONG_LONG)) { + __PYX_VERIFY_RETURN_INT_EXC(enum http_method, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif + } } - } else { - if (sizeof(uint16_t) <= sizeof(long)) { - return PyInt_FromLong((long) value); -#ifdef HAVE_LONG_LONG - } else if (sizeof(uint16_t) <= sizeof(PY_LONG_LONG)) { - return PyLong_FromLongLong((PY_LONG_LONG) value); + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + enum http_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 http_method) -1; } + } else { + enum http_method val; + PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); + if (!tmp) return (enum http_method) -1; + val = __Pyx_PyInt_As_enum__http_method(tmp); + Py_DECREF(tmp); + return val; } - { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&value; - return _PyLong_FromByteArray(bytes, sizeof(uint16_t), - little, !is_unsigned); - } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to enum http_method"); + return (enum http_method) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to enum http_method"); + return (enum http_method) -1; } /* CIntFromPy */ - static CYTHON_INLINE size_t __Pyx_PyInt_As_size_t(PyObject *x) { - const size_t neg_one = (size_t) -1, const_zero = (size_t) 0; +static CYTHON_INLINE size_t __Pyx_PyInt_As_size_t(PyObject *x) { + const size_t neg_one = (size_t) ((size_t) 0 - (size_t) 1), const_zero = (size_t) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { @@ -14325,8 +22415,8 @@ } /* CIntFromPy */ - static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { - const long neg_one = (long) -1, const_zero = (long) 0; +static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { + const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { @@ -14466,316 +22556,1234 @@ } 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; +} + +/* 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 CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); + } + 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 - 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; - } + tstate = __Pyx_PyThreadState_Current; #endif - return (long) -1; + 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 { - long val; - PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); - if (!tmp) return (long) -1; - val = __Pyx_PyInt_As_long(tmp); - Py_DECREF(tmp); - return val; + __Pyx_Coroutine_ExceptionClear(exc_state); + __Pyx_ExceptionSave(&exc_state->exc_type, &exc_state->exc_value, &exc_state->exc_traceback); } -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) { - const int neg_one = (int) -1, const_zero = (int) 0; - 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; - } + 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 -#if CYTHON_COMPILING_IN_CPYTHON - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } + 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 - { - 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)) + 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; +} +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 = _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 = _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 { -#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)) + 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 = _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"; } - { -#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); + 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; } - #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; + if (likely(args)) { + ret = PyObject_CallObject(meth, args); + } else { + ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL); } -#endif - return (int) -1; + Py_DECREF(meth); } - } 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; + 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); } - -/* 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_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 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; +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_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 (self->ob_refcnt > 0) +#endif + { + return; } - return 0; + PyObject_GC_UnTrack(self); } - 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; +#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); + self->ob_refcnt = 1; +#endif __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; + __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; + } } - if (!res) { - res = PyObject_IsSubclass(err, exc_type2); - if (unlikely(res == -1)) { - PyErr_WriteUnraisable(err); - res = 0; +#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(exception, value, tb); - return res; + __Pyx_ErrRestore(error_type, error_value, error_traceback); +#if !CYTHON_USE_TP_FINALIZE + assert(self->ob_refcnt > 0); + if (--self->ob_refcnt == 0) { + return; + } + { + Py_ssize_t refcnt = self->ob_refcnt; + _Py_NewReference(self); + self->ob_refcnt = refcnt; + } +#if CYTHON_COMPILING_IN_CPYTHON + assert(PyType_IS_GC(self->ob_type) && + _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 -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); + if (unlikely(value == NULL || !PyString_Check(value))) +#endif + { + PyErr_SetString(PyExc_TypeError, + "__name__ must be set to a string object"); + return -1; } - return res; + 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 -static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject* exc_type) { - if (likely(err == exc_type)) return 1; - if (likely(PyExceptionClass_Check(err))) { - return __Pyx_inner_PyErr_GivenExceptionMatches2(err, NULL, exc_type); + { + PyErr_SetString(PyExc_TypeError, + "__qualname__ must be set to a string object"); + return -1; } - return PyErr_GivenExceptionMatches(err, exc_type); + tmp = self->gi_qualname; + Py_INCREF(value); + self->gi_qualname = value; + Py_XDECREF(tmp); + return 0; } -static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *exc_type1, PyObject *exc_type2) { - if (likely(err == exc_type1 || err == exc_type2)) return 1; - if (likely(PyExceptionClass_Check(err))) { - return __Pyx_inner_PyErr_GivenExceptionMatches2(err, exc_type1, exc_type2); +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; + 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; } - return (PyErr_GivenExceptionMatches(err, exc_type1) || PyErr_GivenExceptionMatches(err, exc_type2)); +#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}, + {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 +}; +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) { +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()); @@ -14790,91 +23798,8 @@ return 0; } -/* ModuleImport */ - #ifndef __PYX_HAVE_RT_ImportModule -#define __PYX_HAVE_RT_ImportModule -static PyObject *__Pyx_ImportModule(const char *name) { - PyObject *py_name = 0; - PyObject *py_module = 0; - py_name = __Pyx_PyIdentifier_FromString(name); - if (!py_name) - goto bad; - py_module = PyImport_Import(py_name); - Py_DECREF(py_name); - return py_module; -bad: - Py_XDECREF(py_name); - return 0; -} -#endif - -/* TypeImport */ - #ifndef __PYX_HAVE_RT_ImportType -#define __PYX_HAVE_RT_ImportType -static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, - size_t size, int strict) -{ - PyObject *py_module = 0; - PyObject *result = 0; - PyObject *py_name = 0; - char warning[200]; - Py_ssize_t basicsize; -#ifdef Py_LIMITED_API - PyObject *py_basicsize; -#endif - py_module = __Pyx_ImportModule(module_name); - if (!py_module) - goto bad; - py_name = __Pyx_PyIdentifier_FromString(class_name); - if (!py_name) - goto bad; - result = PyObject_GetAttr(py_module, py_name); - Py_DECREF(py_name); - py_name = 0; - Py_DECREF(py_module); - py_module = 0; - 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 (!strict && (size_t)basicsize > size) { - PyOS_snprintf(warning, sizeof(warning), - "%s.%s size changed, may indicate binary incompatibility. Expected %zd, got %zd", - module_name, class_name, basicsize, size); - if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; - } - else if ((size_t)basicsize != size) { - PyErr_Format(PyExc_ValueError, - "%.200s.%.200s has the wrong size, try recompiling. Expected %zd, got %zd", - module_name, class_name, basicsize, size); - goto bad; - } - return (PyTypeObject *)result; -bad: - Py_XDECREF(py_module); - Py_XDECREF(result); - return NULL; -} -#endif - /* InitStrings */ - static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { +static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { #if PY_MAJOR_VERSION < 3 if (t->is_unicode) { @@ -14983,6 +23908,13 @@ 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)) { @@ -15060,7 +23992,7 @@ if (sizeof(Py_ssize_t) >= sizeof(long)) return PyInt_AS_LONG(b); else - return PyInt_AsSsize_t(x); + return PyInt_AsSsize_t(b); } #endif if (likely(PyLong_CheckExact(b))) { @@ -15114,6 +24046,9 @@ 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); } diff -Nru python-aiohttp-3.1.3/aiohttp/http_parser.py python-aiohttp-3.5.1/aiohttp/http_parser.py --- python-aiohttp-3.1.3/aiohttp/http_parser.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/http_parser.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,20 +1,25 @@ +import abc +import asyncio import collections import re import string import zlib from enum import IntEnum +from typing import Any, List, Optional, Tuple, Type, Union # noqa -from multidict import CIMultiDict +from multidict import CIMultiDict, CIMultiDictProxy, istr from yarl import URL from . import hdrs -from .helpers import NO_EXTENSIONS +from .base_protocol import BaseProtocol +from .helpers import NO_EXTENSIONS, BaseTimerContext from .http_exceptions import (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 RawHeaders try: @@ -25,11 +30,19 @@ __all__ = ( - 'HttpParser', 'HttpRequestParser', 'HttpResponseParser', + 'HeadersParser', 'HttpParser', 'HttpRequestParser', 'HttpResponseParser', 'RawRequestMessage', 'RawResponseMessage') ASCIISET = set(string.printable) -METHRE = re.compile('[A-Z0-9$-_.]+') + +# 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 = re.compile(r"[!#$%&'*+\-.^_`|~0-9A-Za-z]+") VERSRE = re.compile(r'HTTP/(\d+).(\d+)') HDRRE = re.compile(rb'[\x00-\x1F\x7F()<>@,;:\[\]={} \t\\\\\"]') @@ -60,14 +73,108 @@ PARSE_TRAILERS = 4 -class HttpParser: +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): - def __init__(self, protocol=None, loop=None, - max_line_size=8190, max_headers=32768, max_field_size=8190, - timer=None, code=None, method=None, readall=False, - payload_exception=None, - response_with_body=True, read_until_eof=False, - auto_decompress=True): + def __init__(self, protocol: Optional[BaseProtocol]=None, + loop: Optional[asyncio.AbstractEventLoop]=None, + 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 @@ -81,14 +188,21 @@ self.response_with_body = response_with_body self.read_until_eof = read_until_eof - self._lines = [] + self._lines = [] # type: List[bytes] self._tail = b'' self._upgraded = False self._payload = None - self._payload_parser = None + self._payload_parser = None # type: Optional[HttpPayloadParser] self._auto_decompress = auto_decompress + self._headers_parser = HeadersParser(max_line_size, + max_headers, + max_field_size) + + @abc.abstractmethod + def parse_message(self, lines: List[bytes]) -> Any: + pass - def feed_eof(self): + def feed_eof(self) -> Any: if self._payload_parser is not None: self._payload_parser.feed_eof() self._payload_parser = None @@ -99,17 +213,21 @@ if self._lines: if self._lines[-1] != '\r\n': - self._lines.append('') + self._lines.append(b'') try: return self.parse_message(self._lines) except Exception: return None - def feed_data(self, data, - SEP=b'\r\n', EMPTY=b'', - CONTENT_LENGTH=hdrs.CONTENT_LENGTH, - METH_CONNECT=hdrs.METH_CONNECT, - SEC_WEBSOCKET_KEY1=hdrs.SEC_WEBSOCKET_KEY1): + 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[Any], bool, bytes]: messages = [] @@ -161,6 +279,7 @@ 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): @@ -198,7 +317,7 @@ if not payload_parser.done: self._payload_parser = payload_parser else: - payload = EMPTY_PAYLOAD + payload = EMPTY_PAYLOAD # type: ignore messages.append((msg, payload)) else: @@ -214,6 +333,7 @@ # 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:]) @@ -242,88 +362,25 @@ return messages, self._upgraded, data - def parse_headers(self, lines): + 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 = CIMultiDict() - 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")), - self.max_field_size, - 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 = [bvalue] - while continuation: - header_length += len(line) - if header_length > self.max_field_size: - raise LineTooLong( - 'request header field {}'.format( - bname.decode("utf8", "xmlcharrefreplace")), - self.max_field_size, - header_length) - bvalue.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) - else: - if header_length > self.max_field_size: - raise LineTooLong( - 'request header field {}'.format( - bname.decode("utf8", "xmlcharrefreplace")), - self.max_field_size, - 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)) - + headers, raw_headers = self._headers_parser.parse_headers(lines) close_conn = None encoding = None upgrade = False chunked = False - raw_headers = tuple(raw_headers) # keep-alive conn = headers.get(hdrs.CONNECTION) @@ -348,16 +405,16 @@ if te and 'chunked' in te.lower(): chunked = True - return headers, raw_headers, close_conn, encoding, upgrade, chunked + return (headers, raw_headers, close_conn, encoding, upgrade, chunked) -class HttpRequestParserPy(HttpParser): +class HttpRequestParser(HttpParser): """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): + def parse_message(self, lines: List[bytes]) -> Any: # request line line = lines[0].decode('utf-8', 'surrogateescape') try: @@ -367,10 +424,11 @@ if len(path) > self.max_line_size: raise LineTooLong( - 'Status line is too long', self.max_line_size, len(path)) + 'Status line is too long', + str(self.max_line_size), + str(len(path))) # method - method = method.upper() if not METHRE.match(method): raise BadStatusLine(method) @@ -378,34 +436,34 @@ try: if version.startswith('HTTP/'): n1, n2 = version[5:].split('.', 1) - version = HttpVersion(int(n1), int(n2)) + 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) + (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 <= HttpVersion10: # HTTP 1.0 must asks to not close + 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, headers, raw_headers, + method, path, version_o, headers, raw_headers, close, compression, upgrade, chunked, URL(path)) -class HttpResponseParserPy(HttpParser): +class HttpResponseParser(HttpParser): """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): + def parse_message(self, lines: List[bytes]) -> Any: line = lines[0].decode('utf-8', 'surrogateescape') try: version, status = line.split(None, 1) @@ -419,44 +477,48 @@ if len(reason) > self.max_line_size: raise LineTooLong( - 'Status line is too long', self.max_line_size, - len(reason)) + '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 = HttpVersion(int(match.group(1)), int(match.group(2))) + version_o = HttpVersion(int(match.group(1)), int(match.group(2))) # The status code is a three-digit number try: - status = int(status) + status_i = int(status) except ValueError: raise BadStatusLine(line) from None - if status > 999: + if status_i > 999: raise BadStatusLine(line) # read headers - headers, raw_headers, \ - close, compression, upgrade, chunked = self.parse_headers(lines) + (headers, raw_headers, + close, compression, upgrade, chunked) = self.parse_headers(lines) if close is None: - close = version <= HttpVersion10 + close = version_o <= HttpVersion10 return RawResponseMessage( - version, status, reason.strip(), + version_o, status_i, reason.strip(), headers, raw_headers, close, compression, upgrade, chunked) class HttpPayloadParser: - def __init__(self, payload, - length=None, chunked=False, compression=None, - code=None, method=None, - readall=False, response_with_body=True, auto_decompress=True): - self.payload = payload - + 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 @@ -467,13 +529,15 @@ # payload decompression wrapper if response_with_body and compression and self._auto_decompress: - payload = DeflateBuffer(payload, compression) + real_payload = DeflateBuffer(payload, compression) # type: Union[StreamReader, DeflateBuffer] # noqa + 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 - payload.feed_eof() + real_payload.feed_eof() self.done = True elif chunked: @@ -482,7 +546,7 @@ self._type = ParseState.PARSE_LENGTH self._length = length if self._length == 0: - payload.feed_eof() + real_payload.feed_eof() self.done = True else: if readall and code != 204: @@ -491,12 +555,12 @@ internal_logger.warning( # pragma: no cover 'Content-Length or Transfer-Encoding header is required') self._type = ParseState.PARSE_NONE - payload.feed_eof() + real_payload.feed_eof() self.done = True - self.payload = payload + self.payload = real_payload - def feed_eof(self): + def feed_eof(self) -> None: if self._type == ParseState.PARSE_UNTIL_EOF: self.payload.feed_eof() elif self._type == ParseState.PARSE_LENGTH: @@ -506,7 +570,10 @@ raise TransferEncodingError( "Not enough data for satisfy transfer length header.") - def feed_data(self, chunk, SEP=b'\r\n', CHUNK_EXT=b';'): + 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 @@ -538,14 +605,15 @@ if pos >= 0: i = chunk.find(CHUNK_EXT, 0, pos) if i >= 0: - size = chunk[:i] # strip chunk-extensions + size_b = chunk[:i] # strip chunk-extensions else: - size = chunk[:pos] + size_b = chunk[:pos] try: - size = int(bytes(size), 16) + size = int(bytes(size_b), 16) except ValueError: - exc = TransferEncodingError(chunk[:pos]) + exc = TransferEncodingError( + chunk[:pos].decode('ascii', 'surrogateescape')) self.payload.set_exception(exc) raise exc from None @@ -558,7 +626,7 @@ self.payload.begin_http_chunk_receiving() else: self._chunk_tail = chunk - return False, None + return False, b'' # read chunk and feed buffer if self._chunk == ChunkState.PARSE_CHUNKED_CHUNK: @@ -568,7 +636,7 @@ if required > chunk_len: self._chunk_size = required - chunk_len self.payload.feed_data(chunk, chunk_len) - return False, None + return False, b'' else: self._chunk_size = 0 self.payload.feed_data(chunk[:required], required) @@ -583,7 +651,7 @@ self._chunk = ChunkState.PARSE_CHUNKED_SIZE else: self._chunk_tail = chunk - return False, None + return False, b'' # if stream does not contain trailer, after 0\r\n # we should get another \r\n otherwise @@ -604,19 +672,19 @@ self._chunk = ChunkState.PARSE_MAYBE_TRAILERS else: self._chunk_tail = chunk - return False, None + return False, b'' # Read all bytes until eof elif self._type == ParseState.PARSE_UNTIL_EOF: self.payload.feed_data(chunk, len(chunk)) - return False, None + return False, b'' class DeflateBuffer: """DeflateStream decompress stream and feed data into specified stream.""" - def __init__(self, out, encoding): + def __init__(self, out: StreamReader, encoding: Optional[str]) -> None: self.out = out self.size = 0 self.encoding = encoding @@ -633,10 +701,10 @@ if encoding == 'gzip' else -zlib.MAX_WBITS) self.decompressor = zlib.decompressobj(wbits=zlib_mode) - def set_exception(self, exc): + def set_exception(self, exc: BaseException) -> None: self.out.set_exception(exc) - def feed_data(self, chunk, size): + def feed_data(self, chunk: bytes, size: int) -> None: self.size += size try: chunk = self.decompressor.decompress(chunk) @@ -656,29 +724,37 @@ self._started_decoding = True self.out.feed_data(chunk, len(chunk)) - def feed_eof(self): + 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 != 'br' and not self.decompressor.eof: + if self.encoding == 'deflate' and not self.decompressor.eof: raise ContentEncodingError('deflate') self.out.feed_eof() - def begin_http_chunk_receiving(self): + def begin_http_chunk_receiving(self) -> None: self.out.begin_http_chunk_receiving() - def end_http_chunk_receiving(self): + def end_http_chunk_receiving(self) -> None: self.out.end_http_chunk_receiving() -HttpRequestParser = HttpRequestParserPy -HttpResponseParser = HttpResponseParserPy +HttpRequestParserPy = HttpRequestParser +HttpResponseParserPy = HttpResponseParser +RawRequestMessagePy = RawRequestMessage +RawResponseMessagePy = RawResponseMessage + try: - from ._http_parser import HttpRequestParserC, HttpResponseParserC - if not NO_EXTENSIONS: # pragma: no cover - HttpRequestParser = HttpRequestParserC - HttpResponseParser = HttpResponseParserC + if not NO_EXTENSIONS: + from ._http_parser import (HttpRequestParser, # type: ignore # noqa + HttpResponseParser, + RawRequestMessage, + RawResponseMessage) + HttpRequestParserC = HttpRequestParser + HttpResponseParserC = HttpResponseParser + RawRequestMessageC = RawRequestMessage + RawResponseMessageC = RawResponseMessage except ImportError: # pragma: no cover pass diff -Nru python-aiohttp-3.1.3/aiohttp/_http_parser.pyx python-aiohttp-3.5.1/aiohttp/_http_parser.pyx --- python-aiohttp-3.1.3/aiohttp/_http_parser.pyx 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/_http_parser.pyx 2018-12-24 20:58:54.000000000 +0000 @@ -4,28 +4,252 @@ # from __future__ import absolute_import, print_function from cpython.mem cimport PyMem_Malloc, PyMem_Free -from cpython cimport PyObject_GetBuffer, PyBuffer_Release, PyBUF_SIMPLE, \ - Py_buffer, PyBytes_AsString - -from multidict import CIMultiDict -from yarl import URL +from libc.string cimport memcpy +from cpython cimport (PyObject_GetBuffer, PyBuffer_Release, PyBUF_SIMPLE, + Py_buffer, PyBytes_AsString, PyBytes_AsStringAndSize) + +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, InvalidHeader, LineTooLong, InvalidURLError, PayloadEncodingError, ContentLengthError, TransferEncodingError) -from .http_writer import HttpVersion, HttpVersion10, HttpVersion11 -from .http_parser import RawRequestMessage, RawResponseMessage, DeflateBuffer -from .streams import EMPTY_PAYLOAD, StreamReader +from .http_writer import (HttpVersion as _HttpVersion, + HttpVersion10 as _HttpVersion10, + HttpVersion11 as _HttpVersion11) +from .http_parser import DeflateBuffer as _DeflateBuffer +from .streams import (EMPTY_PAYLOAD as _EMPTY_PAYLOAD, + StreamReader as _StreamReader) cimport cython -from . cimport _cparser as cparser +from aiohttp cimport _cparser as cparser + +include "_headers.pxi" +from aiohttp cimport _find_header -__all__ = ('HttpRequestParserC', 'HttpResponseMessageC', 'parse_url') +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 = 34; + +cdef list _http_method = [] + +for i in range(METHODS_COUNT): + _http_method.append( + cparser.http_method_str( 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: @@ -34,10 +258,9 @@ cparser.http_parser* _cparser cparser.http_parser_settings* _csettings - str _header_name - str _header_value - bytes _raw_header_name - bytes _raw_header_value + bytearray _raw_name + bytearray _raw_value + bint _has_value object _protocol object _loop @@ -53,7 +276,7 @@ bytearray _buf str _path str _reason - list _headers + object _headers list _raw_headers bint _upgraded list _messages @@ -63,6 +286,8 @@ object _last_error bint _auto_decompress + str _content_encoding + Py_buffer py_buf def __cinit__(self): @@ -84,7 +309,7 @@ object protocol, object loop, object timer=None, size_t max_line_size=8190, size_t max_headers=32768, size_t max_field_size=8190, payload_exception=None, - response_with_body=True, auto_decompress=True): + bint response_with_body=True, bint auto_decompress=True): cparser.http_parser_init(self._cparser, mode) self._cparser.data = self self._cparser.content_length = 0 @@ -101,10 +326,9 @@ self._payload_exception = payload_exception self._messages = [] - self._header_name = None - self._header_value = None - self._raw_header_name = None - self._raw_header_value = None + self._raw_name = bytearray() + self._raw_value = bytearray() + self._has_value = False self._max_line_size = max_line_size self._max_headers = max_headers @@ -112,6 +336,7 @@ self._response_with_body = response_with_body 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 @@ -127,54 +352,54 @@ self._last_error = None cdef _process_header(self): - if self._header_name is not None: - name = self._header_name - value = self._header_value + 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._header_name = self._header_value = None - self._headers.append((name, value)) + self._headers.add(name, value) - raw_name = self._raw_header_name - raw_value = self._raw_header_value + if name is CONTENT_ENCODING: + self._content_encoding = value - self._raw_header_name = self._raw_header_value = None + 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, str field, bytes raw_field): - if self._header_value is not None: + 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() - self._header_value = None - if self._header_name is None: - self._header_name = field - self._raw_header_name = raw_field - else: - self._header_name += field - self._raw_header_name += raw_field - - cdef _on_header_value(self, str val, bytes raw_val): - if self._header_value is None: - self._header_value = val - self._raw_header_value = raw_val - else: - self._header_value += val - self._raw_header_value += raw_val + 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, - ENCODING='utf-8', - ENCODING_ERR='surrogateescape', - CONTENT_ENCODING=hdrs.CONTENT_ENCODING, - SEC_WEBSOCKET_KEY1=hdrs.SEC_WEBSOCKET_KEY1, - SUPPORTED=('gzip', 'deflate', 'br')): + cdef _on_headers_complete(self): self._process_header() - method = cparser.http_method_str( self._cparser.method) - should_close = not bool(cparser.http_should_keep_alive(self._cparser)) - upgrade = bool(self._cparser.upgrade) - chunked = bool(self._cparser.flags & cparser.F_CHUNKED) + method = http_method_str(self._cparser.method) + should_close = not cparser.http_should_keep_alive(self._cparser) + upgrade = self._cparser.upgrade + chunked = self._cparser.flags & cparser.F_CHUNKED raw_headers = tuple(self._raw_headers) - headers = CIMultiDict(self._headers) + headers = CIMultiDictProxy(self._headers) if upgrade or self._cparser.method == 5: # cparser.CONNECT: self._upgraded = True @@ -184,19 +409,20 @@ raise InvalidHeader(SEC_WEBSOCKET_KEY1) encoding = None - enc = headers.get(CONTENT_ENCODING) - if enc: + enc = self._content_encoding + if enc is not None: + self._content_encoding = None enc = enc.lower() - if enc in SUPPORTED: + if enc in ('gzip', 'deflate', 'br'): encoding = enc if self._cparser.type == cparser.HTTP_REQUEST: - msg = RawRequestMessage( - method.decode(ENCODING, ENCODING_ERR), self._path, + msg = _new_request_message( + method, self._path, self.http_version(), headers, raw_headers, should_close, encoding, upgrade, chunked, self._url) else: - msg = RawResponseMessage( + msg = _new_response_message( self.http_version(), self._cparser.status_code, self._reason, headers, raw_headers, should_close, encoding, upgrade, chunked) @@ -230,9 +456,7 @@ cdef object _on_status_complete(self): pass - ### Public API ### - - def http_version(self): + cdef inline http_version(self): cdef cparser.http_parser* parser = self._cparser if parser.http_major == 1: @@ -243,6 +467,8 @@ return HttpVersion(parser.http_major, parser.http_minor) + ### Public API ### + def feed_eof(self): cdef bytes desc @@ -308,12 +534,12 @@ return messages, False, b'' -cdef class HttpRequestParserC(HttpParser): +cdef class HttpRequestParser(HttpParser): def __init__(self, protocol, loop, timer=None, size_t max_line_size=8190, size_t max_headers=32768, size_t max_field_size=8190, payload_exception=None, - response_with_body=True, read_until_eof=False): + bint response_with_body=True, bint read_until_eof=False): self._init(cparser.HTTP_REQUEST, protocol, loop, timer, max_line_size, max_headers, max_field_size, payload_exception, response_with_body) @@ -332,16 +558,16 @@ py_buf.len) finally: PyBuffer_Release(&py_buf) - self._buf.clear() + PyByteArray_Resize(self._buf, 0) -cdef class HttpResponseParserC(HttpParser): +cdef class HttpResponseParser(HttpParser): def __init__(self, protocol, loop, timer=None, size_t max_line_size=8190, size_t max_headers=32768, size_t max_field_size=8190, payload_exception=None, - response_with_body=True, read_until_eof=False, - auto_decompress=True): + bint response_with_body=True, bint read_until_eof=False, + bint auto_decompress=True): self._init(cparser.HTTP_RESPONSE, protocol, loop, timer, max_line_size, max_headers, max_field_size, payload_exception, response_with_body, auto_decompress) @@ -349,16 +575,16 @@ cdef object _on_status_complete(self): if self._buf: self._reason = self._buf.decode('utf-8', 'surrogateescape') - self._buf.clear() + PyByteArray_Resize(self._buf, 0) cdef int cb_on_message_begin(cparser.http_parser* parser) except -1: cdef HttpParser pyparser = parser.data pyparser._started = True - pyparser._headers = [] + pyparser._headers = CIMultiDict() pyparser._raw_headers = [] - pyparser._buf.clear() + PyByteArray_Resize(pyparser._buf, 0) pyparser._path = None pyparser._reason = None return 0 @@ -371,7 +597,7 @@ if length > pyparser._max_line_size: raise LineTooLong( 'Status line is too long', pyparser._max_line_size, length) - pyparser._buf.extend(at[:length]) + extend(pyparser._buf, at, length) except BaseException as ex: pyparser._last_error = ex return -1 @@ -387,7 +613,7 @@ if length > pyparser._max_line_size: raise LineTooLong( 'Status line is too long', pyparser._max_line_size, length) - pyparser._buf.extend(at[:length]) + extend(pyparser._buf, at, length) except BaseException as ex: pyparser._last_error = ex return -1 @@ -398,13 +624,14 @@ cdef int cb_on_header_field(cparser.http_parser* parser, const char *at, size_t length) except -1: cdef HttpParser pyparser = parser.data + cdef Py_ssize_t size try: pyparser._on_status_complete() - if length > pyparser._max_field_size: + size = len(pyparser._raw_name) + length + if size > pyparser._max_field_size: raise LineTooLong( - 'Header name is too long', pyparser._max_field_size, length) - pyparser._on_header_field( - at[:length].decode('utf-8', 'surrogateescape'), at[:length]) + '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 @@ -415,17 +642,13 @@ cdef int cb_on_header_value(cparser.http_parser* parser, const char *at, size_t length) except -1: cdef HttpParser pyparser = parser.data + cdef Py_ssize_t size try: - if pyparser._header_value is not None: - if len(pyparser._header_value) + length > pyparser._max_field_size: - raise LineTooLong( - 'Header value is too long', pyparser._max_field_size, - len(pyparser._header_value) + length) - elif length > pyparser._max_field_size: + size = len(pyparser._raw_value) + length + if size > pyparser._max_field_size: raise LineTooLong( - 'Header value is too long', pyparser._max_field_size, length) - pyparser._on_header_value( - at[:length].decode('utf-8', 'surrogateescape'), at[:length]) + '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 @@ -542,7 +765,7 @@ PyBuffer_Release(&py_buf) -def _parse_url(char* buf_data, size_t length): +cdef _parse_url(char* buf_data, size_t length): cdef: cparser.http_parser_url* parsed int res diff -Nru python-aiohttp-3.1.3/aiohttp/http.py python-aiohttp-3.5.1/aiohttp/http.py --- python-aiohttp-3.1.3/aiohttp/http.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/http.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,10 +1,12 @@ import http.server import sys +from typing import Mapping, Tuple # noqa from . import __version__ from .http_exceptions import HttpProcessingError -from .http_parser import (HttpParser, HttpRequestParser, HttpResponseParser, - RawRequestMessage, RawResponseMessage) +from .http_parser import (HeadersParser, HttpParser, HttpRequestParser, + HttpResponseParser, RawRequestMessage, + RawResponseMessage) from .http_websocket import (WS_CLOSED_MESSAGE, WS_CLOSING_MESSAGE, WS_KEY, WebSocketError, WebSocketReader, WebSocketWriter, WSCloseCode, WSMessage, WSMsgType, ws_ext_gen, @@ -20,7 +22,8 @@ 'StreamWriter', 'HttpVersion', 'HttpVersion10', 'HttpVersion11', # .http_parser - 'HttpParser', 'HttpRequestParser', 'HttpResponseParser', + 'HeadersParser', 'HttpParser', + 'HttpRequestParser', 'HttpResponseParser', 'RawRequestMessage', 'RawResponseMessage', # .http_websocket @@ -31,6 +34,6 @@ SERVER_SOFTWARE = 'Python/{0[0]}.{0[1]} aiohttp/{1}'.format( - sys.version_info, __version__) + sys.version_info, __version__) # type: str -RESPONSES = http.server.BaseHTTPRequestHandler.responses +RESPONSES = http.server.BaseHTTPRequestHandler.responses # type: Mapping[int, Tuple[str, str]] # noqa diff -Nru python-aiohttp-3.1.3/aiohttp/http_websocket.py python-aiohttp-3.5.1/aiohttp/http_websocket.py --- python-aiohttp-3.1.3/aiohttp/http_websocket.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/http_websocket.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,5 +1,6 @@ """WebSocket protocol versions 13 and 8.""" +import asyncio import collections import json import random @@ -8,9 +9,12 @@ import zlib from enum import IntEnum from struct import Struct +from typing import Any, Callable, List, Optional, Tuple, Union +from .base_protocol import BaseProtocol from .helpers import NO_EXTENSIONS from .log import ws_logger +from .streams import DataQueue __all__ = ('WS_CLOSED_MESSAGE', 'WS_CLOSING_MESSAGE', 'WS_KEY', @@ -79,7 +83,8 @@ class WSMessage(_WSMessageBase): - def json(self, *, loads=json.loads): + def json(self, *, # type: ignore + loads: Callable[[Any], Any]=json.loads) -> None: """Return parsed JSON data. .. versionadded:: 0.22 @@ -94,7 +99,7 @@ class WebSocketError(Exception): """WebSocket protocol parser error.""" - def __init__(self, code, message): + def __init__(self, code: int, message: str) -> None: self.code = code super().__init__(message) @@ -110,7 +115,7 @@ _XOR_TABLE = [bytes(a ^ b for a in range(256)) for b in range(256)] -def _websocket_mask_python(mask, data): +def _websocket_mask_python(mask: bytes, data: bytearray) -> None: """Websocket masking function. `mask` is a `bytes` object of length 4; `data` is a `bytearray` @@ -134,11 +139,11 @@ data[3::4] = data[3::4].translate(d) -if NO_EXTENSIONS: +if NO_EXTENSIONS: # pragma: no cover _websocket_mask = _websocket_mask_python else: try: - from ._websocket import _websocket_mask_cython + from ._websocket import _websocket_mask_cython # type: ignore _websocket_mask = _websocket_mask_cython except ImportError: # pragma: no cover _websocket_mask = _websocket_mask_python @@ -155,7 +160,7 @@ _WS_EXT_RE_SPLIT = re.compile(r'permessage-deflate([^,]+)?') -def ws_ext_parse(extstr, isserver=False): +def ws_ext_parse(extstr: str, isserver: bool=False) -> Tuple[int, bool]: if not extstr: return 0, False @@ -207,8 +212,8 @@ return compress, notakeover -def ws_ext_gen(compress=15, isserver=False, - server_notakeover=False): +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: @@ -236,31 +241,33 @@ class WebSocketReader: - def __init__(self, queue, compress=True): + 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 - self._partial = [] + self._exc = None # type: Optional[BaseException] + self._partial = bytearray() self._state = WSParserState.READ_HEADER - self._opcode = None + self._opcode = None # type: Optional[int] self._frame_fin = False - self._frame_opcode = None + self._frame_opcode = None # type: Optional[int] self._frame_payload = bytearray() self._tail = b'' self._has_mask = False - self._frame_mask = None + self._frame_mask = None # type: Optional[bytes] self._payload_length = 0 self._payload_length_flag = 0 - self._compressed = None - self._decompressobj = None + self._compressed = None # type: Optional[bool] + self._decompressobj = None # type: Any # zlib.decompressobj actually self._compress = compress - def feed_eof(self): + def feed_eof(self) -> None: self.queue.feed_eof() - def feed_data(self, data): + def feed_data(self, data: bytes) -> Tuple[bool, bytes]: if self._exc: return True, data @@ -271,7 +278,7 @@ self.queue.set_exception(exc) return True, b'' - def _feed_data(self, data): + 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) @@ -319,7 +326,13 @@ # got partial frame payload if opcode != WSMsgType.CONTINUATION: self._opcode = opcode - self._partial.append(payload) + 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 @@ -331,18 +344,33 @@ '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.append(payload) - - payload_merged = b''.join(self._partial) + 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( - payload_merged + _WS_DEFLATE_TRAILING) + 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() @@ -362,7 +390,9 @@ return False, b'' - def parse_frame(self, buf): + 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: @@ -426,9 +456,9 @@ WSCloseCode.PROTOCOL_ERROR, 'Received frame with non-zero reserved bits') - self._frame_fin = fin + self._frame_fin = bool(fin) self._frame_opcode = opcode - self._has_mask = has_mask + self._has_mask = bool(has_mask) self._payload_length_flag = length self._state = WSParserState.READ_PAYLOAD_LENGTH else: @@ -493,6 +523,7 @@ if self._payload_length == 0: if self._has_mask: + assert self._frame_mask is not None _websocket_mask(self._frame_mask, payload) frames.append(( @@ -513,9 +544,10 @@ class WebSocketWriter: - def __init__(self, protocol, transport, *, - use_mask=False, limit=DEFAULT_LIMIT, random=random.Random(), - compress=0, notakeover=False): + 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 @@ -525,9 +557,10 @@ self._closing = False self._limit = limit self._output_size = 0 - self._compressobj = None + self._compressobj = None # type: Any # actually compressobj - async def _send_frame(self, message, opcode, compress=None): + 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: ws_logger.warning('websocket connection is closing.') @@ -587,33 +620,35 @@ self._output_size = 0 await self.protocol._drain_helper() - async def pong(self, message=b''): + async def pong(self, message: bytes=b'') -> None: """Send pong message.""" if isinstance(message, str): message = message.encode('utf-8') - return await self._send_frame(message, WSMsgType.PONG) + await self._send_frame(message, WSMsgType.PONG) - async def ping(self, message=b''): + async def ping(self, message: bytes=b'') -> None: """Send ping message.""" if isinstance(message, str): message = message.encode('utf-8') - return await self._send_frame(message, WSMsgType.PING) + await self._send_frame(message, WSMsgType.PING) - async def send(self, message, binary=False, compress=None): + 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: - return await self._send_frame(message, WSMsgType.BINARY, compress) + await self._send_frame(message, WSMsgType.BINARY, compress) else: - return await self._send_frame(message, WSMsgType.TEXT, compress) + await self._send_frame(message, WSMsgType.TEXT, compress) - async def close(self, code=1000, message=b''): + 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: - return await self._send_frame( + await self._send_frame( PACK_CLOSE_CODE(code) + message, opcode=WSMsgType.CLOSE) finally: self._closing = True diff -Nru python-aiohttp-3.1.3/aiohttp/_http_writer.c python-aiohttp-3.5.1/aiohttp/_http_writer.c --- python-aiohttp-3.1.3/aiohttp/_http_writer.c 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/_http_writer.c 2018-12-24 20:59:11.000000000 +0000 @@ -0,0 +1,5616 @@ +/* Generated by Cython 0.29.2 */ + +/* BEGIN: Cython Metadata +{ + "distutils": { + "depends": [], + "name": "aiohttp._http_writer", + "sources": [ + "aiohttp/_http_writer.pyx" + ] + }, + "module_name": "aiohttp._http_writer" +} +END: Cython Metadata */ + +#define 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_2" +#define CYTHON_HEX_VERSION 0x001D02F0 +#define CYTHON_FUTURE_DIVISION 0 +#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" + #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 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_USE_DICT_VERSIONS +#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);\ + }\ + } +#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 +#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; // PyThread_create_key reports success always +} +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 // TSS (Thread Specific Storage) API +#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 + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ + 0 : _PyUnicode_Ready((PyObject *)(op))) + #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) + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) +#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 + #define PyObject_Unicode PyObject_Str +#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 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) ? PyMethod_New(func, self) : (Py_INCREF(func), 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_ERR(f_index, lineno, Ln_error) \ +{ \ + __pyx_filename = __pyx_f[f_index]; __pyx_lineno = lineno; __pyx_clineno = __LINE__; 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_DEFAULT 0 +#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":19 + * # ----------------- 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); + +/* 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, int 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); + +/* 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); + +/* 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); + +/* 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 + +/* 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); + +/* 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); + +/* 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); + +/* UnicodeAsUCS4.proto */ +static CYTHON_INLINE Py_UCS4 __Pyx_PyUnicode_AsPy_UCS4(PyObject*); + +/* ObjectAsUCS4.proto */ +#define __Pyx_PyObject_AsPy_UCS4(x)\ + (likely(PyUnicode_Check(x)) ? __Pyx_PyUnicode_AsPy_UCS4(x) : __Pyx__PyObject_AsPy_UCS4(x)) +static Py_UCS4 __Pyx__PyObject_AsPy_UCS4(PyObject*); + +/* 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.stdint' */ + +/* 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.exc' */ + +/* Module declarations from 'cpython.mem' */ + +/* Module declarations from 'cpython.bytes' */ + +/* 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*/ +#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 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_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 PyObject *__pyx_kp_s_Cannot_serialize_non_str_key_r; +static PyObject *__pyx_n_s_TypeError; +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_; +static PyObject *__pyx_codeobj__2; +/* Late includes */ + +/* "aiohttp/_http_writer.pyx":25 + * + * + * 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":26 + * + * 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":27 + * 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":28 + * writer.buf = &BUFFER[0] + * writer.size = BUF_SIZE + * writer.pos = 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_v_writer->pos = 0; + + /* "aiohttp/_http_writer.pyx":25 + * + * + * cdef inline void _init_writer(Writer* writer): # <<<<<<<<<<<<<< + * writer.buf = &BUFFER[0] + * writer.size = BUF_SIZE + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "aiohttp/_http_writer.pyx":31 + * + * + * 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":32 + * + * 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":33 + * 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":32 + * + * cdef inline void _release_writer(Writer* writer): + * if writer.buf != BUFFER: # <<<<<<<<<<<<<< + * PyMem_Free(writer.buf) + * + */ + } + + /* "aiohttp/_http_writer.pyx":31 + * + * + * cdef inline void _release_writer(Writer* writer): # <<<<<<<<<<<<<< + * if writer.buf != BUFFER: + * PyMem_Free(writer.buf) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "aiohttp/_http_writer.pyx":36 + * + * + * 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; + __Pyx_RefNannySetupContext("_write_byte", 0); + + /* "aiohttp/_http_writer.pyx":40 + * 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":42 + * 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":43 + * # 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":44 + * 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":45 + * 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":46 + * 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, 46, __pyx_L1_error) + + /* "aiohttp/_http_writer.pyx":47 + * if buf == NULL: + * PyErr_NoMemory() + * return -1 # <<<<<<<<<<<<<< + * memcpy(buf, writer.buf, writer.size) + * else: + */ + __pyx_r = -1; + goto __pyx_L0; + + /* "aiohttp/_http_writer.pyx":45 + * if writer.buf == BUFFER: + * buf = PyMem_Malloc(size) + * if buf == NULL: # <<<<<<<<<<<<<< + * PyErr_NoMemory() + * return -1 + */ + } + + /* "aiohttp/_http_writer.pyx":48 + * 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":43 + * # reallocate + * size = writer.size + BUF_SIZE + * if writer.buf == BUFFER: # <<<<<<<<<<<<<< + * buf = PyMem_Malloc(size) + * if buf == NULL: + */ + goto __pyx_L4; + } + + /* "aiohttp/_http_writer.pyx":50 + * 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":51 + * 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":52 + * 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, 52, __pyx_L1_error) + + /* "aiohttp/_http_writer.pyx":53 + * if buf == NULL: + * PyErr_NoMemory() + * return -1 # <<<<<<<<<<<<<< + * writer.buf = buf + * writer.size = size + */ + __pyx_r = -1; + goto __pyx_L0; + + /* "aiohttp/_http_writer.pyx":51 + * else: + * buf = PyMem_Realloc(writer.buf, size) + * if buf == NULL: # <<<<<<<<<<<<<< + * PyErr_NoMemory() + * return -1 + */ + } + } + __pyx_L4:; + + /* "aiohttp/_http_writer.pyx":54 + * 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":55 + * 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":40 + * cdef Py_ssize_t size + * + * if writer.pos == writer.size: # <<<<<<<<<<<<<< + * # reallocate + * size = writer.size + BUF_SIZE + */ + } + + /* "aiohttp/_http_writer.pyx":56 + * 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":57 + * 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":58 + * writer.buf[writer.pos] = ch + * writer.pos += 1 + * return 0 # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = 0; + goto __pyx_L0; + + /* "aiohttp/_http_writer.pyx":36 + * + * + * 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":61 + * + * + * 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":62 + * + * 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":64 + * 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":65 + * + * 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":64 + * cdef uint64_t utf = symbol + * + * if utf < 0x80: # <<<<<<<<<<<<<< + * return _write_byte(writer, utf) + * elif utf < 0x800: + */ + } + + /* "aiohttp/_http_writer.pyx":66 + * 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":67 + * 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":68 + * 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":67 + * 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":69 + * 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":66 + * 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":70 + * 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":72 + * 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":70 + * return -1 + * return _write_byte(writer, (0x80 | (utf & 0x3f))) + * elif 0xD800 <= utf <= 0xDFFF: # <<<<<<<<<<<<<< + * # surogate pair, ignored + * return 0 + */ + } + + /* "aiohttp/_http_writer.pyx":73 + * # 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":74 + * 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":75 + * 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":74 + * 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":76 + * 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":77 + * 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":76 + * 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":78 + * 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":73 + * # surogate pair, ignored + * return 0 + * elif utf < 0x10000: # <<<<<<<<<<<<<< + * if _write_byte(writer, (0xe0 | (utf >> 12))) < 0: + * return -1 + */ + } + + /* "aiohttp/_http_writer.pyx":79 + * 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":81 + * 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":79 + * return -1 + * return _write_byte(writer, (0x80 | (utf & 0x3f))) + * elif utf > 0x10FFFF: # <<<<<<<<<<<<<< + * # symbol is too large + * return 0 + */ + } + + /* "aiohttp/_http_writer.pyx":83 + * 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":84 + * 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":83 + * return 0 + * else: + * if _write_byte(writer, (0xf0 | (utf >> 18))) < 0: # <<<<<<<<<<<<<< + * return -1 + * if _write_byte(writer, + */ + } + + /* "aiohttp/_http_writer.pyx":86 + * 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":85 + * 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":87 + * 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":85 + * 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":89 + * 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":88 + * (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":90 + * 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":88 + * (0x80 | ((utf >> 12) & 0x3f))) < 0: + * return -1 + * if _write_byte(writer, # <<<<<<<<<<<<<< + * (0x80 | ((utf >> 6) & 0x3f))) < 0: + * return -1 + */ + } + + /* "aiohttp/_http_writer.pyx":91 + * (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":61 + * + * + * 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":94 + * + * + * 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; + PyObject *(*__pyx_t_2)(PyObject *); + PyObject *__pyx_t_3 = NULL; + Py_UCS4 __pyx_t_4; + int __pyx_t_5; + __Pyx_RefNannySetupContext("_write_str", 0); + + /* "aiohttp/_http_writer.pyx":96 + * 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 + */ + __pyx_t_1 = PyObject_GetIter(__pyx_v_s); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 96, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = Py_TYPE(__pyx_t_1)->tp_iternext; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 96, __pyx_L1_error) + for (;;) { + { + __pyx_t_3 = __pyx_t_2(__pyx_t_1); + if (unlikely(!__pyx_t_3)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(0, 96, __pyx_L1_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_3); + } + __pyx_t_4 = __Pyx_PyObject_AsPy_UCS4(__pyx_t_3); if (unlikely((__pyx_t_4 == (Py_UCS4)-1) && PyErr_Occurred())) __PYX_ERR(0, 96, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_ch = __pyx_t_4; + + /* "aiohttp/_http_writer.pyx":97 + * cdef Py_UCS4 ch + * for ch in s: + * if _write_utf8(writer, ch) < 0: # <<<<<<<<<<<<<< + * return -1 + * + */ + __pyx_t_5 = ((__pyx_f_7aiohttp_12_http_writer__write_utf8(__pyx_v_writer, __pyx_v_ch) < 0) != 0); + if (__pyx_t_5) { + + /* "aiohttp/_http_writer.pyx":98 + * 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":97 + * cdef Py_UCS4 ch + * for ch in s: + * if _write_utf8(writer, ch) < 0: # <<<<<<<<<<<<<< + * return -1 + * + */ + } + + /* "aiohttp/_http_writer.pyx":96 + * 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 + */ + } + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "aiohttp/_http_writer.pyx":94 + * + * + * 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_XDECREF(__pyx_t_3); + __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":103 + * # --------------- _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; + __Pyx_RefNannySetupContext("to_str", 0); + + /* "aiohttp/_http_writer.pyx":104 + * + * 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":105 + * 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 == (&PyString_Type)); + __pyx_t_2 = (__pyx_t_1 != 0); + if (__pyx_t_2) { + + /* "aiohttp/_http_writer.pyx":106 + * 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":105 + * cdef str to_str(object s): + * typ = type(s) + * if typ is str: # <<<<<<<<<<<<<< + * return s + * elif typ is _istr: + */ + } + + /* "aiohttp/_http_writer.pyx":107 + * 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":108 + * 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, 108, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (!(likely(PyString_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "str", Py_TYPE(__pyx_t_3)->tp_name), 0))) __PYX_ERR(0, 108, __pyx_L1_error) + __pyx_r = ((PyObject*)__pyx_t_3); + __pyx_t_3 = 0; + goto __pyx_L0; + + /* "aiohttp/_http_writer.pyx":107 + * if typ is str: + * return s + * elif typ is _istr: # <<<<<<<<<<<<<< + * return PyObject_Str(s) + * elif not isinstance(s, str): + */ + } + + /* "aiohttp/_http_writer.pyx":109 + * 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 = PyString_Check(__pyx_v_s); + __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); + if (unlikely(__pyx_t_2)) { + + /* "aiohttp/_http_writer.pyx":110 + * 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_s_Cannot_serialize_non_str_key_r, __pyx_n_s_format); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 110, __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, 110, __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, 110, __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, 110, __pyx_L1_error) + + /* "aiohttp/_http_writer.pyx":109 + * 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":112 + * 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 *)(&PyString_Type)), __pyx_v_s); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 112, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + if (!(likely(PyString_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "str", Py_TYPE(__pyx_t_4)->tp_name), 0))) __PYX_ERR(0, 112, __pyx_L1_error) + __pyx_r = ((PyObject*)__pyx_t_4); + __pyx_t_4 = 0; + goto __pyx_L0; + } + + /* "aiohttp/_http_writer.pyx":103 + * # --------------- _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":115 + * + * + * 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; + 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, 115, __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, 115, __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, 115, __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), (&PyString_Type), 1, "status_line", 1))) __PYX_ERR(0, 115, __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 + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + Py_ssize_t __pyx_t_5; + PyObject *(*__pyx_t_6)(PyObject *); + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *(*__pyx_t_9)(PyObject *); + int __pyx_t_10; + int __pyx_t_11; + char const *__pyx_t_12; + 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; + __Pyx_RefNannySetupContext("_serialize_headers", 0); + + /* "aiohttp/_http_writer.pyx":121 + * cdef bytes ret + * + * _init_writer(&writer) # <<<<<<<<<<<<<< + * + * try: + */ + __pyx_f_7aiohttp_12_http_writer__init_writer((&__pyx_v_writer)); + + /* "aiohttp/_http_writer.pyx":123 + * _init_writer(&writer) + * + * try: # <<<<<<<<<<<<<< + * if _write_str(&writer, status_line) < 0: + * raise + */ + /*try:*/ { + + /* "aiohttp/_http_writer.pyx":124 + * + * try: + * if _write_str(&writer, status_line) < 0: # <<<<<<<<<<<<<< + * raise + * if _write_byte(&writer, '\r') < 0: + */ + __pyx_t_1 = ((__pyx_f_7aiohttp_12_http_writer__write_str((&__pyx_v_writer), __pyx_v_status_line) < 0) != 0); + if (unlikely(__pyx_t_1)) { + + /* "aiohttp/_http_writer.pyx":125 + * try: + * if _write_str(&writer, status_line) < 0: + * raise # <<<<<<<<<<<<<< + * if _write_byte(&writer, '\r') < 0: + * raise + */ + __Pyx_ReraiseException(); __PYX_ERR(0, 125, __pyx_L4_error) + + /* "aiohttp/_http_writer.pyx":124 + * + * try: + * if _write_str(&writer, status_line) < 0: # <<<<<<<<<<<<<< + * raise + * if _write_byte(&writer, '\r') < 0: + */ + } + + /* "aiohttp/_http_writer.pyx":126 + * if _write_str(&writer, status_line) < 0: + * raise + * if _write_byte(&writer, '\r') < 0: # <<<<<<<<<<<<<< + * raise + * if _write_byte(&writer, '\n') < 0: + */ + __pyx_t_1 = ((__pyx_f_7aiohttp_12_http_writer__write_byte((&__pyx_v_writer), '\r') < 0) != 0); + if (unlikely(__pyx_t_1)) { + + /* "aiohttp/_http_writer.pyx":127 + * raise + * if _write_byte(&writer, '\r') < 0: + * raise # <<<<<<<<<<<<<< + * if _write_byte(&writer, '\n') < 0: + * raise + */ + __Pyx_ReraiseException(); __PYX_ERR(0, 127, __pyx_L4_error) + + /* "aiohttp/_http_writer.pyx":126 + * if _write_str(&writer, status_line) < 0: + * raise + * if _write_byte(&writer, '\r') < 0: # <<<<<<<<<<<<<< + * raise + * if _write_byte(&writer, '\n') < 0: + */ + } + + /* "aiohttp/_http_writer.pyx":128 + * if _write_byte(&writer, '\r') < 0: + * raise + * if _write_byte(&writer, '\n') < 0: # <<<<<<<<<<<<<< + * raise + * + */ + __pyx_t_1 = ((__pyx_f_7aiohttp_12_http_writer__write_byte((&__pyx_v_writer), '\n') < 0) != 0); + if (unlikely(__pyx_t_1)) { + + /* "aiohttp/_http_writer.pyx":129 + * raise + * if _write_byte(&writer, '\n') < 0: + * raise # <<<<<<<<<<<<<< + * + * for key, val in headers.items(): + */ + __Pyx_ReraiseException(); __PYX_ERR(0, 129, __pyx_L4_error) + + /* "aiohttp/_http_writer.pyx":128 + * if _write_byte(&writer, '\r') < 0: + * raise + * if _write_byte(&writer, '\n') < 0: # <<<<<<<<<<<<<< + * raise + * + */ + } + + /* "aiohttp/_http_writer.pyx":131 + * raise + * + * for key, val in headers.items(): # <<<<<<<<<<<<<< + * if _write_str(&writer, to_str(key)) < 0: + * raise + */ + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_headers, __pyx_n_s_items); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 131, __pyx_L4_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_2 = (__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_2)) __PYX_ERR(0, 131, __pyx_L4_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + if (likely(PyList_CheckExact(__pyx_t_2)) || PyTuple_CheckExact(__pyx_t_2)) { + __pyx_t_3 = __pyx_t_2; __Pyx_INCREF(__pyx_t_3); __pyx_t_5 = 0; + __pyx_t_6 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 131, __pyx_L4_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_6 = Py_TYPE(__pyx_t_3)->tp_iternext; if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 131, __pyx_L4_error) + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + for (;;) { + if (likely(!__pyx_t_6)) { + if (likely(PyList_CheckExact(__pyx_t_3))) { + if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_2 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_5); __Pyx_INCREF(__pyx_t_2); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(0, 131, __pyx_L4_error) + #else + __pyx_t_2 = PySequence_ITEM(__pyx_t_3, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 131, __pyx_L4_error) + __Pyx_GOTREF(__pyx_t_2); + #endif + } else { + if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_3)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_2 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_5); __Pyx_INCREF(__pyx_t_2); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(0, 131, __pyx_L4_error) + #else + __pyx_t_2 = PySequence_ITEM(__pyx_t_3, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 131, __pyx_L4_error) + __Pyx_GOTREF(__pyx_t_2); + #endif + } + } else { + __pyx_t_2 = __pyx_t_6(__pyx_t_3); + if (unlikely(!__pyx_t_2)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(0, 131, __pyx_L4_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_2); + } + if ((likely(PyTuple_CheckExact(__pyx_t_2))) || (PyList_CheckExact(__pyx_t_2))) { + PyObject* sequence = __pyx_t_2; + 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, 131, __pyx_L4_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_7 = PyTuple_GET_ITEM(sequence, 1); + } else { + __pyx_t_4 = PyList_GET_ITEM(sequence, 0); + __pyx_t_7 = PyList_GET_ITEM(sequence, 1); + } + __Pyx_INCREF(__pyx_t_4); + __Pyx_INCREF(__pyx_t_7); + #else + __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 131, __pyx_L4_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_7 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 131, __pyx_L4_error) + __Pyx_GOTREF(__pyx_t_7); + #endif + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + } else { + Py_ssize_t index = -1; + __pyx_t_8 = PyObject_GetIter(__pyx_t_2); if (unlikely(!__pyx_t_8)) __PYX_ERR(0, 131, __pyx_L4_error) + __Pyx_GOTREF(__pyx_t_8); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_9 = Py_TYPE(__pyx_t_8)->tp_iternext; + index = 0; __pyx_t_4 = __pyx_t_9(__pyx_t_8); if (unlikely(!__pyx_t_4)) goto __pyx_L11_unpacking_failed; + __Pyx_GOTREF(__pyx_t_4); + index = 1; __pyx_t_7 = __pyx_t_9(__pyx_t_8); if (unlikely(!__pyx_t_7)) goto __pyx_L11_unpacking_failed; + __Pyx_GOTREF(__pyx_t_7); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_9(__pyx_t_8), 2) < 0) __PYX_ERR(0, 131, __pyx_L4_error) + __pyx_t_9 = NULL; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + goto __pyx_L12_unpacking_done; + __pyx_L11_unpacking_failed:; + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; + __pyx_t_9 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 131, __pyx_L4_error) + __pyx_L12_unpacking_done:; + } + __Pyx_XDECREF_SET(__pyx_v_key, __pyx_t_4); + __pyx_t_4 = 0; + __Pyx_XDECREF_SET(__pyx_v_val, __pyx_t_7); + __pyx_t_7 = 0; + + /* "aiohttp/_http_writer.pyx":132 + * + * for key, val in headers.items(): + * if _write_str(&writer, to_str(key)) < 0: # <<<<<<<<<<<<<< + * raise + * if _write_byte(&writer, ':') < 0: + */ + __pyx_t_2 = __pyx_f_7aiohttp_12_http_writer_to_str(__pyx_v_key); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 132, __pyx_L4_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = ((__pyx_f_7aiohttp_12_http_writer__write_str((&__pyx_v_writer), ((PyObject*)__pyx_t_2)) < 0) != 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(__pyx_t_1)) { + + /* "aiohttp/_http_writer.pyx":133 + * for key, val in headers.items(): + * if _write_str(&writer, to_str(key)) < 0: + * raise # <<<<<<<<<<<<<< + * if _write_byte(&writer, ':') < 0: + * raise + */ + __Pyx_ReraiseException(); __PYX_ERR(0, 133, __pyx_L4_error) + + /* "aiohttp/_http_writer.pyx":132 + * + * for key, val in headers.items(): + * if _write_str(&writer, to_str(key)) < 0: # <<<<<<<<<<<<<< + * raise + * if _write_byte(&writer, ':') < 0: + */ + } + + /* "aiohttp/_http_writer.pyx":134 + * if _write_str(&writer, to_str(key)) < 0: + * raise + * if _write_byte(&writer, ':') < 0: # <<<<<<<<<<<<<< + * raise + * if _write_byte(&writer, ' ') < 0: + */ + __pyx_t_1 = ((__pyx_f_7aiohttp_12_http_writer__write_byte((&__pyx_v_writer), ':') < 0) != 0); + if (unlikely(__pyx_t_1)) { + + /* "aiohttp/_http_writer.pyx":135 + * raise + * if _write_byte(&writer, ':') < 0: + * raise # <<<<<<<<<<<<<< + * if _write_byte(&writer, ' ') < 0: + * raise + */ + __Pyx_ReraiseException(); __PYX_ERR(0, 135, __pyx_L4_error) + + /* "aiohttp/_http_writer.pyx":134 + * if _write_str(&writer, to_str(key)) < 0: + * raise + * if _write_byte(&writer, ':') < 0: # <<<<<<<<<<<<<< + * raise + * if _write_byte(&writer, ' ') < 0: + */ + } + + /* "aiohttp/_http_writer.pyx":136 + * if _write_byte(&writer, ':') < 0: + * raise + * if _write_byte(&writer, ' ') < 0: # <<<<<<<<<<<<<< + * raise + * if _write_str(&writer, to_str(val)) < 0: + */ + __pyx_t_1 = ((__pyx_f_7aiohttp_12_http_writer__write_byte((&__pyx_v_writer), ' ') < 0) != 0); + if (unlikely(__pyx_t_1)) { + + /* "aiohttp/_http_writer.pyx":137 + * raise + * if _write_byte(&writer, ' ') < 0: + * raise # <<<<<<<<<<<<<< + * if _write_str(&writer, to_str(val)) < 0: + * raise + */ + __Pyx_ReraiseException(); __PYX_ERR(0, 137, __pyx_L4_error) + + /* "aiohttp/_http_writer.pyx":136 + * if _write_byte(&writer, ':') < 0: + * raise + * if _write_byte(&writer, ' ') < 0: # <<<<<<<<<<<<<< + * raise + * if _write_str(&writer, to_str(val)) < 0: + */ + } + + /* "aiohttp/_http_writer.pyx":138 + * if _write_byte(&writer, ' ') < 0: + * raise + * if _write_str(&writer, to_str(val)) < 0: # <<<<<<<<<<<<<< + * raise + * if _write_byte(&writer, '\r') < 0: + */ + __pyx_t_2 = __pyx_f_7aiohttp_12_http_writer_to_str(__pyx_v_val); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 138, __pyx_L4_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_1 = ((__pyx_f_7aiohttp_12_http_writer__write_str((&__pyx_v_writer), ((PyObject*)__pyx_t_2)) < 0) != 0); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + if (unlikely(__pyx_t_1)) { + + /* "aiohttp/_http_writer.pyx":139 + * raise + * if _write_str(&writer, to_str(val)) < 0: + * raise # <<<<<<<<<<<<<< + * if _write_byte(&writer, '\r') < 0: + * raise + */ + __Pyx_ReraiseException(); __PYX_ERR(0, 139, __pyx_L4_error) + + /* "aiohttp/_http_writer.pyx":138 + * if _write_byte(&writer, ' ') < 0: + * raise + * if _write_str(&writer, to_str(val)) < 0: # <<<<<<<<<<<<<< + * raise + * if _write_byte(&writer, '\r') < 0: + */ + } + + /* "aiohttp/_http_writer.pyx":140 + * if _write_str(&writer, to_str(val)) < 0: + * raise + * if _write_byte(&writer, '\r') < 0: # <<<<<<<<<<<<<< + * raise + * if _write_byte(&writer, '\n') < 0: + */ + __pyx_t_1 = ((__pyx_f_7aiohttp_12_http_writer__write_byte((&__pyx_v_writer), '\r') < 0) != 0); + if (unlikely(__pyx_t_1)) { + + /* "aiohttp/_http_writer.pyx":141 + * raise + * if _write_byte(&writer, '\r') < 0: + * raise # <<<<<<<<<<<<<< + * if _write_byte(&writer, '\n') < 0: + * raise + */ + __Pyx_ReraiseException(); __PYX_ERR(0, 141, __pyx_L4_error) + + /* "aiohttp/_http_writer.pyx":140 + * if _write_str(&writer, to_str(val)) < 0: + * raise + * if _write_byte(&writer, '\r') < 0: # <<<<<<<<<<<<<< + * raise + * if _write_byte(&writer, '\n') < 0: + */ + } + + /* "aiohttp/_http_writer.pyx":142 + * if _write_byte(&writer, '\r') < 0: + * raise + * if _write_byte(&writer, '\n') < 0: # <<<<<<<<<<<<<< + * raise + * + */ + __pyx_t_1 = ((__pyx_f_7aiohttp_12_http_writer__write_byte((&__pyx_v_writer), '\n') < 0) != 0); + if (unlikely(__pyx_t_1)) { + + /* "aiohttp/_http_writer.pyx":143 + * raise + * if _write_byte(&writer, '\n') < 0: + * raise # <<<<<<<<<<<<<< + * + * if _write_byte(&writer, '\r') < 0: + */ + __Pyx_ReraiseException(); __PYX_ERR(0, 143, __pyx_L4_error) + + /* "aiohttp/_http_writer.pyx":142 + * if _write_byte(&writer, '\r') < 0: + * raise + * if _write_byte(&writer, '\n') < 0: # <<<<<<<<<<<<<< + * raise + * + */ + } + + /* "aiohttp/_http_writer.pyx":131 + * raise + * + * for key, val in headers.items(): # <<<<<<<<<<<<<< + * if _write_str(&writer, to_str(key)) < 0: + * raise + */ + } + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "aiohttp/_http_writer.pyx":145 + * raise + * + * if _write_byte(&writer, '\r') < 0: # <<<<<<<<<<<<<< + * raise + * if _write_byte(&writer, '\n') < 0: + */ + __pyx_t_1 = ((__pyx_f_7aiohttp_12_http_writer__write_byte((&__pyx_v_writer), '\r') < 0) != 0); + if (unlikely(__pyx_t_1)) { + + /* "aiohttp/_http_writer.pyx":146 + * + * if _write_byte(&writer, '\r') < 0: + * raise # <<<<<<<<<<<<<< + * if _write_byte(&writer, '\n') < 0: + * raise + */ + __Pyx_ReraiseException(); __PYX_ERR(0, 146, __pyx_L4_error) + + /* "aiohttp/_http_writer.pyx":145 + * raise + * + * if _write_byte(&writer, '\r') < 0: # <<<<<<<<<<<<<< + * raise + * if _write_byte(&writer, '\n') < 0: + */ + } + + /* "aiohttp/_http_writer.pyx":147 + * if _write_byte(&writer, '\r') < 0: + * raise + * if _write_byte(&writer, '\n') < 0: # <<<<<<<<<<<<<< + * raise + * + */ + __pyx_t_1 = ((__pyx_f_7aiohttp_12_http_writer__write_byte((&__pyx_v_writer), '\n') < 0) != 0); + if (unlikely(__pyx_t_1)) { + + /* "aiohttp/_http_writer.pyx":148 + * raise + * if _write_byte(&writer, '\n') < 0: + * raise # <<<<<<<<<<<<<< + * + * return PyBytes_FromStringAndSize(writer.buf, writer.pos) + */ + __Pyx_ReraiseException(); __PYX_ERR(0, 148, __pyx_L4_error) + + /* "aiohttp/_http_writer.pyx":147 + * if _write_byte(&writer, '\r') < 0: + * raise + * if _write_byte(&writer, '\n') < 0: # <<<<<<<<<<<<<< + * raise + * + */ + } + + /* "aiohttp/_http_writer.pyx":150 + * raise + * + * return PyBytes_FromStringAndSize(writer.buf, writer.pos) # <<<<<<<<<<<<<< + * finally: + * _release_writer(&writer) + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_3 = PyBytes_FromStringAndSize(__pyx_v_writer.buf, __pyx_v_writer.pos); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 150, __pyx_L4_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; + goto __pyx_L3_return; + } + + /* "aiohttp/_http_writer.pyx":152 + * return PyBytes_FromStringAndSize(writer.buf, writer.pos) + * finally: + * _release_writer(&writer) # <<<<<<<<<<<<<< + */ + /*finally:*/ { + __pyx_L4_error:; + /*exception exit:*/{ + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __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_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; + if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_16, &__pyx_t_17, &__pyx_t_18); + if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_13, &__pyx_t_14, &__pyx_t_15) < 0)) __Pyx_ErrFetch(&__pyx_t_13, &__pyx_t_14, &__pyx_t_15); + __Pyx_XGOTREF(__pyx_t_13); + __Pyx_XGOTREF(__pyx_t_14); + __Pyx_XGOTREF(__pyx_t_15); + __Pyx_XGOTREF(__pyx_t_16); + __Pyx_XGOTREF(__pyx_t_17); + __Pyx_XGOTREF(__pyx_t_18); + __pyx_t_10 = __pyx_lineno; __pyx_t_11 = __pyx_clineno; __pyx_t_12 = __pyx_filename; + { + __pyx_f_7aiohttp_12_http_writer__release_writer((&__pyx_v_writer)); + } + if (PY_MAJOR_VERSION >= 3) { + __Pyx_XGIVEREF(__pyx_t_16); + __Pyx_XGIVEREF(__pyx_t_17); + __Pyx_XGIVEREF(__pyx_t_18); + __Pyx_ExceptionReset(__pyx_t_16, __pyx_t_17, __pyx_t_18); + } + __Pyx_XGIVEREF(__pyx_t_13); + __Pyx_XGIVEREF(__pyx_t_14); + __Pyx_XGIVEREF(__pyx_t_15); + __Pyx_ErrRestore(__pyx_t_13, __pyx_t_14, __pyx_t_15); + __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_lineno = __pyx_t_10; __pyx_clineno = __pyx_t_11; __pyx_filename = __pyx_t_12; + goto __pyx_L1_error; + } + __pyx_L3_return: { + __pyx_t_18 = __pyx_r; + __pyx_r = 0; + __pyx_f_7aiohttp_12_http_writer__release_writer((&__pyx_v_writer)); + __pyx_r = __pyx_t_18; + __pyx_t_18 = 0; + goto __pyx_L0; + } + } + + /* "aiohttp/_http_writer.pyx":115 + * + * + * def _serialize_headers(str status_line, headers): # <<<<<<<<<<<<<< + * cdef Writer writer + * cdef object key + */ + + /* 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_7); + __Pyx_XDECREF(__pyx_t_8); + __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_s_Cannot_serialize_non_str_key_r, __pyx_k_Cannot_serialize_non_str_key_r, sizeof(__pyx_k_Cannot_serialize_non_str_key_r), 0, 0, 1, 0}, + {&__pyx_n_s_TypeError, __pyx_k_TypeError, sizeof(__pyx_k_TypeError), 0, 0, 1, 1}, + {&__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, 110, __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":115 + * + * + * def _serialize_headers(str status_line, headers): # <<<<<<<<<<<<<< + * cdef Writer writer + * cdef object key + */ + __pyx_tuple_ = 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_)) __PYX_ERR(0, 115, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple_); + __Pyx_GIVEREF(__pyx_tuple_); + __pyx_codeobj__2 = (PyObject*)__Pyx_PyCode_New(2, 0, 6, 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__http_writer_pyx, __pyx_n_s_serialize_headers, 115, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__2)) __PYX_ERR(0, 115, __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; + __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; +} + + +#if PY_MAJOR_VERSION < 3 +#ifdef CYTHON_NO_PYINIT_EXPORT +#define __Pyx_PyMODINIT_FUNC void +#else +#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC +#endif +#else +#ifdef CYTHON_NO_PYINIT_EXPORT +#define __Pyx_PyMODINIT_FUNC PyObject * +#else +#define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC +#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; + __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(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS + #ifdef WITH_THREAD /* Python build with threading support? */ + PyEval_InitThreads(); + #endif + #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) + __pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) + #if CYTHON_COMPILING_IN_PYPY + Py_INCREF(__pyx_b); + #endif + 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)) goto __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":9 + * from cpython.object cimport PyObject_Str + * + * from multidict import istr # <<<<<<<<<<<<<< + * + * DEF BUF_SIZE = 16 * 1024 # 16KiB + */ + __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 9, __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, -1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 9, __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, 9, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_istr, __pyx_t_1) < 0) __PYX_ERR(0, 9, __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":14 + * 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, 14, __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":115 + * + * + * 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, 115, __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, 115, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + + /* "aiohttp/_http_writer.pyx":1 + * from libc.stdint cimport uint8_t, uint64_t # <<<<<<<<<<<<<< + * from libc.string cimport memcpy + * from cpython.exc cimport PyErr_NoMemory + */ + __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 +} + +/* 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, int 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, nargs, + k, (int)nk, + d, (int)nd, kwdefs, closure); +#else + result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL, + args, 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 = func->ob_type->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 (PyCFunction_GET_FLAGS(func) & METH_FASTCALL) { + 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_CheckExact(key)) || 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 + (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(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 + (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(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; +} + +/* 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); + } +} + +/* 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 + +/* 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; +} + +/* 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 (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; +} + +/* 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(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); +} + +/* UnicodeAsUCS4 */ +static CYTHON_INLINE Py_UCS4 __Pyx_PyUnicode_AsPy_UCS4(PyObject* x) { + Py_ssize_t length; + #if CYTHON_PEP393_ENABLED + length = PyUnicode_GET_LENGTH(x); + if (likely(length == 1)) { + return PyUnicode_READ_CHAR(x, 0); + } + #else + length = PyUnicode_GET_SIZE(x); + if (likely(length == 1)) { + return PyUnicode_AS_UNICODE(x)[0]; + } + #if Py_UNICODE_SIZE == 2 + else if (PyUnicode_GET_SIZE(x) == 2) { + Py_UCS4 high_val = PyUnicode_AS_UNICODE(x)[0]; + if (high_val >= 0xD800 && high_val <= 0xDBFF) { + Py_UCS4 low_val = PyUnicode_AS_UNICODE(x)[1]; + if (low_val >= 0xDC00 && low_val <= 0xDFFF) { + return 0x10000 + (((high_val & ((1<<10)-1)) << 10) | (low_val & ((1<<10)-1))); + } + } + } + #endif + #endif + PyErr_Format(PyExc_ValueError, + "only single character unicode strings can be converted to Py_UCS4, " + "got length %" CYTHON_FORMAT_SSIZE_T "d", length); + return (Py_UCS4)-1; +} + +/* ObjectAsUCS4 */ +static Py_UCS4 __Pyx__PyObject_AsPy_UCS4_raise_error(long ival) { + if (ival < 0) { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_OverflowError, + "cannot convert negative value to Py_UCS4"); + } else { + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to Py_UCS4"); + } + return (Py_UCS4)-1; +} +static Py_UCS4 __Pyx__PyObject_AsPy_UCS4(PyObject* x) { + long ival; + ival = __Pyx_PyInt_As_long(x); + if (unlikely(!__Pyx_is_valid_index(ival, 1114111 + 1))) { + return __Pyx__PyObject_AsPy_UCS4_raise_error(ival); + } + return (Py_UCS4)ival; +} + +/* CIntToPy */ +static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { + const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0; + 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) { + const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0; + 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) { + const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 0; + 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 -Nru python-aiohttp-3.1.3/aiohttp/http_writer.py python-aiohttp-3.5.1/aiohttp/http_writer.py --- python-aiohttp-3.1.3/aiohttp/http_writer.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/http_writer.py 2018-12-24 20:58:54.000000000 +0000 @@ -3,8 +3,13 @@ import asyncio import collections import zlib +from typing import Any, Awaitable, Callable, Optional, Union # noqa + +from multidict import CIMultiDict # noqa from .abc import AbstractStreamWriter +from .base_protocol import BaseProtocol +from .helpers import NO_EXTENSIONS __all__ = ('StreamWriter', 'HttpVersion', 'HttpVersion10', 'HttpVersion11') @@ -14,11 +19,17 @@ HttpVersion11 = HttpVersion(1, 1) +_T_OnChunkSent = Optional[Callable[[bytes], Awaitable[None]]] + + class StreamWriter(AbstractStreamWriter): - def __init__(self, protocol, transport, loop, on_chunk_sent=None): + def __init__(self, + protocol: BaseProtocol, + loop: asyncio.AbstractEventLoop, + on_chunk_sent: _T_OnChunkSent = None) -> None: self._protocol = protocol - self._transport = transport + self._transport = protocol.transport self.loop = loop self.length = None @@ -27,37 +38,38 @@ self.output_size = 0 self._eof = False - self._compress = None + self._compress = None # type: Any self._drain_waiter = None - self._on_chunk_sent = on_chunk_sent + self._on_chunk_sent = on_chunk_sent # type: _T_OnChunkSent @property - def transport(self): + def transport(self) -> Optional[asyncio.Transport]: return self._transport @property - def protocol(self): + def protocol(self) -> BaseProtocol: return self._protocol - def enable_chunking(self): + def enable_chunking(self) -> None: self.chunked = True - def enable_compression(self, encoding='deflate'): + def enable_compression(self, encoding: str='deflate') -> None: zlib_mode = (16 + zlib.MAX_WBITS if encoding == 'gzip' else -zlib.MAX_WBITS) self._compress = zlib.compressobj(wbits=zlib_mode) - def _write(self, chunk): + 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 asyncio.CancelledError('Cannot write to closing transport') + raise ConnectionResetError('Cannot write to closing transport') self._transport.write(chunk) - async def write(self, chunk, *, drain=True, LIMIT=0x10000): + 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. @@ -84,8 +96,8 @@ if chunk: if self.chunked: - chunk_len = ('%x\r\n' % len(chunk)).encode('ascii') - chunk = chunk_len + chunk + b'\r\n' + chunk_len_pre = ('%x\r\n' % len(chunk)).encode('ascii') + chunk = chunk_len_pre + chunk + b'\r\n' self._write(chunk) @@ -93,15 +105,14 @@ self.buffer_size = 0 await self.drain() - async def write_headers(self, status_line, headers, SEP=': ', END='\r\n'): + async def write_headers(self, status_line: str, + headers: 'CIMultiDict[str]') -> None: """Write request/response status and headers.""" # status + headers - headers = status_line + ''.join( - [k + SEP + v + END for k, v in headers.items()]) - headers = headers.encode('utf-8') + b'\r\n' - self._write(headers) + buf = _serialize_headers(status_line, headers) + self._write(buf) - async def write_eof(self, chunk=b''): + async def write_eof(self, chunk: bytes=b'') -> None: if self._eof: return @@ -132,7 +143,7 @@ self._eof = True self._transport = None - async def drain(self): + async def drain(self) -> None: """Flush the write buffer. The intended use is to write @@ -142,3 +153,21 @@ """ if self._protocol.transport is not None: await self._protocol._drain_helper() + + +def _py_serialize_headers(status_line: str, + headers: 'CIMultiDict[str]') -> bytes: + line = status_line + '\r\n' + ''.join( + [k + ': ' + v + '\r\n' for k, v in headers.items()]) + return line.encode('utf-8') + b'\r\n' + + +_serialize_headers = _py_serialize_headers + +try: + import aiohttp._http_writer as _http_writer # type: ignore + _c_serialize_headers = _http_writer._serialize_headers + if not NO_EXTENSIONS: + _serialize_headers = _c_serialize_headers +except ImportError: + pass diff -Nru python-aiohttp-3.1.3/aiohttp/_http_writer.pyx python-aiohttp-3.5.1/aiohttp/_http_writer.pyx --- python-aiohttp-3.1.3/aiohttp/_http_writer.pyx 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/_http_writer.pyx 2018-12-24 20:58:54.000000000 +0000 @@ -0,0 +1,152 @@ +from libc.stdint cimport uint8_t, uint64_t +from libc.string cimport memcpy +from cpython.exc cimport PyErr_NoMemory +from cpython.mem cimport PyMem_Malloc, PyMem_Realloc, PyMem_Free + +from cpython.bytes cimport PyBytes_FromStringAndSize +from cpython.object cimport PyObject_Str + +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) + + +def _serialize_headers(str status_line, headers): + cdef Writer writer + cdef object key + cdef object val + cdef bytes ret + + _init_writer(&writer) + + try: + if _write_str(&writer, status_line) < 0: + raise + if _write_byte(&writer, '\r') < 0: + raise + if _write_byte(&writer, '\n') < 0: + raise + + for key, val in headers.items(): + if _write_str(&writer, to_str(key)) < 0: + raise + if _write_byte(&writer, ':') < 0: + raise + if _write_byte(&writer, ' ') < 0: + raise + if _write_str(&writer, to_str(val)) < 0: + raise + if _write_byte(&writer, '\r') < 0: + raise + if _write_byte(&writer, '\n') < 0: + raise + + if _write_byte(&writer, '\r') < 0: + raise + if _write_byte(&writer, '\n') < 0: + raise + + return PyBytes_FromStringAndSize(writer.buf, writer.pos) + finally: + _release_writer(&writer) diff -Nru python-aiohttp-3.1.3/aiohttp/__init__.py python-aiohttp-3.5.1/aiohttp/__init__.py --- python-aiohttp-3.1.3/aiohttp/__init__.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/__init__.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,9 +1,10 @@ -__version__ = '3.1.3' +__version__ = '3.5.1' # This relies on each of the submodules having an __all__ variable. from . import hdrs # noqa from .client import * # noqa +from .client import ClientSession, ServerFingerprintMismatch # noqa from .cookiejar import * # noqa from .formdata import * # noqa from .helpers import * # noqa @@ -21,7 +22,7 @@ from .worker import GunicornWebWorker, GunicornUVLoopWebWorker # noqa workers = ('GunicornWebWorker', 'GunicornUVLoopWebWorker') except ImportError: # pragma: no cover - workers = () + workers = () # type: ignore __all__ = (client.__all__ + # noqa diff -Nru python-aiohttp-3.1.3/aiohttp/locks.py python-aiohttp-3.5.1/aiohttp/locks.py --- python-aiohttp-3.1.3/aiohttp/locks.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/locks.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,5 +1,12 @@ import asyncio import collections +from typing import Any, Optional + + +try: + from typing import Deque +except ImportError: + from typing_extensions import Deque # noqa class EventResultOrError: @@ -9,17 +16,17 @@ thanks to @vorpalsmith for the simple design. """ - def __init__(self, loop): + def __init__(self, loop: asyncio.AbstractEventLoop) -> None: self._loop = loop - self._exc = None + self._exc = None # type: Optional[BaseException] self._event = asyncio.Event(loop=loop) - self._waiters = collections.deque() + self._waiters = collections.deque() # type: Deque[asyncio.Future[Any]] - def set(self, exc=None): + def set(self, exc: Optional[BaseException]=None) -> None: self._exc = exc self._event.set() - async def wait(self): + async def wait(self) -> Any: waiter = self._loop.create_task(self._event.wait()) self._waiters.append(waiter) try: @@ -32,7 +39,7 @@ return val - def cancel(self): + def cancel(self) -> None: """ Cancel all waiters """ for waiter in self._waiters: waiter.cancel() diff -Nru python-aiohttp-3.1.3/aiohttp/multipart.py python-aiohttp-3.5.1/aiohttp/multipart.py --- python-aiohttp-3.1.3/aiohttp/multipart.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/multipart.py 2018-12-24 20:58:54.000000000 +0000 @@ -5,17 +5,21 @@ import uuid import warnings import zlib -from collections import Mapping, Sequence, deque +from collections import deque +from types import TracebackType +from typing import (TYPE_CHECKING, Any, Dict, Iterator, List, Mapping, # noqa + Optional, Sequence, Tuple, Type, Union, cast) from urllib.parse import parse_qsl, unquote, urlencode -from multidict import CIMultiDict +from multidict import CIMultiDict, CIMultiDictProxy, MultiMapping # noqa 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 HttpParser +from .http import HeadersParser from .payload import (JsonPayload, LookupError, Order, Payload, StringPayload, get_payload, payload_type) +from .streams import StreamReader __all__ = ('MultipartReader', 'MultipartWriter', 'BodyPartReader', @@ -23,6 +27,10 @@ 'parse_content_disposition', 'content_disposition_filename') +if TYPE_CHECKING: # pragma: no cover + from .client_reqrep import ClientResponse # noqa + + class BadContentDispositionHeader(RuntimeWarning): pass @@ -31,28 +39,30 @@ pass -def parse_content_disposition(header): +def parse_content_disposition(header: Optional[str]) -> Tuple[Optional[str], + Dict[str, str]]: - def is_token(string): - return string and TOKEN >= set(string) + def is_token(string: str) -> bool: + return bool(string) and TOKEN >= set(string) - def is_quoted(string): + def is_quoted(string: str) -> bool: return string[0] == string[-1] == '"' - def is_rfc5987(string): + def is_rfc5987(string: str) -> bool: return is_token(string) and string.count("'") == 2 - def is_extended_param(string): + def is_extended_param(string: str) -> bool: return string.endswith('*') - def is_continuous_param(string): + 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, *, chars=''.join(map(re.escape, CHAR))): + def unescape(text: str, *, + chars: str=''.join(map(re.escape, CHAR))) -> str: return re.sub('\\\\([{}])'.format(chars), '\\1', text) if not header: @@ -63,7 +73,7 @@ warnings.warn(BadContentDispositionHeader(header)) return None, {} - params = {} + params = {} # type: Dict[str, str] while parts: item = parts.pop(0) @@ -129,7 +139,8 @@ return disptype.lower(), params -def content_disposition_filename(params, name='filename'): +def content_disposition_filename(params: Mapping[str, str], + name: str='filename') -> Optional[str]: name_suf = '%s*' % name if not params: return None @@ -167,31 +178,32 @@ underlying connection and close it when it needs in. """ - def __init__(self, resp, stream): + def __init__(self, resp: 'ClientResponse', stream: Any) -> None: + # TODO: add strong annotation to stream self.resp = resp self.stream = stream - def __aiter__(self): + def __aiter__(self) -> 'MultipartResponseWrapper': return self - async def __anext__(self): + async def __anext__(self) -> Any: part = await self.next() if part is None: raise StopAsyncIteration # NOQA return part - def at_eof(self): + def at_eof(self) -> bool: """Returns True when all response data had been read.""" return self.resp.content.at_eof() - async def next(self): + async def next(self) -> Any: """Emits next multipart reader object.""" item = await self.stream.next() if self.stream.at_eof(): await self.release() return item - async def release(self): + async def release(self) -> None: """Releases the connection gracefully, reading all the content to the void.""" await self.resp.release() @@ -202,7 +214,9 @@ chunk_size = 8192 - def __init__(self, boundary, headers, content): + def __init__(self, boundary: bytes, + headers: Mapping[str, Optional[str]], + content: StreamReader) -> None: self.headers = headers self._boundary = boundary self._content = content @@ -210,27 +224,28 @@ length = self.headers.get(CONTENT_LENGTH, None) self._length = int(length) if length is not None else None self._read_bytes = 0 - self._unread = deque() - self._prev_chunk = None + # TODO: typeing.Deque is not supported by Python 3.5 + self._unread = deque() # type: Any + self._prev_chunk = None # type: Optional[bytes] self._content_eof = 0 - self._cache = {} + self._cache = {} # type: Dict[str, Any] - def __aiter__(self): + def __aiter__(self) -> 'BodyPartReader': return self - async def __anext__(self): + async def __anext__(self) -> Any: part = await self.next() if part is None: raise StopAsyncIteration # NOQA return part - async def next(self): + async def next(self) -> Any: item = await self.read() if not item: return None return item - async def read(self, *, decode=False): + async def read(self, *, decode: bool=False) -> Any: """Reads body part data. decode: Decodes data following by encoding @@ -246,7 +261,7 @@ return self.decode(data) return data - async def read_chunk(self, size=chunk_size): + async def read_chunk(self, size: int=chunk_size) -> bytes: """Reads body part content chunk of the specified size. size: chunk size @@ -267,7 +282,7 @@ 'reader did not read all the data or it is malformed' return chunk - async def _read_chunk_from_length(self, size): + 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, \ @@ -276,7 +291,7 @@ chunk = await self._content.read(chunk_size) return chunk - async def _read_chunk_from_stream(self, size): + 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, \ @@ -288,6 +303,7 @@ 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: @@ -296,7 +312,10 @@ idx = window.find(sub, max(0, len(self._prev_chunk) - len(sub))) if idx >= 0: # pushing boundary back to content - self._content.unread_data(window[idx:]) + 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] @@ -306,7 +325,7 @@ self._prev_chunk = chunk return result - async def readline(self): + async def readline(self) -> bytes: """Reads body part by line by line.""" if self._at_eof: return b'' @@ -335,14 +354,14 @@ return line - async def release(self): + 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=None): + 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 @@ -350,7 +369,7 @@ encoding = encoding or self.get_charset(default='utf-8') return data.decode(encoding) - async def json(self, *, encoding=None): + async def json(self, *, encoding: Optional[str]=None) -> Any: """Like read(), but assumes that body parts contains JSON data.""" data = await self.read(decode=True) if not data: @@ -358,23 +377,27 @@ encoding = encoding or self.get_charset(default='utf-8') return json.loads(data.decode(encoding)) - async def form(self, *, encoding=None): + async def form(self, *, + encoding: Optional[str]=None) -> List[Tuple[str, str]]: """Like read(), but assumes that body parts contains form urlencoded data. """ data = await self.read(decode=True) if not data: - return None - encoding = encoding or self.get_charset(default='utf-8') - return parse_qsl(data.rstrip().decode(encoding), + 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=encoding) + encoding=real_encoding) - def at_eof(self): + def at_eof(self) -> bool: """Returns True if the boundary was reached or False otherwise.""" return self._at_eof - def decode(self, data): + def decode(self, data: bytes) -> bytes: """Decodes data according the specified Content-Encoding or Content-Transfer-Encoding headers value. """ @@ -384,8 +407,8 @@ return self._decode_content(data) return data - def _decode_content(self, data): - encoding = self.headers[CONTENT_ENCODING].lower() + def _decode_content(self, data: bytes) -> bytes: + encoding = cast(str, self.headers[CONTENT_ENCODING]).lower() if encoding == 'deflate': return zlib.decompress(data, -zlib.MAX_WBITS) @@ -396,8 +419,8 @@ else: raise RuntimeError('unknown content encoding: {}'.format(encoding)) - def _decode_content_transfer(self, data): - encoding = self.headers[CONTENT_TRANSFER_ENCODING].lower() + def _decode_content_transfer(self, data: bytes) -> bytes: + encoding = cast(str, self.headers[CONTENT_TRANSFER_ENCODING]).lower() if encoding == 'base64': return base64.b64decode(data) @@ -409,23 +432,24 @@ raise RuntimeError('unknown content transfer encoding: {}' ''.format(encoding)) - def get_charset(self, default=None): + 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): + def name(self) -> Optional[str]: """Returns name specified in Content-Disposition header or None if missed or header is malformed. """ + _, params = parse_content_disposition( self.headers.get(CONTENT_DISPOSITION)) return content_disposition_filename(params, 'name') @reify - def filename(self): + def filename(self) -> Optional[str]: """Returns filename specified in Content-Disposition header or None if missed or header is malformed. """ @@ -437,19 +461,20 @@ @payload_type(BodyPartReader, order=Order.try_first) class BodyPartReaderPayload(Payload): - def __init__(self, value, *args, **kwargs): + def __init__(self, value: BodyPartReader, + *args: Any, **kwargs: Any) -> None: super().__init__(value, *args, **kwargs) - params = {} + params = {} # type: Dict[str, str] if value.name is not None: params['name'] = value.name if value.filename is not None: - params['filename'] = value.name + params['filename'] = value.filename if params: - self.set_content_disposition('attachment', **params) + self.set_content_disposition('attachment', True, **params) - async def write(self, writer): + async def write(self, writer: Any) -> None: field = self._value chunk = await field.read_chunk(size=2**16) while chunk: @@ -468,26 +493,27 @@ #: Body part reader class for non multipart/* content types. part_reader_cls = BodyPartReader - def __init__(self, headers, content): + 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 self._at_eof = False self._at_bof = True - self._unread = [] + self._unread = [] # type: List[bytes] - def __aiter__(self): + def __aiter__(self) -> 'MultipartReader': return self - async def __anext__(self): + async def __anext__(self) -> Any: part = await self.next() if part is None: raise StopAsyncIteration # NOQA return part @classmethod - def from_response(cls, response): + def from_response(cls, response: 'ClientResponse') -> Any: """Constructs reader instance from HTTP response. :param response: :class:`~aiohttp.client.ClientResponse` instance @@ -496,13 +522,13 @@ response.content)) return obj - def at_eof(self): + def at_eof(self) -> bool: """Returns True if the final boundary was reached or False otherwise. """ return self._at_eof - async def next(self): + async def next(self) -> Any: """Emits the next multipart body part.""" # So, if we're at BOF, we need to skip till the boundary. if self._at_eof: @@ -518,7 +544,7 @@ self._last_part = await self.fetch_next_part() return self._last_part - async def release(self): + 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() @@ -526,12 +552,12 @@ break await item.release() - async def fetch_next_part(self): + async def fetch_next_part(self) -> Any: """Returns the next body part reader.""" headers = await self._read_headers() return self._get_part_reader(headers) - def _get_part_reader(self, headers): + def _get_part_reader(self, headers: 'CIMultiDictProxy[str]') -> Any: """Dispatches the response by the `Content-Type` header, returning suitable reader instance. @@ -547,7 +573,7 @@ else: return self.part_reader_cls(self._boundary, headers, self._content) - def _get_boundary(self): + def _get_boundary(self) -> str: mimetype = parse_mimetype(self.headers[CONTENT_TYPE]) assert mimetype.type == 'multipart', ( @@ -565,12 +591,12 @@ return boundary - async def _readline(self): + async def _readline(self) -> bytes: if self._unread: return self._unread.pop() return await self._content.readline() - async def _read_until_first_boundary(self): + async def _read_until_first_boundary(self) -> None: while True: chunk = await self._readline() if chunk == b'': @@ -583,7 +609,7 @@ self._at_eof = True return - async def _read_boundary(self): + async def _read_boundary(self) -> None: chunk = (await self._readline()).rstrip() if chunk == self._boundary: pass @@ -607,7 +633,7 @@ raise ValueError('Invalid boundary %r, expected %r' % (chunk, self._boundary)) - async def _read_headers(self): + async def _read_headers(self) -> 'CIMultiDictProxy[str]': lines = [b''] while True: chunk = await self._content.readline() @@ -615,11 +641,11 @@ lines.append(chunk) if not chunk: break - parser = HttpParser() - headers, *_ = parser.parse_headers(lines) + parser = HeadersParser() + headers, raw_headers = parser.parse_headers(lines) return headers - async def _maybe_release_last_part(self): + 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(): @@ -628,10 +654,14 @@ self._last_part = None +_Part = Tuple[Payload, 'MultiMapping[str]', str, str] + + class MultipartWriter(Payload): """Multipart body writer.""" - def __init__(self, subtype='mixed', boundary=None): + 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. @@ -648,27 +678,31 @@ super().__init__(None, content_type=ctype) - self._parts = [] - self._headers = CIMultiDict() + self._parts = [] # type: List[_Part] # noqa + self._headers = CIMultiDict() # type: CIMultiDict[str] + assert self.content_type is not None self._headers[CONTENT_TYPE] = self.content_type - def __enter__(self): + def __enter__(self) -> 'MultipartWriter': return self - def __exit__(self, exc_type, exc_val, exc_tb): + def __exit__(self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType]) -> None: pass - def __iter__(self): + def __iter__(self) -> Iterator[_Part]: return iter(self._parts) - def __len__(self): + def __len__(self) -> int: return len(self._parts) _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): + def _boundary_value(self) -> str: """Wrap boundary parameter value in quotes, if necessary. Reads self.boundary and returns a unicode sting. @@ -700,10 +734,14 @@ return '"' + quoted_value_content.decode('ascii') + '"' @property - def boundary(self): + def boundary(self) -> str: return self._boundary.decode('ascii') - def append(self, obj, headers=None): + def append( + self, + obj: Any, + headers: Optional['MultiMapping[str]']=None + ) -> Payload: if headers is None: headers = CIMultiDict() @@ -711,7 +749,10 @@ if obj.headers is not None: obj.headers.update(headers) else: - obj._headers = headers + if isinstance(headers, CIMultiDict): + obj._headers = headers + else: + obj._headers = CIMultiDict(headers) return self.append_payload(obj) else: try: @@ -719,14 +760,16 @@ except LookupError: raise TypeError - def append_payload(self, payload): + def append_payload(self, payload: Payload) -> Payload: """Adds a new body part to multipart writer.""" # content-type + assert payload.headers is not None if CONTENT_TYPE not in payload.headers: + assert payload.content_type is not None payload.headers[CONTENT_TYPE] = payload.content_type # compression - encoding = payload.headers.get(CONTENT_ENCODING, '').lower() + encoding = payload.headers.get(CONTENT_ENCODING, '').lower() # type: Optional[str] # noqa if encoding and encoding not in ('deflate', 'gzip', 'identity'): raise RuntimeError('unknown content encoding: {}'.format(encoding)) if encoding == 'identity': @@ -734,7 +777,7 @@ # te encoding te_encoding = payload.headers.get( - CONTENT_TRANSFER_ENCODING, '').lower() + CONTENT_TRANSFER_ENCODING, '').lower() # type: Optional[str] # noqa if te_encoding not in ('', 'base64', 'quoted-printable', 'binary'): raise RuntimeError('unknown content transfer encoding: {}' ''.format(te_encoding)) @@ -751,17 +794,26 @@ [k + ': ' + v + '\r\n' for k, v in payload.headers.items()] ).encode('utf-8') + b'\r\n' - self._parts.append((payload, headers, encoding, te_encoding)) + self._parts.append((payload, headers, encoding, te_encoding)) # type: ignore # noqa return payload - def append_json(self, obj, headers=None): + 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, headers=None): + 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)) @@ -777,7 +829,7 @@ content_type='application/x-www-form-urlencoded')) @property - def size(self): + def size(self) -> Optional[int]: """Size of the payload.""" if not self._parts: return 0 @@ -787,7 +839,7 @@ if encoding or te_encoding or part.size is None: return None - total += ( + total += int( 2 + len(self._boundary) + 2 + # b'--'+self._boundary+b'\r\n' part.size + len(headers) + 2 # b'\r\n' @@ -796,7 +848,8 @@ total += 2 + len(self._boundary) + 4 # b'--'+self._boundary+b'--\r\n' return total - async def write(self, writer): + async def write(self, writer: Any, + close_boundary: bool=True) -> None: """Write body.""" if not self._parts: return @@ -811,36 +864,38 @@ w.enable_compression(encoding) if te_encoding: w.enable_encoding(te_encoding) - await part.write(w) + await part.write(w) # type: ignore await w.write_eof() else: await part.write(writer) await writer.write(b'\r\n') - await writer.write(b'--' + self._boundary + b'--\r\n') + if close_boundary: + await writer.write(b'--' + self._boundary + b'--\r\n') class MultipartPayloadWriter: - def __init__(self, writer): + def __init__(self, writer: Any) -> None: self._writer = writer - self._encoding = None - self._compress = None + self._encoding = None # type: Optional[str] + self._compress = None # type: Any + self._encoding_buffer = None # type: Optional[bytearray] - def enable_encoding(self, encoding): + 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='deflate'): + def enable_compression(self, encoding: str='deflate') -> None: zlib_mode = (16 + zlib.MAX_WBITS if encoding == 'gzip' else -zlib.MAX_WBITS) self._compress = zlib.compressobj(wbits=zlib_mode) - async def write_eof(self): + async def write_eof(self) -> None: if self._compress is not None: chunk = self._compress.flush() if chunk: @@ -852,7 +907,7 @@ await self._writer.write(base64.b64encode( self._encoding_buffer)) - async def write(self, chunk): + async def write(self, chunk: bytes) -> None: if self._compress is not None: if chunk: chunk = self._compress.compress(chunk) @@ -860,16 +915,17 @@ return if self._encoding == 'base64': - self._encoding_buffer.extend(chunk) + buf = self._encoding_buffer + assert buf is not None + buf.extend(chunk) - if self._encoding_buffer: - buffer = self._encoding_buffer - div, mod = divmod(len(buffer), 3) + if buf: + div, mod = divmod(len(buf), 3) enc_chunk, self._encoding_buffer = ( - buffer[:div * 3], buffer[div * 3:]) + buf[:div * 3], buf[div * 3:]) if enc_chunk: - enc_chunk = base64.b64encode(enc_chunk) - await self._writer.write(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: diff -Nru python-aiohttp-3.1.3/aiohttp/payload.py python-aiohttp-3.5.1/aiohttp/payload.py --- python-aiohttp-3.1.3/aiohttp/payload.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/payload.py 2018-12-24 20:58:54.000000000 +0000 @@ -5,15 +5,18 @@ import os import warnings from abc import ABC, abstractmethod -from collections.abc import AsyncIterable from itertools import chain +from typing import (IO, TYPE_CHECKING, Any, ByteString, Callable, Dict, # noqa + Iterable, List, Optional, Text, 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 DEFAULT_LIMIT +from .streams import DEFAULT_LIMIT, StreamReader +from .typedefs import JSONEncoder, _CIMultiDict __all__ = ('PAYLOAD_REGISTRY', 'get_payload', 'payload_type', 'Payload', @@ -29,27 +32,30 @@ pass -class Order(enum.Enum): +class Order(str, enum.Enum): normal = 'normal' try_first = 'try_first' try_last = 'try_last' -def get_payload(data, *args, **kwargs): +def get_payload(data: Any, *args: Any, **kwargs: Any) -> 'Payload': return PAYLOAD_REGISTRY.get(data, *args, **kwargs) -def register_payload(factory, type, *, order=Order.normal): +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, *, order=Order.normal): + def __init__(self, type: Any, *, order: Order=Order.normal) -> None: self.type = type self.order = order - def __call__(self, factory): + def __call__(self, factory: Type['Payload']) -> Type['Payload']: register_payload(factory, self.type, order=self.order) return factory @@ -60,12 +66,16 @@ note: we need zope.interface for more efficient adapter search """ - def __init__(self): - self._first = [] - self._normal = [] - self._last = [] - - def get(self, data, *args, _CHAIN=chain, **kwargs): + def __init__(self) -> None: + self._first = [] # type: List[Tuple[Type[Payload], Any]] + self._normal = [] # type: List[Tuple[Type[Payload], Any]] + self._last = [] # type: List[Tuple[Type[Payload], Any]] + + def get(self, + data: Any, + *args: Any, + _CHAIN: Any=chain, + **kwargs: Any) -> 'Payload': if isinstance(data, Payload): return data for factory, type in _CHAIN(self._first, self._normal, self._last): @@ -74,7 +84,11 @@ raise LookupError() - def register(self, factory, type, *, order=Order.normal): + def register(self, + factory: Type['Payload'], + type: Any, + *, + order: Order=Order.normal) -> None: if order is Order.try_first: self._first.append((factory, type)) elif order is Order.normal: @@ -87,12 +101,23 @@ class Payload(ABC): - _size = None - _headers = None - _content_type = 'application/octet-stream' - - def __init__(self, value, *, headers=None, content_type=sentinel, - filename=None, encoding=None, **kwargs): + _size = None # type: Optional[float] + _headers = None # type: Optional[_CIMultiDict] + _content_type = 'application/octet-stream' # type: Optional[str] + + 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._value = value self._encoding = encoding self._filename = filename @@ -107,27 +132,27 @@ self._content_type = content_type @property - def size(self): + def size(self) -> Optional[float]: """Size of the payload.""" return self._size @property - def filename(self): + def filename(self) -> Optional[str]: """Filename of the payload.""" return self._filename @property - def headers(self): + def headers(self) -> Optional[_CIMultiDict]: """Custom item headers""" return self._headers @property - def encoding(self): + def encoding(self) -> Optional[str]: """Payload encoding""" return self._encoding @property - def content_type(self): + def content_type(self) -> Optional[str]: """Content type""" if self._content_type is not None: return self._content_type @@ -137,7 +162,10 @@ else: return Payload._content_type - def set_content_disposition(self, disptype, quote_fields=True, **params): + def set_content_disposition(self, + disptype: str, + quote_fields: bool=True, + **params: Any) -> None: """Sets ``Content-Disposition`` header.""" if self._headers is None: self._headers = CIMultiDict() @@ -146,7 +174,7 @@ disptype, quote_fields=quote_fields, **params) @abstractmethod - async def write(self, writer): + async def write(self, writer: AbstractStreamWriter) -> None: """Write payload. writer is an AbstractStreamWriter instance: @@ -155,7 +183,10 @@ class BytesPayload(Payload): - def __init__(self, value, *args, **kwargs): + def __init__(self, + value: ByteString, + *args: Any, + **kwargs: Any) -> None: if not isinstance(value, (bytes, bytearray, memoryview)): raise TypeError("value argument must be byte-ish, not (!r)" .format(type(value))) @@ -177,40 +208,56 @@ "io.BytesIO object instead", ResourceWarning, **kwargs) - async def write(self, writer): + async def write(self, writer: AbstractStreamWriter) -> None: await writer.write(self._value) class StringPayload(BytesPayload): - def __init__(self, value, *args, - encoding=None, content_type=None, **kwargs): + def __init__(self, + value: Text, + *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' + real_encoding = 'utf-8' content_type = 'text/plain; charset=utf-8' else: mimetype = parse_mimetype(content_type) - encoding = mimetype.parameters.get('charset', 'utf-8') + 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(encoding), - encoding=encoding, content_type=content_type, *args, **kwargs) + value.encode(real_encoding), + encoding=real_encoding, + content_type=content_type, + *args, + **kwargs, + ) class StringIOPayload(StringPayload): - def __init__(self, value, *args, **kwargs): + def __init__(self, + value: IO[str], + *args: Any, + **kwargs: Any) -> None: super().__init__(value.read(), *args, **kwargs) class IOBasePayload(Payload): - def __init__(self, value, disposition='attachment', *args, **kwargs): + def __init__(self, + value: IO[Any], + disposition: str='attachment', + *args: Any, + **kwargs: Any) -> None: if 'filename' not in kwargs: kwargs['filename'] = guess_filename(value) @@ -219,7 +266,7 @@ if self._filename is not None and disposition is not None: self.set_content_disposition(disposition, filename=self._filename) - async def write(self, writer): + async def write(self, writer: AbstractStreamWriter) -> None: try: chunk = self._value.read(DEFAULT_LIMIT) while chunk: @@ -231,8 +278,12 @@ class TextIOPayload(IOBasePayload): - def __init__(self, value, *args, - encoding=None, content_type=None, **kwargs): + 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: @@ -247,16 +298,20 @@ super().__init__( value, - content_type=content_type, encoding=encoding, *args, **kwargs) + content_type=content_type, + encoding=encoding, + *args, + **kwargs, + ) @property - def size(self): + def size(self) -> Optional[float]: try: return os.fstat(self._value.fileno()).st_size - self._value.tell() except OSError: return None - async def write(self, writer): + async def write(self, writer: AbstractStreamWriter) -> None: try: chunk = self._value.read(DEFAULT_LIMIT) while chunk: @@ -269,7 +324,7 @@ class BytesIOPayload(IOBasePayload): @property - def size(self): + def size(self) -> float: position = self._value.tell() end = self._value.seek(0, os.SEEK_END) self._value.seek(position) @@ -279,7 +334,7 @@ class BufferedReaderPayload(IOBasePayload): @property - def size(self): + def size(self) -> Optional[float]: try: return os.fstat(self._value.fileno()).st_size - self._value.tell() except OSError: @@ -290,18 +345,39 @@ class JsonPayload(BytesPayload): - def __init__(self, value, - encoding='utf-8', content_type='application/json', - dumps=json.dumps, *args, **kwargs): + 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 AsyncIterator, AsyncIterable + + _AsyncIterator = AsyncIterator[bytes] + _AsyncIterable = AsyncIterable[bytes] +else: + from collections.abc import AsyncIterable, AsyncIterator + + _AsyncIterator = AsyncIterator + _AsyncIterable = AsyncIterable + + class AsyncIterablePayload(Payload): - def __init__(self, value, *args, **kwargs): + _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, " @@ -314,15 +390,22 @@ self._iter = value.__aiter__() - async def write(self, writer): - 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 + 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() @@ -334,6 +417,7 @@ 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, diff -Nru python-aiohttp-3.1.3/aiohttp/payload_streamer.py python-aiohttp-3.5.1/aiohttp/payload_streamer.py --- python-aiohttp-3.1.3/aiohttp/payload_streamer.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/payload_streamer.py 2018-12-24 20:58:54.000000000 +0000 @@ -23,7 +23,9 @@ import asyncio import warnings +from typing import Any, Awaitable, Callable, Dict, Tuple +from .abc import AbstractStreamWriter from .payload import Payload, payload_type @@ -32,39 +34,42 @@ class _stream_wrapper: - def __init__(self, coro, args, kwargs): + def __init__(self, + coro: Callable[..., Awaitable[None]], + args: Tuple[Any, ...], + kwargs: Dict[str, Any]) -> None: self.coro = asyncio.coroutine(coro) self.args = args self.kwargs = kwargs - async def __call__(self, writer): + async def __call__(self, writer: AbstractStreamWriter) -> None: await self.coro(writer, *self.args, **self.kwargs) class streamer: - def __init__(self, coro): + 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, **kwargs): + 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): + async def write(self, writer: AbstractStreamWriter) -> None: await self._value(writer) @payload_type(streamer) class StreamPayload(StreamWrapperPayload): - def __init__(self, value, *args, **kwargs): + def __init__(self, value: Any, *args: Any, **kwargs: Any) -> None: super().__init__(value(), *args, **kwargs) - async def write(self, writer): + async def write(self, writer: AbstractStreamWriter) -> None: await self._value(writer) diff -Nru python-aiohttp-3.1.3/aiohttp/pytest_plugin.py python-aiohttp-3.5.1/aiohttp/pytest_plugin.py --- python-aiohttp-3.1.3/aiohttp/pytest_plugin.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/pytest_plugin.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,7 +1,7 @@ import asyncio -import collections import contextlib import warnings +from collections.abc import Callable import pytest @@ -24,7 +24,7 @@ tokio = None -def pytest_addoption(parser): +def pytest_addoption(parser): # type: ignore parser.addoption( '--aiohttp-fast', action='store_true', default=False, help='run tests faster by disabling extra checks') @@ -36,7 +36,7 @@ help='enable event loop debug mode') -def pytest_fixture_setup(fixturedef): +def pytest_fixture_setup(fixturedef): # type: ignore """ Allow fixtures to be coroutines. Run coroutine fixtures in an event loop. """ @@ -57,7 +57,7 @@ fixturedef.argnames += ('request',) strip_request = True - def wrapper(*args, **kwargs): + def wrapper(*args, **kwargs): # type: ignore request = kwargs['request'] if strip_request: del kwargs['request'] @@ -78,7 +78,7 @@ # then advance it again in a finalizer gen = func(*args, **kwargs) - def finalizer(): + def finalizer(): # type: ignore try: return _loop.run_until_complete(gen.__anext__()) except StopAsyncIteration: # NOQA @@ -93,19 +93,19 @@ @pytest.fixture -def fast(request): +def fast(request): # type: ignore """--fast config option""" return request.config.getoption('--aiohttp-fast') @pytest.fixture -def loop_debug(request): +def loop_debug(request): # type: ignore """--enable-loop-debug config option""" return request.config.getoption('--aiohttp-enable-loop-debug') @contextlib.contextmanager -def _runtime_warning_context(): +def _runtime_warning_context(): # type: ignore """ Context manager which checks for RuntimeWarnings, specifically to avoid "coroutine 'X' was never awaited" warnings being missed. @@ -115,7 +115,8 @@ 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] + for w in _warnings # type: ignore + if w.category == RuntimeWarning] if rw: raise RuntimeError('{} Runtime Warning{},\n{}'.format( len(rw), @@ -125,7 +126,7 @@ @contextlib.contextmanager -def _passthrough_loop_context(loop, fast=False): +def _passthrough_loop_context(loop, fast=False): # type: ignore """ setups and tears down a loop unless one is passed in via the loop argument when it's passed straight through. @@ -140,7 +141,7 @@ teardown_test_loop(loop, fast=fast) -def pytest_pycollect_makeitem(collector, name, obj): +def pytest_pycollect_makeitem(collector, name, obj): # type: ignore """ Fix pytest collecting for coroutines. """ @@ -148,7 +149,7 @@ return list(collector._genfunctions(name, obj)) -def pytest_pyfunc_call(pyfuncitem): +def pytest_pyfunc_call(pyfuncitem): # type: ignore """ Run coroutines in an event loop instead of a normal function call. """ @@ -164,23 +165,23 @@ return True -def pytest_generate_tests(metafunc): +def pytest_generate_tests(metafunc): # type: ignore if 'loop_factory' not in metafunc.fixturenames: return loops = metafunc.config.option.aiohttp_loop - avail_factories = {'pyloop': asyncio.new_event_loop} + avail_factories = {'pyloop': asyncio.DefaultEventLoopPolicy} if uvloop is not None: # pragma: no cover - avail_factories['uvloop'] = uvloop.new_event_loop + avail_factories['uvloop'] = uvloop.EventLoopPolicy if tokio is not None: # pragma: no cover - avail_factories['tokio'] = tokio.new_event_loop + avail_factories['tokio'] = tokio.EventLoopPolicy if loops == 'all': loops = 'pyloop,uvloop?,tokio?' - factories = {} + factories = {} # type: ignore for name in loops.split(','): required = not name.endswith('?') name = name.strip(' ?') @@ -198,9 +199,11 @@ @pytest.fixture -def loop(loop_factory, fast, loop_debug): +def loop(loop_factory, fast, loop_debug): # type: ignore """Return an instance of the event loop.""" - with loop_context(loop_factory, fast=fast) as _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) @@ -208,27 +211,27 @@ @pytest.fixture -def unused_port(aiohttp_unused_port): # pragma: no cover +def unused_port(aiohttp_unused_port): # type: ignore # pragma: no cover warnings.warn("Deprecated, use aiohttp_unused_port fixture instead", DeprecationWarning) return aiohttp_unused_port @pytest.fixture -def aiohttp_unused_port(): +def aiohttp_unused_port(): # type: ignore """Return a port that is unused on the current host.""" return _unused_port @pytest.fixture -def aiohttp_server(loop): +def aiohttp_server(loop): # type: ignore """Factory to create a TestServer instance, given an app. aiohttp_server(app, **kwargs) """ servers = [] - async def go(app, *, port=None, **kwargs): + async def go(app, *, port=None, **kwargs): # type: ignore server = TestServer(app, port=port) await server.start_server(loop=loop, **kwargs) servers.append(server) @@ -236,7 +239,7 @@ yield go - async def finalize(): + async def finalize(): # type: ignore while servers: await servers.pop().close() @@ -244,21 +247,21 @@ @pytest.fixture -def test_server(aiohttp_server): # pragma: no cover +def test_server(aiohttp_server): # type: ignore # pragma: no cover warnings.warn("Deprecated, use aiohttp_server fixture instead", DeprecationWarning) return aiohttp_server @pytest.fixture -def aiohttp_raw_server(loop): +def aiohttp_raw_server(loop): # type: ignore """Factory to create a RawTestServer instance, given a web handler. aiohttp_raw_server(handler, **kwargs) """ servers = [] - async def go(handler, *, port=None, **kwargs): + async def go(handler, *, port=None, **kwargs): # type: ignore server = RawTestServer(handler, port=port) await server.start_server(loop=loop, **kwargs) servers.append(server) @@ -266,7 +269,7 @@ yield go - async def finalize(): + async def finalize(): # type: ignore while servers: await servers.pop().close() @@ -274,14 +277,14 @@ @pytest.fixture -def raw_test_server(aiohttp_raw_server): # pragma: no cover +def raw_test_server(aiohttp_raw_server): # type: ignore # pragma: no cover warnings.warn("Deprecated, use aiohttp_raw_server fixture instead", DeprecationWarning) return aiohttp_raw_server @pytest.fixture -def aiohttp_client(loop): +def aiohttp_client(loop): # type: ignore """Factory to create a TestClient instance. aiohttp_client(app, **kwargs) @@ -290,10 +293,10 @@ """ clients = [] - async def go(__param, *args, server_kwargs=None, **kwargs): + async def go(__param, *args, server_kwargs=None, **kwargs): # type: ignore - if isinstance(__param, collections.Callable) and \ - not isinstance(__param, (Application, BaseTestServer)): + if (isinstance(__param, Callable) and # type: ignore + not isinstance(__param, (Application, BaseTestServer))): __param = __param(loop, *args, **kwargs) kwargs = {} else: @@ -314,7 +317,7 @@ yield go - async def finalize(): + async def finalize(): # type: ignore while clients: await clients.pop().close() @@ -322,7 +325,7 @@ @pytest.fixture -def test_client(aiohttp_client): # pragma: no cover +def test_client(aiohttp_client): # type: ignore # pragma: no cover warnings.warn("Deprecated, use aiohttp_client fixture instead", DeprecationWarning) return aiohttp_client diff -Nru python-aiohttp-3.1.3/aiohttp/py.typed python-aiohttp-3.5.1/aiohttp/py.typed --- python-aiohttp-3.1.3/aiohttp/py.typed 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/py.typed 2018-12-24 20:58:54.000000000 +0000 @@ -0,0 +1 @@ +Marker \ No newline at end of file diff -Nru python-aiohttp-3.1.3/aiohttp/resolver.py python-aiohttp-3.5.1/aiohttp/resolver.py --- python-aiohttp-3.1.3/aiohttp/resolver.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/resolver.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,7 +1,9 @@ import asyncio import socket +from typing import Any, Dict, List, Optional from .abc import AbstractResolver +from .helpers import get_running_loop __all__ = ('ThreadedResolver', 'AsyncResolver', 'DefaultResolver') @@ -20,12 +22,11 @@ concurrent.futures.ThreadPoolExecutor. """ - def __init__(self, loop=None): - if loop is None: - loop = asyncio.get_event_loop() - self._loop = loop + def __init__(self, loop: Optional[asyncio.AbstractEventLoop]=None) -> None: + self._loop = get_running_loop(loop) - async def resolve(self, host, port=0, family=socket.AF_INET): + async def resolve(self, host: str, port: int=0, + family: int=socket.AF_INET) -> List[Dict[str, Any]]: infos = await self._loop.getaddrinfo( host, port, type=socket.SOCK_STREAM, family=family) @@ -39,28 +40,27 @@ return hosts - async def close(self): + async def close(self) -> None: pass class AsyncResolver(AbstractResolver): """Use the `aiodns` package to make asynchronous DNS lookups""" - def __init__(self, loop=None, *args, **kwargs): - if loop is None: - loop = asyncio.get_event_loop() - + 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 = loop + 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 + self.resolve = self._resolve_with_query # type: ignore - async def resolve(self, host, port=0, family=socket.AF_INET): + 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: @@ -79,7 +79,9 @@ return hosts - async def _resolve_with_query(self, host, port=0, family=socket.AF_INET): + 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: @@ -104,7 +106,7 @@ return hosts - async def close(self): + async def close(self) -> None: return self._resolver.cancel() diff -Nru python-aiohttp-3.1.3/aiohttp/signals.py python-aiohttp-3.5.1/aiohttp/signals.py --- python-aiohttp-3.1.3/aiohttp/signals.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/signals.py 2018-12-24 20:58:54.000000000 +0000 @@ -32,4 +32,4 @@ raise RuntimeError("Cannot send non-frozen signal.") for receiver in self: - await receiver(*args, **kwargs) + await receiver(*args, **kwargs) # type: ignore diff -Nru python-aiohttp-3.1.3/aiohttp/signals.pyi python-aiohttp-3.5.1/aiohttp/signals.pyi --- python-aiohttp-3.1.3/aiohttp/signals.pyi 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/signals.pyi 2018-12-24 20:58:54.000000000 +0000 @@ -0,0 +1,18 @@ +from typing import Any, Generic, TypeVar + +from aiohttp.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 -Nru python-aiohttp-3.1.3/aiohttp/streams.py python-aiohttp-3.5.1/aiohttp/streams.py --- python-aiohttp-3.1.3/aiohttp/streams.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/streams.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,30 +1,42 @@ import asyncio import collections +import warnings +from typing import List # noqa +from typing import Awaitable, Callable, Generic, Optional, Tuple, TypeVar -from .helpers import set_exception, set_result +from .base_protocol import BaseProtocol +from .helpers import BaseTimerContext, set_exception, set_result from .log import internal_logger +try: # pragma: no cover + from typing import Deque # noqa +except ImportError: + from typing_extensions import Deque # noqa + + __all__ = ( 'EMPTY_PAYLOAD', 'EofStream', 'StreamReader', 'DataQueue', 'FlowControlDataQueue') DEFAULT_LIMIT = 2 ** 16 +_T = TypeVar('_T') + class EofStream(Exception): """eof stream indication.""" -class AsyncStreamIterator: +class AsyncStreamIterator(Generic[_T]): - def __init__(self, read_func): + def __init__(self, read_func: Callable[[], Awaitable[_T]]) -> None: self.read_func = read_func - def __aiter__(self): + def __aiter__(self) -> 'AsyncStreamIterator[_T]': return self - async def __anext__(self): + async def __anext__(self) -> _T: try: rv = await self.read_func() except EofStream: @@ -34,9 +46,16 @@ return rv -class ChunkTupleAsyncStreamIterator(AsyncStreamIterator): - async def __anext__(self): - rv = await self.read_func() +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 # NOQA return rv @@ -44,32 +63,32 @@ class AsyncStreamReaderMixin: - def __aiter__(self): - return AsyncStreamIterator(self.readline) + def __aiter__(self) -> AsyncStreamIterator[bytes]: + return AsyncStreamIterator(self.readline) # type: ignore - def iter_chunked(self, n): + 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)) + return AsyncStreamIterator(lambda: self.read(n)) # type: ignore - def iter_any(self): + def iter_any(self) -> AsyncStreamIterator[bytes]: """Returns an asynchronous iterator that yields all the available data as soon as it is received Python-3.5 available for Python 3.5+ only """ - return AsyncStreamIterator(self.readany) + return AsyncStreamIterator(self.readany) # type: ignore - def iter_chunks(self): + def iter_chunks(self) -> ChunkTupleAsyncStreamIterator: """Returns an asynchronous iterator that yields 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.readchunk) + return ChunkTupleAsyncStreamIterator(self) # type: ignore class StreamReader(AsyncStreamReaderMixin): @@ -88,8 +107,10 @@ total_bytes = 0 - def __init__(self, protocol, - *, limit=DEFAULT_LIMIT, timer=None, loop=None): + def __init__(self, protocol: BaseProtocol, + *, limit: int=DEFAULT_LIMIT, + timer: Optional[BaseTimerContext]=None, + loop: Optional[asyncio.AbstractEventLoop]=None) -> None: self._protocol = protocol self._low_water = limit self._high_water = limit * 2 @@ -98,17 +119,17 @@ self._loop = loop self._size = 0 self._cursor = 0 - self._http_chunk_splits = None - self._buffer = collections.deque() + 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 - self._eof_waiter = None - self._exception = None + self._waiter = None # type: Optional[asyncio.Future[bool]] + self._eof_waiter = None # type: Optional[asyncio.Future[bool]] + self._exception = None # type: Optional[BaseException] self._timer = timer - self._eof_callbacks = [] + self._eof_callbacks = [] # type: List[Callable[[], None]] - def __repr__(self): + def __repr__(self) -> str: info = [self.__class__.__name__] if self._size: info.append('%d bytes' % self._size) @@ -122,10 +143,10 @@ info.append('e=%r' % self._exception) return '<%s>' % ' '.join(info) - def exception(self): + def exception(self) -> Optional[BaseException]: return self._exception - def set_exception(self, exc): + def set_exception(self, exc: BaseException) -> None: self._exception = exc self._eof_callbacks.clear() @@ -139,7 +160,7 @@ set_exception(waiter, exc) self._eof_waiter = None - def on_eof(self, callback): + def on_eof(self, callback: Callable[[], None]) -> None: if self._eof: try: callback() @@ -148,7 +169,7 @@ else: self._eof_callbacks.append(callback) - def feed_eof(self): + def feed_eof(self) -> None: self._eof = True waiter = self._waiter @@ -169,15 +190,15 @@ self._eof_callbacks.clear() - def is_eof(self): + def is_eof(self) -> bool: """Return True if 'feed_eof' was called.""" return self._eof - def at_eof(self): + 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): + async def wait_eof(self) -> None: if self._eof: return @@ -188,9 +209,13 @@ finally: self._eof_waiter = None - def unread_data(self, data): + 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 @@ -203,7 +228,7 @@ self._eof_counter = 0 # TODO: size is ignored, remove the param later - def feed_data(self, data, size=0): + def feed_data(self, data: bytes, size: int=0) -> None: assert not self._eof, 'feed_data after feed_eof' if not data: @@ -222,11 +247,11 @@ not self._protocol._reading_paused): self._protocol.pause_reading() - def begin_http_chunk_receiving(self): + def begin_http_chunk_receiving(self) -> None: if self._http_chunk_splits is None: self._http_chunk_splits = [] - def end_http_chunk_receiving(self): + 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") @@ -234,7 +259,13 @@ self._http_chunk_splits[-1] != self.total_bytes: self._http_chunk_splits.append(self.total_bytes) - async def _wait(self, func_name): + # wake up readchunk when end of http chunk received + waiter = self._waiter + if waiter is not None: + self._waiter = None + set_result(waiter, False) + + 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 @@ -253,7 +284,7 @@ finally: self._waiter = None - async def readline(self): + async def readline(self) -> bytes: if self._exception is not None: raise self._exception @@ -283,7 +314,7 @@ return b''.join(line) - async def read(self, n=-1): + async def read(self, n: int=-1) -> bytes: if self._exception is not None: raise self._exception @@ -320,7 +351,7 @@ return self._read_nowait(n) - async def readany(self): + async def readany(self) -> bytes: if self._exception is not None: raise self._exception @@ -329,7 +360,7 @@ return self._read_nowait(-1) - async def readchunk(self): + 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 @@ -346,24 +377,26 @@ return (b"", True) await self._wait('readchunk') - if not self._buffer: + if not self._buffer and not self._http_chunk_splits: # end of file return (b"", False) elif self._http_chunk_splits is not None: while self._http_chunk_splits: pos = self._http_chunk_splits[0] self._http_chunk_splits = self._http_chunk_splits[1:] + if pos == self._cursor: + return (b"", True) if pos > self._cursor: return (self._read_nowait(pos-self._cursor), True) return (self._read_nowait(-1), False) else: return (self._read_nowait_chunk(-1), False) - async def readexactly(self, n): + async def readexactly(self, n: int) -> bytes: if self._exception is not None: raise self._exception - blocks = [] + blocks = [] # type: List[bytes] while n > 0: block = await self.read(n) if not block: @@ -375,7 +408,7 @@ return b''.join(blocks) - def read_nowait(self, n=-1): + 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 @@ -389,7 +422,7 @@ return self._read_nowait(n) - def _read_nowait_chunk(self, 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: @@ -411,7 +444,7 @@ self._protocol.resume_reading() return data - def _read_nowait(self, n): + def _read_nowait(self, n: int) -> bytes: chunks = [] while self._buffer: @@ -427,79 +460,79 @@ class EmptyStreamReader(AsyncStreamReaderMixin): - def exception(self): + def exception(self) -> Optional[BaseException]: return None - def set_exception(self, exc): + def set_exception(self, exc: BaseException) -> None: pass - def on_eof(self, callback): + def on_eof(self, callback: Callable[[], None]) -> None: try: callback() except Exception: internal_logger.exception('Exception in eof callback') - def feed_eof(self): + def feed_eof(self) -> None: pass - def is_eof(self): + def is_eof(self) -> bool: return True - def at_eof(self): + def at_eof(self) -> bool: return True - async def wait_eof(self): + async def wait_eof(self) -> None: return - def feed_data(self, data): + def feed_data(self, data: bytes, n: int=0) -> None: pass - async def readline(self): + async def readline(self) -> bytes: return b'' - async def read(self, n=-1): + async def read(self, n: int=-1) -> bytes: return b'' - async def readany(self): + async def readany(self) -> bytes: return b'' - async def readchunk(self): - return (b'', False) + async def readchunk(self) -> Tuple[bytes, bool]: + return (b'', True) - async def readexactly(self, n): + async def readexactly(self, n: int) -> bytes: raise asyncio.streams.IncompleteReadError(b'', n) - def read_nowait(self): + def read_nowait(self) -> bytes: return b'' EMPTY_PAYLOAD = EmptyStreamReader() -class DataQueue: +class DataQueue(Generic[_T]): """DataQueue is a general-purpose blocking queue with one reader.""" - def __init__(self, *, loop=None): + def __init__(self, loop: asyncio.AbstractEventLoop) -> None: self._loop = loop self._eof = False - self._waiter = None - self._exception = None + self._waiter = None # type: Optional[asyncio.Future[bool]] + self._exception = None # type: Optional[BaseException] self._size = 0 - self._buffer = collections.deque() + self._buffer = collections.deque() # type: Deque[Tuple[_T, int]] - def __len__(self): + def __len__(self) -> int: return len(self._buffer) - def is_eof(self): + def is_eof(self) -> bool: return self._eof - def at_eof(self): + def at_eof(self) -> bool: return self._eof and not self._buffer - def exception(self): + def exception(self) -> Optional[BaseException]: return self._exception - def set_exception(self, exc): + def set_exception(self, exc: BaseException) -> None: self._eof = True self._exception = exc @@ -508,7 +541,7 @@ set_exception(waiter, exc) self._waiter = None - def feed_data(self, data, size=0): + def feed_data(self, data: _T, size: int=0) -> None: self._size += size self._buffer.append((data, size)) @@ -517,7 +550,7 @@ self._waiter = None set_result(waiter, True) - def feed_eof(self): + def feed_eof(self) -> None: self._eof = True waiter = self._waiter @@ -525,7 +558,7 @@ self._waiter = None set_result(waiter, False) - async def read(self): + async def read(self) -> _T: if not self._buffer and not self._eof: assert not self._waiter self._waiter = self._loop.create_future() @@ -545,28 +578,30 @@ else: raise EofStream - def __aiter__(self): + def __aiter__(self) -> AsyncStreamIterator[_T]: return AsyncStreamIterator(self.read) -class FlowControlDataQueue(DataQueue): +class FlowControlDataQueue(DataQueue[_T]): """FlowControlDataQueue resumes and pauses an underlying stream. It is a destination for parsed data.""" - def __init__(self, protocol, *, limit=DEFAULT_LIMIT, loop=None): + def __init__(self, protocol: BaseProtocol, *, + limit: int=DEFAULT_LIMIT, + loop: asyncio.AbstractEventLoop) -> None: super().__init__(loop=loop) self._protocol = protocol self._limit = limit * 2 - def feed_data(self, data, size): + 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): + async def read(self) -> _T: try: return await super().read() finally: diff -Nru python-aiohttp-3.1.3/aiohttp/tcp_helpers.py python-aiohttp-3.5.1/aiohttp/tcp_helpers.py --- python-aiohttp-3.1.3/aiohttp/tcp_helpers.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/tcp_helpers.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,31 +1,34 @@ """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', 'tcp_cork') if hasattr(socket, 'TCP_CORK'): # pragma: no cover - CORK = socket.TCP_CORK + CORK = socket.TCP_CORK # type: Optional[int] elif hasattr(socket, 'TCP_NOPUSH'): # pragma: no cover - CORK = socket.TCP_NOPUSH + CORK = socket.TCP_NOPUSH # type: ignore else: # pragma: no cover CORK = None if hasattr(socket, 'SO_KEEPALIVE'): - def tcp_keepalive(transport): + 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): # pragma: no cover + def tcp_keepalive( + transport: asyncio.Transport) -> None: # pragma: no cover pass -def tcp_nodelay(transport, value): +def tcp_nodelay(transport: asyncio.Transport, value: bool) -> None: sock = transport.get_extra_info('socket') if sock is None: @@ -42,7 +45,7 @@ socket.IPPROTO_TCP, socket.TCP_NODELAY, value) -def tcp_cork(transport, value): +def tcp_cork(transport: asyncio.Transport, value: bool) -> None: sock = transport.get_extra_info('socket') if CORK is None: diff -Nru python-aiohttp-3.1.3/aiohttp/test_utils.py python-aiohttp-3.5.1/aiohttp/test_utils.py --- python-aiohttp-3.1.3/aiohttp/test_utils.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/test_utils.py 2018-12-24 20:58:54.000000000 +0000 @@ -8,23 +8,47 @@ import sys import unittest from abc import ABC, abstractmethod +from types import TracebackType +from typing import (TYPE_CHECKING, Any, Callable, Iterator, List, # noqa + Optional, Type, Union) from unittest import mock -from multidict import CIMultiDict +from multidict import CIMultiDict, CIMultiDictProxy from yarl import URL import aiohttp -from aiohttp.client import _RequestContextManager, _WSRequestContextManager +from aiohttp.client import (ClientResponse, _RequestContextManager, + _WSRequestContextManager) from . import ClientSession, hdrs +from .abc import AbstractCookieJar +from .client_reqrep import ClientResponse # noqa +from .client_ws import ClientWebSocketResponse # noqa from .helpers import sentinel from .http import HttpVersion, RawRequestMessage from .signals import Signal -from .web import (AppRunner, Request, Server, ServerRunner, TCPSite, - UrlMappingMatchInfo) +from .web import (Application, AppRunner, BaseRunner, Request, Server, + ServerRunner, SockSite, UrlMappingMatchInfo) +from .web_protocol import _RequestHandler -def unused_port(): +if TYPE_CHECKING: # pragma: no cover + from ssl import SSLContext +else: + SSLContext = None + + +def get_unused_port_socket(host: str) -> socket.socket: + return get_port_socket(host, 0) + + +def get_port_socket(host: str, port: int) -> socket.socket: + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + 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)) @@ -32,19 +56,26 @@ class BaseTestServer(ABC): - def __init__(self, *, scheme=sentinel, loop=None, - host='127.0.0.1', port=None, skip_url_asserts=False, - **kwargs): + 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, + **kwargs: Any) -> None: self._loop = loop - self.runner = None - self._root = None + 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 - async def start_server(self, loop=None, **kwargs): + async def start_server(self, + loop: Optional[asyncio.AbstractEventLoop]=None, + **kwargs: Any) -> None: if self.runner: return self._loop = loop @@ -52,10 +83,16 @@ self.runner = await self._make_runner(**kwargs) await self.runner.setup() if not self.port: - self.port = unused_port() - site = TCPSite(self.runner, host=self.host, port=self.port, - ssl_context=self._ssl) + self.port = 0 + _sock = get_port_socket(self.host, self.port) + 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' @@ -67,10 +104,11 @@ self.port)) @abstractmethod # pragma: no cover - async def _make_runner(self, **kwargs): + async def _make_runner(self, **kwargs: Any) -> BaseRunner: pass - def make_url(self, path): + 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() @@ -79,20 +117,23 @@ return URL(str(self._root) + path) @property - def started(self): + def started(self) -> bool: return self.runner is not None @property - def closed(self): + def closed(self) -> bool: return self._closed @property - def handler(self): + def handler(self) -> Server: # for backward compatibility # web.Server instance - return self.runner.server + runner = self.runner + assert runner is not None + assert runner.server is not None + return runner.server - async def close(self): + async def close(self) -> None: """Close all fixtures created by the test client. After that point, the TestClient is no longer usable. @@ -105,45 +146,60 @@ """ 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): + def __enter__(self) -> None: raise TypeError("Use async with instead") - def __exit__(self, exc_type, exc_value, traceback): + 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): + async def __aenter__(self) -> 'BaseTestServer': await self.start_server(loop=self._loop) return self - async def __aexit__(self, exc_type, exc_value, traceback): + 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, *, - scheme=sentinel, host='127.0.0.1', port=None, **kwargs): + 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): + async def _make_runner(self, **kwargs: Any) -> BaseRunner: return AppRunner(self.app, **kwargs) class RawTestServer(BaseTestServer): - def __init__(self, handler, *, - scheme=sentinel, host='127.0.0.1', port=None, **kwargs): + 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=True, **kwargs): + async def _make_runner(self, + debug: bool=True, + **kwargs: Any) -> ServerRunner: srv = Server( self._handler, loop=self._loop, debug=True, **kwargs) return ServerRunner(srv, debug=debug, **kwargs) @@ -157,9 +213,12 @@ """ - def __init__(self, server, *, cookie_jar=None, loop=None, **kwargs): + 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 web.Application TestServer " + raise TypeError("server must be TestServer " "instance, found type: %r" % type(server)) self._server = server self._loop = loop @@ -169,26 +228,30 @@ cookie_jar=cookie_jar, **kwargs) self._closed = False - self._responses = [] - self._websockets = [] + self._responses = [] # type: List[ClientResponse] + self._websockets = [] # type: List[ClientWebSocketResponse] - async def start_server(self): + async def start_server(self) -> None: await self._server.start_server(loop=self._loop) @property - def host(self): + def host(self) -> str: return self._server.host @property - def port(self): + def port(self) -> Optional[int]: return self._server.port @property - def server(self): + def server(self) -> BaseTestServer: return self._server @property - def session(self): + def app(self) -> Application: + return getattr(self._server, "app", None) + + @property + def session(self) -> ClientSession: """An internal aiohttp.ClientSession. Unlike the methods on the TestClient, client session requests @@ -198,83 +261,85 @@ """ return self._session - def make_url(self, path): + def make_url(self, path: str) -> URL: return self._server.make_url(path) - async def request(self, method, path, *args, **kwargs): + async def request(self, method: str, path: str, + **kwargs: Any) -> ClientResponse: """Routes a request to tested http server. - The interface is identical to asyncio.ClientSession.request, + The interface is identical to aiohttp.ClientSession.request, except the loop kwarg is overridden by the instance used by the test server. """ resp = await self._session.request( - method, self.make_url(path), *args, **kwargs + method, self.make_url(path), **kwargs ) # save it to close later self._responses.append(resp) return resp - def get(self, path, *args, **kwargs): + def get(self, path: str, **kwargs: Any) -> _RequestContextManager: """Perform an HTTP GET request.""" return _RequestContextManager( - self.request(hdrs.METH_GET, path, *args, **kwargs) + self.request(hdrs.METH_GET, path, **kwargs) ) - def post(self, path, *args, **kwargs): + def post(self, path: str, **kwargs: Any) -> _RequestContextManager: """Perform an HTTP POST request.""" return _RequestContextManager( - self.request(hdrs.METH_POST, path, *args, **kwargs) + self.request(hdrs.METH_POST, path, **kwargs) ) - def options(self, path, *args, **kwargs): + def options(self, path: str, **kwargs: Any) -> _RequestContextManager: """Perform an HTTP OPTIONS request.""" return _RequestContextManager( - self.request(hdrs.METH_OPTIONS, path, *args, **kwargs) + self.request(hdrs.METH_OPTIONS, path, **kwargs) ) - def head(self, path, *args, **kwargs): + def head(self, path: str, **kwargs: Any) -> _RequestContextManager: """Perform an HTTP HEAD request.""" return _RequestContextManager( - self.request(hdrs.METH_HEAD, path, *args, **kwargs) + self.request(hdrs.METH_HEAD, path, **kwargs) ) - def put(self, path, *args, **kwargs): + def put(self, path: str, **kwargs: Any) -> _RequestContextManager: """Perform an HTTP PUT request.""" return _RequestContextManager( - self.request(hdrs.METH_PUT, path, *args, **kwargs) + self.request(hdrs.METH_PUT, path, **kwargs) ) - def patch(self, path, *args, **kwargs): + def patch(self, path: str, **kwargs: Any) -> _RequestContextManager: """Perform an HTTP PATCH request.""" return _RequestContextManager( - self.request(hdrs.METH_PATCH, path, *args, **kwargs) + self.request(hdrs.METH_PATCH, path, **kwargs) ) - def delete(self, path, *args, **kwargs): + def delete(self, path: str, **kwargs: Any) -> _RequestContextManager: """Perform an HTTP PATCH request.""" return _RequestContextManager( - self.request(hdrs.METH_DELETE, path, *args, **kwargs) + self.request(hdrs.METH_DELETE, path, **kwargs) ) - def ws_connect(self, path, *args, **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, *args, **kwargs) + self._ws_connect(path, **kwargs) ) - async def _ws_connect(self, path, *args, **kwargs): + async def _ws_connect(self, path: str, + **kwargs: Any) -> ClientWebSocketResponse: ws = await self._session.ws_connect( - self.make_url(path), *args, **kwargs) + self.make_url(path), **kwargs) self._websockets.append(ws) return ws - async def close(self): + async def close(self) -> None: """Close all fixtures created by the test client. After that point, the TestClient is no longer usable. @@ -295,18 +360,24 @@ await self._server.close() self._closed = True - def __enter__(self): + def __enter__(self) -> None: raise TypeError("Use async with instead") - def __exit__(self, exc_type, exc_value, traceback): + 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): + async def __aenter__(self) -> 'TestClient': await self.start_server() return self - async def __aexit__(self, exc_type, exc_value, traceback): + async def __aexit__(self, + exc_type: Optional[Type[BaseException]], + exc: Optional[BaseException], + tb: Optional[TracebackType]) -> None: await self.close() @@ -326,7 +397,7 @@ execute function on the test client using asynchronous methods. """ - async def get_application(self): + async def get_application(self) -> Application: """ This method should be overridden to return the aiohttp.web.Application @@ -335,7 +406,7 @@ """ return self.get_app() - def get_app(self): + def get_app(self) -> Application: """Obsolete method used to constructing web application. Use .get_application() coroutine instead @@ -343,7 +414,7 @@ """ raise RuntimeError("Did you forget to define get_application()?") - def setUp(self): + def setUp(self) -> None: self.loop = setup_test_loop() self.app = self.loop.run_until_complete(self.get_application()) @@ -355,27 +426,27 @@ self.loop.run_until_complete(self.setUpAsync()) - async def setUpAsync(self): + async def setUpAsync(self) -> None: pass - def tearDown(self): + def tearDown(self) -> None: self.loop.run_until_complete(self.tearDownAsync()) self.loop.run_until_complete(self.client.close()) teardown_test_loop(self.loop) - async def tearDownAsync(self): + async def tearDownAsync(self) -> None: pass - async def get_server(self, app): + async def get_server(self, app: Application) -> TestServer: """Return a TestServer instance.""" return TestServer(app, loop=self.loop) - async def get_client(self, server): + async def get_client(self, server: TestServer) -> TestClient: """Return a TestClient instance.""" return TestClient(server, loop=self.loop) -def unittest_run_loop(func, *args, **kwargs): +def unittest_run_loop(func: Any, *args: Any, **kwargs: Any) -> Any: """A decorator dedicated to use with asynchronous methods of an AioHTTPTestCase. @@ -384,15 +455,19 @@ """ @functools.wraps(func, *args, **kwargs) - def new_func(self, *inner_args, **inner_kwargs): + def new_func(self: Any, *inner_args: Any, **inner_kwargs: Any) -> Any: return self.loop.run_until_complete( func(self, *inner_args, **inner_kwargs)) return new_func +_LOOP_FACTORY = Callable[[], asyncio.AbstractEventLoop] + + @contextlib.contextmanager -def loop_context(loop_factory=asyncio.new_event_loop, fast=False): +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. @@ -402,7 +477,9 @@ teardown_test_loop(loop, fast=fast) -def setup_test_loop(loop_factory=asyncio.new_event_loop): +def setup_test_loop( + loop_factory: _LOOP_FACTORY=asyncio.new_event_loop +) -> asyncio.AbstractEventLoop: """Create and return an asyncio.BaseEventLoop instance. @@ -410,17 +487,24 @@ 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": + if sys.platform != "win32" and not skip_watcher: policy = asyncio.get_event_loop_policy() - watcher = asyncio.SafeChildWatcher() + watcher = asyncio.SafeChildWatcher() # type: ignore watcher.attach_loop(loop) with contextlib.suppress(NotImplementedError): policy.set_child_watcher(watcher) return loop -def teardown_test_loop(loop, fast=False): +def teardown_test_loop(loop: asyncio.AbstractEventLoop, + fast: bool=False) -> None: """Teardown and cleanup an event_loop created by setup_test_loop. @@ -437,18 +521,28 @@ asyncio.set_event_loop(None) -def _create_app_mock(): - app = mock.Mock() +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=None): +def _create_transport(sslcontext: Optional[SSLContext]=None) -> mock.Mock: transport = mock.Mock() - def get_extra_info(key): + def get_extra_info(key: str) -> Optional[SSLContext]: if key == 'sslcontext': return sslcontext else: @@ -458,17 +552,19 @@ return transport -def make_mocked_request(method, path, headers=None, *, - match_info=sentinel, - version=HttpVersion(1, 1), closing=False, - app=None, - writer=sentinel, - protocol=sentinel, - transport=sentinel, - payload=sentinel, - sslcontext=None, - client_max_size=1024**2, - loop=...): +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=...) -> Any: """Creates mocked web.Request testing purposes. Useful in unit tests, when spinning full web server is overkill or @@ -485,11 +581,11 @@ closing = True if headers: - headers = CIMultiDict(headers) + headers = CIMultiDictProxy(CIMultiDict(headers)) raw_hdrs = tuple( (k.encode('utf-8'), v.encode('utf-8')) for k, v in headers.items()) else: - headers = CIMultiDict() + headers = CIMultiDictProxy(CIMultiDict()) raw_hdrs = () chunked = 'chunked' in headers.get(hdrs.TRANSFER_ENCODING, '').lower() @@ -500,12 +596,13 @@ if app is None: app = _create_app_mock() - if protocol is sentinel: - protocol = mock.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) @@ -532,10 +629,11 @@ return req -def make_mocked_coro(return_value=sentinel, raise_exception=sentinel): +def make_mocked_coro(return_value: Any=sentinel, + raise_exception: Any=sentinel) -> Any: """Creates a coroutine mock.""" @asyncio.coroutine - def mock_coro(*args, **kwargs): + def mock_coro(*args: Any, **kwargs: Any) -> Any: if raise_exception is not sentinel: raise raise_exception return return_value diff -Nru python-aiohttp-3.1.3/aiohttp/tracing.py python-aiohttp-3.5.1/aiohttp/tracing.py --- python-aiohttp-3.1.3/aiohttp/tracing.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/tracing.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,13 +1,22 @@ from types import SimpleNamespace +from typing import TYPE_CHECKING, Awaitable, Callable, Type import attr -from multidict import CIMultiDict +from multidict import CIMultiDict # noqa from yarl import URL from .client_reqrep import ClientResponse from .signals import Signal +if TYPE_CHECKING: # pragma: no cover + from .client import ClientSession # noqa + + _Signal = Signal[Callable[['TraceConfig'], Awaitable[None]]] +else: + _Signal = Signal + + __all__ = ( 'TraceConfig', 'TraceRequestStartParams', 'TraceRequestEndParams', 'TraceRequestExceptionParams', 'TraceConnectionQueuedStartParams', @@ -24,31 +33,37 @@ """First-class used to trace requests launched via ClientSession objects.""" - def __init__(self, trace_config_ctx_factory=SimpleNamespace): - self._on_request_start = Signal(self) - self._on_request_chunk_sent = Signal(self) - self._on_response_chunk_received = Signal(self) - self._on_request_end = Signal(self) - self._on_request_exception = Signal(self) - self._on_request_redirect = Signal(self) - self._on_connection_queued_start = Signal(self) - self._on_connection_queued_end = Signal(self) - self._on_connection_create_start = Signal(self) - self._on_connection_create_end = Signal(self) - self._on_connection_reuseconn = Signal(self) - self._on_dns_resolvehost_start = Signal(self) - self._on_dns_resolvehost_end = Signal(self) - self._on_dns_cache_hit = Signal(self) - self._on_dns_cache_miss = Signal(self) - - self._trace_config_ctx_factory = trace_config_ctx_factory - - def trace_config_ctx(self, trace_request_ctx=None): + def __init__( + self, + trace_config_ctx_factory: Type[SimpleNamespace]=SimpleNamespace + ) -> None: + self._on_request_start = Signal(self) # type: _Signal + self._on_request_chunk_sent = Signal(self) # type: _Signal + self._on_response_chunk_received = Signal(self) # type: _Signal + self._on_request_end = Signal(self) # type: _Signal + self._on_request_exception = Signal(self) # type: _Signal + self._on_request_redirect = Signal(self) # type: _Signal + self._on_connection_queued_start = Signal(self) # type: _Signal + self._on_connection_queued_end = Signal(self) # type: _Signal + self._on_connection_create_start = Signal(self) # type: _Signal + self._on_connection_create_end = Signal(self) # type: _Signal + self._on_connection_reuseconn = Signal(self) # type: _Signal + self._on_dns_resolvehost_start = Signal(self) # type: _Signal + self._on_dns_resolvehost_end = Signal(self) # type: _Signal + self._on_dns_cache_hit = Signal(self) # type: _Signal + self._on_dns_cache_miss = Signal(self) # type: _Signal + + self._trace_config_ctx_factory = trace_config_ctx_factory # type: Type[SimpleNamespace] # noqa + + def trace_config_ctx( + self, + trace_request_ctx: SimpleNamespace=None + ) -> SimpleNamespace: # noqa """ Return a new trace_config_ctx instance """ return self._trace_config_ctx_factory( trace_request_ctx=trace_request_ctx) - def freeze(self): + def freeze(self) -> None: self._on_request_start.freeze() self._on_request_chunk_sent.freeze() self._on_response_chunk_received.freeze() @@ -66,63 +81,63 @@ self._on_dns_cache_miss.freeze() @property - def on_request_start(self): + def on_request_start(self) -> _Signal: return self._on_request_start @property - def on_request_chunk_sent(self): + def on_request_chunk_sent(self) -> _Signal: return self._on_request_chunk_sent @property - def on_response_chunk_received(self): + def on_response_chunk_received(self) -> _Signal: return self._on_response_chunk_received @property - def on_request_end(self): + def on_request_end(self) -> _Signal: return self._on_request_end @property - def on_request_exception(self): + def on_request_exception(self) -> _Signal: return self._on_request_exception @property - def on_request_redirect(self): + def on_request_redirect(self) -> _Signal: return self._on_request_redirect @property - def on_connection_queued_start(self): + def on_connection_queued_start(self) -> _Signal: return self._on_connection_queued_start @property - def on_connection_queued_end(self): + def on_connection_queued_end(self) -> _Signal: return self._on_connection_queued_end @property - def on_connection_create_start(self): + def on_connection_create_start(self) -> _Signal: return self._on_connection_create_start @property - def on_connection_create_end(self): + def on_connection_create_end(self) -> _Signal: return self._on_connection_create_end @property - def on_connection_reuseconn(self): + def on_connection_reuseconn(self) -> _Signal: return self._on_connection_reuseconn @property - def on_dns_resolvehost_start(self): + def on_dns_resolvehost_start(self) -> _Signal: return self._on_dns_resolvehost_start @property - def on_dns_resolvehost_end(self): + def on_dns_resolvehost_end(self) -> _Signal: return self._on_dns_resolvehost_end @property - def on_dns_cache_hit(self): + def on_dns_cache_hit(self) -> _Signal: return self._on_dns_cache_hit @property - def on_dns_cache_miss(self): + def on_dns_cache_miss(self) -> _Signal: return self._on_dns_cache_miss @@ -131,7 +146,7 @@ """ Parameters sent by the `on_request_start` signal""" method = attr.ib(type=str) url = attr.ib(type=URL) - headers = attr.ib(type=CIMultiDict) + headers = attr.ib(type='CIMultiDict[str]') @attr.s(frozen=True, slots=True) @@ -151,7 +166,7 @@ """ Parameters sent by the `on_request_end` signal""" method = attr.ib(type=str) url = attr.ib(type=URL) - headers = attr.ib(type=CIMultiDict) + headers = attr.ib(type='CIMultiDict[str]') response = attr.ib(type=ClientResponse) @@ -160,8 +175,8 @@ """ Parameters sent by the `on_request_exception` signal""" method = attr.ib(type=str) url = attr.ib(type=URL) - headers = attr.ib(type=CIMultiDict) - exception = attr.ib(type=Exception) + headers = attr.ib(type='CIMultiDict[str]') + exception = attr.ib(type=BaseException) @attr.s(frozen=True, slots=True) @@ -169,7 +184,7 @@ """ Parameters sent by the `on_request_redirect` signal""" method = attr.ib(type=str) url = attr.ib(type=URL) - headers = attr.ib(type=CIMultiDict) + headers = attr.ib(type='CIMultiDict[str]') response = attr.ib(type=ClientResponse) @@ -226,110 +241,128 @@ """ Internal class used to keep together the main dependencies used at the moment of send a signal.""" - def __init__(self, session, trace_config, trace_config_ctx): + 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, url, headers): + 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, chunk): + async def send_request_chunk_sent(self, chunk: bytes) -> None: return await self._trace_config.on_request_chunk_sent.send( self._session, self._trace_config_ctx, TraceRequestChunkSentParams(chunk) ) - async def send_response_chunk_received(self, chunk): + async def send_response_chunk_received(self, chunk: bytes) -> None: return await self._trace_config.on_response_chunk_received.send( self._session, self._trace_config_ctx, TraceResponseChunkReceivedParams(chunk) ) - async def send_request_end(self, method, url, headers, response): + 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, url, headers, exception): + 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, url, headers, response): + 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): + 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): + 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): + 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): + 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): + 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): + 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): + 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): + 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): + 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, diff -Nru python-aiohttp-3.1.3/aiohttp/typedefs.py python-aiohttp-3.5.1/aiohttp/typedefs.py --- python-aiohttp-3.1.3/aiohttp/typedefs.py 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/typedefs.py 2018-12-24 20:58:54.000000000 +0000 @@ -0,0 +1,40 @@ +import json +import os # noqa +import pathlib # noqa +import sys +from typing import (TYPE_CHECKING, Any, Callable, Iterable, Mapping, Tuple, + Union) + +from multidict import CIMultiDict, CIMultiDictProxy, MultiDict, MultiDictProxy +from yarl import URL + + +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 # noqa +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[str, str], _CIMultiDict, _CIMultiDictProxy] +RawHeaders = Tuple[Tuple[bytes, bytes], ...] +StrOrURL = Union[str, URL] +LooseCookies = Union[Iterable[Tuple[str, 'BaseCookie[str]']], + Mapping[str, 'BaseCookie[str]'], 'BaseCookie[str]'] + + +if sys.version_info >= (3, 6): + PathLike = Union[str, 'os.PathLike[str]'] +else: + PathLike = Union[str, pathlib.PurePath] diff -Nru python-aiohttp-3.1.3/aiohttp/web_app.py python-aiohttp-3.5.1/aiohttp/web_app.py --- python-aiohttp-3.1.3/aiohttp/web_app.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/web_app.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,78 +1,126 @@ import asyncio +import logging import warnings -from collections import MutableMapping from functools import partial +from typing import (TYPE_CHECKING, Any, AsyncIterator, Awaitable, # noqa + Callable, Dict, Iterable, Iterator, List, Mapping, + MutableMapping, Optional, Sequence, Tuple, Type, Union, + cast) from . import hdrs -from .abc import AbstractAccessLogger, AbstractMatchInfo, AbstractRouter +from .abc import (AbstractAccessLogger, AbstractMatchInfo, AbstractRouter, + AbstractStreamWriter) from .frozenlist import FrozenList -from .helpers import DEBUG, AccessLogger +from .helpers import DEBUG +from .http_parser import RawRequestMessage from .log import web_logger from .signals import Signal +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 PrefixedSubAppResource, UrlDispatcher +from .web_urldispatcher import (AbstractResource, Domain, MaskDomain, + MatchedSubAppResource, PrefixedSubAppResource, + UrlDispatcher) __all__ = ('Application', 'CleanupError') -class Application(MutableMapping): +if TYPE_CHECKING: # pragma: no cover + _AppSignal = Signal[Callable[['Application'], Awaitable[None]]] + _RespPrepareSignal = Signal[Callable[[Request, StreamResponse], + Awaitable[None]]] + _Handler = Callable[[Request], Awaitable[StreamResponse]] + _Middleware = Union[Callable[[Request, _Handler], + Awaitable[StreamResponse]], + Callable[['Application', _Handler], # old-style + Awaitable[_Handler]]] + _Middlewares = FrozenList[_Middleware] + _MiddlewaresHandlers = Optional[Sequence[Tuple[_Middleware, bool]]] + _Subapps = List['Application'] +else: + # No type checker mode, skip types + _AppSignal = Signal + _RespPrepareSignal = Signal + _Handler = Callable + _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', '_subapps', + '_state', '_frozen', '_pre_frozen', '_subapps', '_on_response_prepare', '_on_startup', '_on_shutdown', '_on_cleanup', '_client_max_size', '_cleanup_ctx']) def __init__(self, *, - logger=web_logger, - router=None, - middlewares=(), - handler_args=None, - client_max_size=1024**2, - loop=None, - debug=...): + logger: logging.Logger=web_logger, + router: Optional[UrlDispatcher]=None, + middlewares: Sequence[_Middleware]=(), + handler_args: 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 + self._router = router # type: UrlDispatcher self._loop = loop self._handler_args = handler_args self.logger = logger - self._middlewares = FrozenList(middlewares) - self._middlewares_handlers = None # initialized on freezing - self._run_middlewares = None # initialized on freezing - self._state = {} + 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._subapps = [] + self._pre_frozen = False + self._subapps = [] # type: _Subapps - self._on_response_prepare = Signal(self) - self._on_startup = Signal(self) - self._on_shutdown = Signal(self) - self._on_cleanup = Signal(self) + 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): + def __init_subclass__(cls: Type['Application']) -> None: warnings.warn("Inheritance class {} from web.Application " "is discouraged".format(cls.__name__), DeprecationWarning, stacklevel=2) - if DEBUG: - def __setattr__(self, name, val): + 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), @@ -82,39 +130,45 @@ # MutableMapping API - def __eq__(self, other): + def __eq__(self, other: object) -> bool: return self is other - def __getitem__(self, key): + def __getitem__(self, key: str) -> Any: return self._state[key] - def _check_frozen(self): + 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, value): + def __setitem__(self, key: str, value: Any) -> None: self._check_frozen() self._state[key] = value - def __delitem__(self, key): + def __delitem__(self, key: str) -> None: self._check_frozen() del self._state[key] - def __len__(self): + def __len__(self) -> int: return len(self._state) - def __iter__(self): + def __iter__(self) -> Iterator[str]: return iter(self._state) ######## @property - def loop(self): - return self._loop + 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): + 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: @@ -132,14 +186,14 @@ subapp._set_loop(loop) @property - def frozen(self): - return self._frozen + def pre_frozen(self) -> bool: + return self._pre_frozen - def freeze(self): - if self._frozen: + def pre_freeze(self) -> None: + if self._pre_frozen: return - self._frozen = True + self._pre_frozen = True self._middlewares.freeze() self._router.freeze() self._on_response_prepare.freeze() @@ -157,20 +211,36 @@ 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() - self._run_middlewares =\ - self._run_middlewares or subapp._run_middlewares @property - def debug(self): + def debug(self) -> bool: + warnings.warn("debug property is deprecated", + DeprecationWarning, + stacklevel=2) return self._debug - def _reg_subapp_signals(self, subapp): + def _reg_subapp_signals(self, subapp: 'Application') -> None: - def reg_handler(signame): + def reg_handler(signame: str) -> None: subsig = getattr(subapp, signame) - async def handler(app): + async def handler(app: 'Application') -> None: await subsig.send(subapp) appsig = getattr(self, signame) appsig.append(handler) @@ -179,61 +249,80 @@ reg_handler('on_shutdown') reg_handler('on_cleanup') - def add_subapp(self, prefix, subapp): + 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") - if prefix.endswith('/'): - prefix = prefix[:-1] - if prefix in ('', '/'): - raise ValueError("Prefix cannot be empty") - - resource = PrefixedSubAppResource(prefix, subapp) + resource = resource_factory() self.router.register_resource(resource) self._reg_subapp_signals(subapp) self._subapps.append(subapp) - subapp.freeze() + subapp.pre_freeze() if self._loop is not None: subapp._set_loop(self._loop) return resource - def add_routes(self, routes): + 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]) -> None: self.router.add_routes(routes) @property - def on_response_prepare(self): + def on_response_prepare(self) -> _RespPrepareSignal: return self._on_response_prepare @property - def on_startup(self): + def on_startup(self) -> _AppSignal: return self._on_startup @property - def on_shutdown(self): + def on_shutdown(self) -> _AppSignal: return self._on_shutdown @property - def on_cleanup(self): + def on_cleanup(self) -> _AppSignal: return self._on_cleanup @property - def cleanup_ctx(self): + def cleanup_ctx(self) -> 'CleanupContext': return self._cleanup_ctx @property - def router(self): + def router(self) -> UrlDispatcher: return self._router @property - def middlewares(self): + def middlewares(self) -> _Middlewares: return self._middlewares - def make_handler(self, *, - loop=None, - access_log_class=AccessLogger, - **kwargs): + 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( @@ -244,44 +333,64 @@ self._set_loop(loop) self.freeze() - kwargs['debug'] = self.debug + 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, request_factory=self._make_request, - access_log_class=access_log_class, - loop=self.loop, **kwargs) + return Server(self._handle, # type: ignore + 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: - async def startup(self): + 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): + async def shutdown(self) -> None: """Causes on_shutdown signal Should be called before cleanup() """ await self.on_shutdown.send(self) - async def cleanup(self): + async def cleanup(self) -> None: """Causes on_cleanup signal Should be called after shutdown() """ await self.on_cleanup.send(self) - def _make_request(self, message, payload, protocol, writer, task, - _cls=Request): + 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): + def _prepare_middleware(self) -> Iterator[Tuple[_Middleware, bool]]: for m in reversed(self._middlewares): if getattr(m, '__middleware_version__', None) == 1: yield m, True @@ -293,16 +402,20 @@ yield _fix_request_current_app(self), True - async def _handle(self, request): + async def _handle(self, request: Request) -> StreamResponse: + loop = asyncio.get_event_loop() + debug = loop.get_debug() match_info = await self._router.resolve(request) - assert isinstance(match_info, AbstractMatchInfo), match_info + 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) - if __debug__: - match_info.freeze() + match_info.freeze() resp = None - request._match_info = match_info + request._match_info = match_info # type: ignore expect = request.headers.get(hdrs.EXPECT) if expect: resp = await match_info.expect_handler(request) @@ -313,50 +426,50 @@ if self._run_middlewares: for app in match_info.apps[::-1]: - for m, new_style in app._middlewares_handlers: + for m, new_style in app._middlewares_handlers: # type: ignore # noqa if new_style: handler = partial(m, handler=handler) else: - handler = await m(app, handler) + handler = await m(app, handler) # type: ignore resp = await handler(request) - assert isinstance(resp, StreamResponse), \ - ("Handler {!r} should return response instance, " - "got {!r} [middlewares {!r}]").format( - match_info.handler, type(resp), - [middleware - for app in match_info.apps - for middleware in app.middlewares]) return resp - def __call__(self): + def __call__(self) -> 'Application': """gunicorn compatibility""" return self - def __repr__(self): + def __repr__(self) -> str: return "".format(id(self)) class CleanupError(RuntimeError): @property - def exceptions(self): + def exceptions(self) -> List[BaseException]: return self.args[1] -class CleanupContext(FrozenList): +if TYPE_CHECKING: # pragma: no cover + _CleanupContextBase = FrozenList[Callable[[Application], + AsyncIterator[None]]] +else: + _CleanupContextBase = FrozenList + + +class CleanupContext(_CleanupContextBase): - def __init__(self): + def __init__(self) -> None: super().__init__() - self._exits = [] + self._exits = [] # type: List[AsyncIterator[None]] - async def _on_startup(self, app): + 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): + async def _on_cleanup(self, app: Application) -> None: errors = [] for it in reversed(self._exits): try: diff -Nru python-aiohttp-3.1.3/aiohttp/web_exceptions.py python-aiohttp-3.5.1/aiohttp/web_exceptions.py --- python-aiohttp-3.1.3/aiohttp/web_exceptions.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/web_exceptions.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,3 +1,7 @@ +import warnings +from typing import Any, Dict, Iterable, List, Optional, Set # noqa + +from .typedefs import LooseHeaders, StrOrURL from .web_response import Response @@ -71,11 +75,21 @@ # You should set in subclasses: # status = 200 - status_code = None + status_code = -1 empty_body = False - def __init__(self, *, headers=None, reason=None, - body=None, text=None, content_type=None): + __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) @@ -83,6 +97,9 @@ if self.body is None and not self.empty_body: self.text = "{}: {}".format(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.""" @@ -133,8 +150,14 @@ class _HTTPMove(HTTPRedirection): - def __init__(self, location, *, headers=None, reason=None, - body=None, text=None, content_type=None): + 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, @@ -212,13 +235,20 @@ class HTTPMethodNotAllowed(HTTPClientError): status_code = 405 - def __init__(self, method, allowed_methods, *, headers=None, reason=None, - body=None, text=None, content_type=None): + 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 = allowed_methods + self.allowed_methods = set(allowed_methods) # type: Set[str] self.method = method.upper() @@ -253,6 +283,17 @@ 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 @@ -301,8 +342,14 @@ class HTTPUnavailableForLegalReasons(HTTPClientError): status_code = 451 - def __init__(self, link, *, headers=None, reason=None, - body=None, text=None, content_type=None): + 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 diff -Nru python-aiohttp-3.1.3/aiohttp/web_fileresponse.py python-aiohttp-3.5.1/aiohttp/web_fileresponse.py --- python-aiohttp-3.1.3/aiohttp/web_fileresponse.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/web_fileresponse.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,11 +1,18 @@ +import asyncio import mimetypes import os import pathlib +from functools import partial +from typing import (IO, TYPE_CHECKING, Any, Awaitable, Callable, List, # noqa + Optional, Union, cast) from . import hdrs +from .abc import AbstractStreamWriter +from .base_protocol import BaseProtocol from .helpers import set_exception, set_result from .http_writer import StreamWriter from .log import server_logger +from .typedefs import LooseHeaders from .web_exceptions import (HTTPNotModified, HTTPOk, HTTPPartialContent, HTTPPreconditionFailed, HTTPRequestRangeNotSatisfiable) @@ -14,78 +21,104 @@ __all__ = ('FileResponse',) +if TYPE_CHECKING: # pragma: no cover + from .web_request import BaseRequest # noqa + + +_T_OnChunkSent = Optional[Callable[[bytes], Awaitable[None]]] + NOSENDFILE = bool(os.environ.get("AIOHTTP_NOSENDFILE")) class SendfileStreamWriter(StreamWriter): - def __init__(self, *args, **kwargs): - self._sendfile_buffer = [] - super().__init__(*args, **kwargs) + def __init__(self, + protocol: BaseProtocol, + loop: asyncio.AbstractEventLoop, + fobj: IO[Any], + count: int, + on_chunk_sent: _T_OnChunkSent=None) -> None: + super().__init__(protocol, loop, on_chunk_sent) + self._sendfile_buffer = [] # type: List[bytes] + self._fobj = fobj + self._count = count + self._offset = fobj.tell() + self._in_fd = fobj.fileno() - def _write(self, chunk): + def _write(self, chunk: bytes) -> None: # we overwrite StreamWriter._write, so nothing can be appended to # _buffer, and nothing is written to the transport directly by the # parent class self.output_size += len(chunk) self._sendfile_buffer.append(chunk) - def _sendfile_cb(self, fut, out_fd, in_fd, - offset, count, loop, registered): - if registered: - loop.remove_writer(out_fd) + def _sendfile_cb(self, fut: 'asyncio.Future[None]', out_fd: int) -> None: if fut.cancelled(): return + try: + if self._do_sendfile(out_fd): + set_result(fut, None) + except Exception as exc: + set_exception(fut, exc) + def _do_sendfile(self, out_fd: int) -> bool: try: - n = os.sendfile(out_fd, in_fd, offset, count) - if n == 0: # EOF reached - n = count + n = os.sendfile(out_fd, + self._in_fd, + self._offset, + self._count) + if n == 0: # in_fd EOF reached + n = self._count except (BlockingIOError, InterruptedError): n = 0 - except Exception as exc: - set_exception(fut, exc) - return + self.output_size += n + self._offset += n + self._count -= n + assert self._count >= 0 + return self._count == 0 - if n < count: - loop.add_writer(out_fd, self._sendfile_cb, fut, out_fd, in_fd, - offset + n, count - n, loop, True) - else: - set_result(fut, None) + def _done_fut(self, out_fd: int, fut: 'asyncio.Future[None]') -> None: + self.loop.remove_writer(out_fd) - async def sendfile(self, fobj, count): + async def sendfile(self) -> None: + assert self.transport is not None out_socket = self.transport.get_extra_info('socket').dup() out_socket.setblocking(False) out_fd = out_socket.fileno() - in_fd = fobj.fileno() - offset = fobj.tell() loop = self.loop data = b''.join(self._sendfile_buffer) try: await loop.sock_sendall(out_socket, data) - fut = loop.create_future() - self._sendfile_cb(fut, out_fd, in_fd, offset, count, loop, False) - await fut + if not self._do_sendfile(out_fd): + fut = loop.create_future() + fut.add_done_callback(partial(self._done_fut, out_fd)) + loop.add_writer(out_fd, self._sendfile_cb, fut, out_fd) + await fut + except asyncio.CancelledError: + raise except Exception: server_logger.debug('Socket error') self.transport.close() finally: out_socket.close() - self.output_size += count await super().write_eof() - async def write_eof(self, chunk=b''): + async def write_eof(self, chunk: bytes=b'') -> None: pass class FileResponse(StreamResponse): """A response object can be used to send files.""" - def __init__(self, path, chunk_size=256*1024, *args, **kwargs): - super().__init__(*args, **kwargs) + 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) @@ -93,7 +126,9 @@ self._path = path self._chunk_size = chunk_size - async def _sendfile_system(self, request, fobj, count): + async def _sendfile_system(self, request: 'BaseRequest', + fobj: IO[Any], + count: int) -> AbstractStreamWriter: # Write count bytes of fobj to resp using # the os.sendfile system call. # @@ -101,28 +136,33 @@ # https://github.com/KeepSafe/aiohttp/issues/1177 # See https://github.com/KeepSafe/aiohttp/issues/958 for details # - # request should be a aiohttp.web.Request instance. + # request should be an aiohttp.web.Request instance. # fobj should be an open file object. # count should be an integer > 0. transport = request.transport + assert transport is not None if (transport.get_extra_info("sslcontext") or - transport.get_extra_info("socket") is None): + transport.get_extra_info("socket") is None or + self.compression): writer = await self._sendfile_fallback(request, fobj, count) else: writer = SendfileStreamWriter( request.protocol, - transport, - request.loop + request._loop, + fobj, + count ) request._payload_writer = writer await super().prepare(request) - await writer.sendfile(fobj, count) + await writer.sendfile() return writer - async def _sendfile_fallback(self, request, fobj, count): + async def _sendfile_fallback(self, request: 'BaseRequest', + fobj: IO[Any], + count: int) -> AbstractStreamWriter: # Mimic the _sendfile_system() method, but without using the # os.sendfile() system call. This should be used on systems # that don't support the os.sendfile(). @@ -131,12 +171,13 @@ # fobj is transferred in chunks controlled by the # constructor's chunk_size argument. - writer = (await super().prepare(request)) + writer = await super().prepare(request) + assert writer is not None chunk_size = self._chunk_size chunk = fobj.read(chunk_size) - while True: + while chunk: await writer.write(chunk) count = count - chunk_size if count <= 0: @@ -151,7 +192,10 @@ else: # pragma: no cover _sendfile = _sendfile_fallback - async def prepare(self, request): + async def prepare( + self, + request: 'BaseRequest' + ) -> Optional[AbstractStreamWriter]: filepath = self._path gzip = False @@ -262,19 +306,21 @@ self.set_status(status) if should_set_ct: - self.content_type = ct + self.content_type = ct # type: ignore if encoding: self.headers[hdrs.CONTENT_ENCODING] = encoding if gzip: self.headers[hdrs.VARY] = hdrs.ACCEPT_ENCODING - self.last_modified = st.st_mtime + self.last_modified = st.st_mtime # type: ignore 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 {0}-{1}/{2}'.format( - start, start + count - 1, file_size) + real_start, real_start + count - 1, file_size) with filepath.open('rb') as fobj: if start: # be aware that start could be None or int=0 here. diff -Nru python-aiohttp-3.1.3/aiohttp/web_log.py python-aiohttp-3.5.1/aiohttp/web_log.py --- python-aiohttp-3.1.3/aiohttp/web_log.py 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/web_log.py 2018-12-24 20:58:54.000000000 +0000 @@ -0,0 +1,236 @@ +import datetime +import functools +import logging +import os +import re +from collections import namedtuple +from typing import 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 '%s %s HTTP/%s.%s' % (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 + dct = extra.get(k1, {}) + dct[k2] = value # type: ignore + extra[k1] = dct # type: ignore + + self.logger.info(self._log_format % tuple(values), extra=extra) + except Exception: + self.logger.exception("Error in logging") diff -Nru python-aiohttp-3.1.3/aiohttp/web_middlewares.py python-aiohttp-3.5.1/aiohttp/web_middlewares.py --- python-aiohttp-3.1.3/aiohttp/web_middlewares.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/web_middlewares.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,7 +1,10 @@ import re +from typing import TYPE_CHECKING, Awaitable, Callable, Tuple, Type, TypeVar -from aiohttp.web_exceptions import HTTPMovedPermanently -from aiohttp.web_urldispatcher import SystemRoute +from .web_exceptions import HTTPMovedPermanently, _HTTPMove +from .web_request import Request +from .web_response import StreamResponse +from .web_urldispatcher import SystemRoute __all__ = ( @@ -9,49 +12,73 @@ 'normalize_path_middleware', ) +if TYPE_CHECKING: # pragma: no cover + from .web_app import Application # noqa -async def _check_request_resolves(request, path): +_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 + alt_request._match_info = match_info # type: ignore - if not isinstance(match_info.route, SystemRoute): + if match_info.http_exception is None: return True, alt_request return False, request -def middleware(f): - f.__middleware_version__ = 1 +def middleware(f: _Func) -> _Func: + f.__middleware_version__ = 1 # type: ignore return f +_Handler = Callable[[Request], Awaitable[StreamResponse]] +_Middleware = Callable[[Request, _Handler], Awaitable[StreamResponse]] + + def normalize_path_middleware( - *, append_slash=True, merge_slashes=True, - redirect_class=HTTPMovedPermanently): + *, append_slash: bool=True, remove_slash: bool=False, + merge_slashes: bool=True, + redirect_class: Type[_HTTPMove]=HTTPMovedPermanently) -> _Middleware: """ - Middleware that normalizes the path of a request. By normalizing - it means: + Middleware factory which produces a middleware that normalizes + the path of a request. By normalizing it means: - - Add a trailing slash to the path. + - 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 all enable is 1) merge_slashes, 2) append_slash - and 3) both merge_slashes and append_slash. If the path resolves with - at least one of those conditions, it will redirect to the new path. - - If append_slash is True append slash when needed. If a resource is - defined with trailing slash and the request comes without it, it will - append it automatically. + 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, handler): + async def impl(request: Request, handler: _Handler) -> StreamResponse: if isinstance(request.match_info.route, SystemRoute): paths_to_check = [] if '?' in request.raw_path: @@ -65,25 +92,30 @@ 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: resolves, request = await _check_request_resolves( request, path) if resolves: - raise redirect_class(request.path + query) + raise redirect_class(request.raw_path + query) return await handler(request) return impl -def _fix_request_current_app(app): +def _fix_request_current_app(app: 'Application') -> _Middleware: @middleware - async def impl(request, handler): + async def impl(request: Request, handler: _Handler) -> StreamResponse: with request.match_info.set_current_app(app): return await handler(request) return impl diff -Nru python-aiohttp-3.1.3/aiohttp/web_protocol.py python-aiohttp-3.5.1/aiohttp/web_protocol.py --- python-aiohttp-3.1.3/aiohttp/web_protocol.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/web_protocol.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,29 +1,48 @@ import asyncio import asyncio.streams -import http.server import traceback import warnings from collections import deque from contextlib import suppress from html import escape as html_escape +from logging import Logger +from typing import (TYPE_CHECKING, Any, Awaitable, Callable, Optional, Type, + cast) import yarl -from . import helpers, http -from .helpers import CeilTimeout -from .http import HttpProcessingError, HttpRequestParser, StreamWriter +from .abc import AbstractAccessLogger, AbstractStreamWriter +from .base_protocol import BaseProtocol +from .helpers import CeilTimeout, current_task +from .http import (HttpProcessingError, HttpRequestParser, HttpVersion10, + RawRequestMessage, StreamWriter) from .log import access_logger, server_logger -from .streams import EMPTY_PAYLOAD -from .tcp_helpers import tcp_cork, tcp_keepalive, tcp_nodelay +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 +from .web_response import Response, StreamResponse -__all__ = ('RequestHandler', 'RequestPayloadError') +__all__ = ('RequestHandler', 'RequestPayloadError', 'PayloadAccessError') -ERROR = http.RawRequestMessage( - 'UNKNOWN', '/', http.HttpVersion10, {}, +if TYPE_CHECKING: # pragma: no cover + from .web_server import Server # noqa + + +_RequestFactory = Callable[[RawRequestMessage, + StreamReader, + 'RequestHandler', + AbstractStreamWriter, + 'asyncio.Task[None]'], + BaseRequest] + +_RequestHandler = Callable[[BaseRequest], Awaitable[StreamResponse]] + + +ERROR = RawRequestMessage( + 'UNKNOWN', '/', HttpVersion10, {}, {}, True, False, False, False, yarl.URL('/')) @@ -31,7 +50,11 @@ """Payload parsing error.""" -class RequestHandler(asyncio.streams.FlowControlMixin, asyncio.Protocol): +class PayloadAccessError(Exception): + """Payload was accessed after response was sent.""" + + +class RequestHandler(BaseProtocol): """HTTP protocol implementation. RequestHandler handles incoming HTTP request. It reads request line, @@ -70,78 +93,84 @@ :param int max_headers: Optional maximum header size """ - _request_count = 0 - _keepalive = False # keep transport open KEEPALIVE_RESCHEDULE_DELAY = 1 - def __init__(self, manager, *, loop=None, - keepalive_timeout=75, # NGINX default value is 75 secs - tcp_keepalive=True, - logger=server_logger, - access_log_class=helpers.AccessLogger, - access_log=access_logger, - access_log_format=helpers.AccessLogger.LOG_FORMAT, - debug=False, - max_line_size=8190, - max_headers=32768, - max_field_size=8190, - lingering_time=10.0): - - super().__init__(loop=loop) - - self._loop = loop if loop is not None else asyncio.get_event_loop() - - self._manager = manager - self._request_handler = manager.request_handler - self._request_factory = manager.request_factory + __slots__ = ('_request_count', '_keep_alive', '_manager', + '_request_handler', '_request_factory', '_tcp_keepalive', + '_keepalive_time', '_keepalive_handle', '_keepalive_timeout', + '_lingering_time', '_messages', '_message_tail', + '_waiter', '_error_handler', '_task_handler', + '_upgrade', '_payload_parser', '_request_parser', + '_reading_paused', 'logger', 'debug', 'access_log', + 'access_logger', '_close', '_force_close') + + def __init__(self, manager: 'Server', *, + loop: asyncio.AbstractEventLoop, + keepalive_timeout: float=75., # 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): + + super().__init__(loop) + + self._request_count = 0 + self._keepalive = False + self._manager = manager # type: Optional[Server] + self._request_handler = manager.request_handler # type: Optional[_RequestHandler] # noqa + self._request_factory = manager.request_factory # type: Optional[_RequestFactory] # noqa self._tcp_keepalive = tcp_keepalive - self._keepalive_time = None - self._keepalive_handle = None + # 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() + self._messages = deque() # type: Any # Python 3.5 has no typing.Deque self._message_tail = b'' - self._waiter = None - self._error_handler = None - self._task_handler = self._loop.create_task(self.start()) + self._waiter = None # type: Optional[asyncio.Future[None]] + self._error_handler = None # type: Optional[asyncio.Task[None]] + self._task_handler = None # type: Optional[asyncio.Task[None]] self._upgrade = False - self._payload_parser = None + self._payload_parser = None # type: Any self._request_parser = HttpRequestParser( self, loop, max_line_size=max_line_size, max_field_size=max_field_size, max_headers=max_headers, - payload_exception=RequestPayloadError) - - self.transport = None - self._reading_paused = False + payload_exception=RequestPayloadError) # type: Optional[HttpRequestParser] # noqa 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) + access_log, access_log_format) # type: Optional[AbstractAccessLogger] # noqa else: self.access_logger = None self._close = False self._force_close = False - def __repr__(self): + def __repr__(self) -> str: return "<{} {}>".format( self.__class__.__name__, 'connected' if self.transport is not None else 'disconnected') @property - def keepalive_timeout(self): + def keepalive_timeout(self) -> float: return self._keepalive_timeout - async def shutdown(self, timeout=15.0): + async def shutdown(self, timeout: Optional[float]=15.0) -> None: """Worker process is about to exit, we need cleanup everything and stop accepting requests. It is especially important for keep-alive connections.""" @@ -156,33 +185,36 @@ # wait for handlers with suppress(asyncio.CancelledError, asyncio.TimeoutError): with CeilTimeout(timeout, loop=self._loop): - if self._error_handler and not self._error_handler.done(): + if (self._error_handler is not None and + not self._error_handler.done()): await self._error_handler - if self._task_handler and not self._task_handler.done(): + 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: + 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): + def connection_made(self, transport: asyncio.BaseTransport) -> None: super().connection_made(transport) - self.transport = transport - + real_transport = cast(asyncio.Transport, transport) if self._tcp_keepalive: - tcp_keepalive(transport) + tcp_keepalive(real_transport) - tcp_cork(transport, False) - tcp_nodelay(transport, True) - self._manager.connection_made(self, 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): + def connection_lost(self, exc: Optional[BaseException]) -> None: + if self._manager is None: + return self._manager.connection_lost(self, exc) super().connection_lost(exc) @@ -192,12 +224,11 @@ self._request_factory = None self._request_handler = None self._request_parser = None - self.transport = None if self._keepalive_handle is not None: self._keepalive_handle.cancel() - if self._task_handler: + if self._task_handler is not None: self._task_handler.cancel() if self._error_handler is not None: @@ -209,7 +240,8 @@ self._payload_parser.feed_eof() self._payload_parser = None - def set_parser(self, parser): + def set_parser(self, parser: Any) -> None: + # Actual type is WebReader assert self._payload_parser is None self._payload_parser = parser @@ -218,29 +250,29 @@ self._payload_parser.feed_data(self._message_tail) self._message_tail = b'' - def eof_received(self): + def eof_received(self) -> None: pass - def data_received(self, data): + def data_received(self, data: bytes) -> None: if self._force_close or self._close: return - # parse http messages 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: # something happened during parsing self._error_handler = self._loop.create_task( self.handle_parse_error( - StreamWriter(self, self.transport, self._loop), + StreamWriter(self, self._loop), 400, exc, exc.message)) self.close() except Exception as exc: # 500: internal error self._error_handler = self._loop.create_task( self.handle_parse_error( - StreamWriter(self, self.transport, self._loop), + StreamWriter(self, self._loop), 500, exc)) self.close() else: @@ -270,7 +302,7 @@ if eof: self.close() - def keep_alive(self, val): + def keep_alive(self, val: bool) -> None: """Set keep-alive connection mode. :param bool val: new state. @@ -280,36 +312,37 @@ self._keepalive_handle.cancel() self._keepalive_handle = None - def close(self): + def close(self) -> None: """Stop accepting new pipelinig messages and close connection when handlers done processing messages""" self._close = True if self._waiter: self._waiter.cancel() - def force_close(self, send_last_heartbeat=False): + def force_close(self) -> None: """Force close connection""" self._force_close = True if self._waiter: self._waiter.cancel() if self.transport is not None: - if send_last_heartbeat: - self.transport.write(b"\r\n") self.transport.close() self.transport = None - def log_access(self, request, response, time): + def log_access(self, + request: BaseRequest, + response: StreamResponse, + time: float) -> None: if self.access_logger is not None: self.access_logger.log(request, response, time) - def log_debug(self, *args, **kw): + def log_debug(self, *args: Any, **kw: Any) -> None: if self.debug: self.logger.debug(*args, **kw) - def log_exception(self, *args, **kw): + def log_exception(self, *args: Any, **kw: Any) -> None: self.logger.exception(*args, **kw) - def _process_keepalive(self): + def _process_keepalive(self) -> None: if self._force_close or not self._keepalive: return @@ -318,7 +351,7 @@ # handler in idle state if self._waiter: if self._loop.time() > next: - self.force_close(send_last_heartbeat=True) + self.force_close() return # not all request handlers are done, @@ -326,23 +359,7 @@ self._keepalive_handle = self._loop.call_later( self.KEEPALIVE_RESCHEDULE_DELAY, self._process_keepalive) - def pause_reading(self): - if not self._reading_paused: - try: - self.transport.pause_reading() - except (AttributeError, NotImplementedError, RuntimeError): - pass - self._reading_paused = True - - def resume_reading(self): - if self._reading_paused: - try: - self.transport.resume_reading() - except (AttributeError, NotImplementedError, RuntimeError): - pass - self._reading_paused = False - - async def start(self): + async def start(self) -> None: """Process incoming request. It reads request line, request headers and request payload, then @@ -353,8 +370,13 @@ """ 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: @@ -373,36 +395,48 @@ now = loop.time() manager.requests_count += 1 - writer = StreamWriter(self, self.transport, loop) + writer = StreamWriter(self, loop) request = self._request_factory( message, payload, self, writer, handler) try: try: - resp = await self._request_handler(request) + # a new task is used for copy context vars (#3406) + task = self._loop.create_task( + self._request_handler(request)) + resp = await task except HTTPException as exc: resp = exc except asyncio.CancelledError: self.log_debug('Ignored premature client disconnection') break - except asyncio.TimeoutError: - self.log_debug('Request handler timed out.') + except asyncio.TimeoutError as exc: + self.log_debug('Request handler timed out.', exc_info=exc) resp = self.handle_error(request, 504) except Exception as exc: resp = self.handle_error(request, 500, exc) else: # Deprecation warning (See #2415) - if isinstance(resp, HTTPException): + if getattr(resp, '__http_exception__', False): warnings.warn( "returning HTTPException object is deprecated " "(#2415) and will be removed, " "please raise the exception instead", DeprecationWarning) + if self.debug: + if not isinstance(resp, StreamResponse): + 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)) await resp.prepare(request) await resp.write_eof() # notify server about keep-alive - self._keepalive = resp.keep_alive + self._keepalive = bool(resp.keep_alive) # log access if self.access_log: @@ -422,8 +456,7 @@ with suppress( asyncio.TimeoutError, asyncio.CancelledError): while not payload.is_eof() and now < end_t: - timeout = min(end_t - now, lingering_time) - with CeilTimeout(timeout, loop=loop): + with CeilTimeout(end_t - now, loop=loop): # read and ignore await payload.readany() now = loop.time() @@ -433,6 +466,8 @@ self.log_debug('Uncompleted request.') self.close() + payload.set_exception(PayloadAccessError()) + except asyncio.CancelledError: self.log_debug('Ignored premature client disconnection ') break @@ -445,7 +480,7 @@ self.log_exception('Unhandled exception', exc_info=exc) self.force_close() finally: - if self.transport is None: + 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: @@ -466,7 +501,11 @@ if self.transport is not None and self._error_handler is None: self.transport.close() - def handle_error(self, request, status=500, exc=None, message=None): + 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 @@ -486,10 +525,11 @@ msg += "Server got itself in trouble" msg = ("500 Internal Server Error" "" + msg + "") + resp = Response(status=status, text=msg, content_type='text/html') else: - msg = message + resp = Response(status=status, text=message, + content_type='text/html') - resp = Response(status=status, text=msg, content_type='text/html') resp.force_close() # some data already got sent, connection is broken @@ -498,10 +538,17 @@ return resp - async def handle_parse_error(self, writer, status, exc=None, message=None): - request = BaseRequest( - ERROR, EMPTY_PAYLOAD, - self, writer, None, self._loop) + async def handle_parse_error(self, + writer: AbstractStreamWriter, + status: int, + exc: Optional[BaseException]=None, + message: Optional[str]=None) -> None: + request = BaseRequest( # type: ignore + ERROR, + EMPTY_PAYLOAD, + self, writer, + current_task(), + self._loop) resp = self.handle_error(request, status, exc, message) await resp.prepare(request) diff -Nru python-aiohttp-3.1.3/aiohttp/web.py python-aiohttp-3.5.1/aiohttp/web.py --- python-aiohttp-3.1.3/aiohttp/web.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/web.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,23 +1,30 @@ import asyncio +import logging import socket import sys from argparse import ArgumentParser -from collections import Iterable +from collections.abc import Iterable from importlib import import_module +from typing import Any, Awaitable, Callable, List, Optional, Type, Union, cast -from . import (helpers, web_app, web_exceptions, web_fileresponse, - web_middlewares, web_protocol, web_request, web_response, +from . import (web_app, web_exceptions, web_fileresponse, web_middlewares, + web_protocol, web_request, web_response, web_routedef, web_runner, web_server, web_urldispatcher, web_ws) +from .abc import AbstractAccessLogger +from .helpers import all_tasks from .log import access_logger from .web_app import * # noqa +from .web_app import Application from .web_exceptions import * # noqa from .web_fileresponse import * # noqa +from .web_log import AccessLogger from .web_middlewares import * # noqa from .web_protocol import * # noqa from .web_request import * # noqa from .web_response import * # noqa -from .web_runner import * # noqa -from .web_runner import AppRunner, GracefulExit, SockSite, TCPSite, UnixSite +from .web_routedef import * # noqa +from .web_runner import (AppRunner, BaseRunner, BaseSite, GracefulExit, # noqa + ServerRunner, SockSite, TCPSite, UnixSite) from .web_server import * # noqa from .web_urldispatcher import * # noqa from .web_ws import * # noqa @@ -28,35 +35,53 @@ web_fileresponse.__all__ + web_request.__all__ + web_response.__all__ + + web_routedef.__all__ + web_exceptions.__all__ + web_urldispatcher.__all__ + web_ws.__all__ + web_server.__all__ + web_runner.__all__ + web_middlewares.__all__ + - ('run_app',)) - - -def run_app(app, *, host=None, port=None, path=None, sock=None, - shutdown_timeout=60.0, ssl_context=None, - print=print, backlog=128, access_log_class=helpers.AccessLogger, - access_log_format=helpers.AccessLogger.LOG_FORMAT, - access_log=access_logger, handle_signals=True, - reuse_address=None, reuse_port=None): - """Run an app locally""" - loop = asyncio.get_event_loop() - + ('run_app', 'BaseSite', 'TCPSite', 'UnixSite', + 'SockSite', 'BaseRunner', + 'AppRunner', 'ServerRunner', 'GracefulExit')) + + +try: + from ssl import SSLContext +except ImportError: # pragma: no cover + SSLContext = Any # type: ignore + + +async def _run_app(app: Union[Application, Awaitable[Application]], *, + host: Optional[str]=None, + port: Optional[int]=None, + path: Optional[str]=None, + sock: Optional[socket.socket]=None, + shutdown_timeout: float=60.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: 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 = loop.run_until_complete(app) + app = await app # type: ignore + + 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) - loop.run_until_complete(runner.setup()) + await runner.setup() - sites = [] + sites = [] # type: List[BaseSite] try: if host is not None: @@ -108,23 +133,91 @@ ssl_context=ssl_context, backlog=backlog)) for site in sites: - loop.run_until_complete(site.start()) - try: - 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))) - loop.run_forever() - except (GracefulExit, KeyboardInterrupt): # pragma: no cover - pass + 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))) + while True: + await asyncio.sleep(3600) # sleep forever by 1 hour intervals finally: - loop.run_until_complete(runner.cleanup()) - if hasattr(loop, 'shutdown_asyncgens'): - loop.run_until_complete(loop.shutdown_asyncgens()) - loop.close() + await runner.cleanup() + + +def _cancel_all_tasks(loop: asyncio.AbstractEventLoop) -> None: + to_cancel = all_tasks(loop) + if not to_cancel: + return + + for task in to_cancel: + task.cancel() + + loop.run_until_complete( + asyncio.gather(*to_cancel, loop=loop, 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[str]=None, + port: Optional[int]=None, + path: Optional[str]=None, + sock: Optional[socket.socket]=None, + shutdown_timeout: float=60.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: logging.Logger=access_logger, + handle_signals: bool=True, + reuse_address: Optional[bool]=None, + reuse_port: Optional[bool]=None) -> None: + """Run an app locally""" + loop = asyncio.get_event_loop() + # Configure if and only if in debugging mode and using the default logger + if loop.get_debug() 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()) -def main(argv): + try: + loop.run_until_complete(_run_app(app, + host=host, + port=port, + path=path, + sock=sock, + shutdown_timeout=shutdown_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)) + except (GracefulExit, KeyboardInterrupt): # pragma: no cover + pass + finally: + _cancel_all_tasks(loop) + if sys.version_info >= (3, 6): # don't use PY_36 to pass mypy + 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" @@ -175,6 +268,8 @@ 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") diff -Nru python-aiohttp-3.1.3/aiohttp/web_request.py python-aiohttp-3.5.1/aiohttp/web_request.py --- python-aiohttp-3.1.3/aiohttp/web_request.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/web_request.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,8 +1,6 @@ import asyncio -import collections import datetime import io -import json import re import socket import string @@ -12,28 +10,42 @@ from email.utils import parsedate from http.cookies import SimpleCookie from types import MappingProxyType +from typing import (TYPE_CHECKING, Any, Dict, Iterator, Mapping, # noqa + MutableMapping, Optional, 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, multipart -from .helpers import DEBUG, HeadersMixin, reify, sentinel -from .streams import EmptyStreamReader +from . import hdrs +from .abc import AbstractStreamWriter +from .helpers import DEBUG, ChainMapProxy, HeadersMixin, reify, sentinel +from .http_parser import RawRequestMessage +from .multipart import MultipartReader +from .streams import EmptyStreamReader, StreamReader +from .typedefs import (DEFAULT_JSON_DECODER, 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 # noqa + from .web_urldispatcher import UrlMappingMatchInfo # noqa + from .web_protocol import RequestHandler # noqa + + @attr.s(frozen=True, slots=True) class FileField: name = attr.ib(type=str) filename = attr.ib(type=str) file = attr.ib(type=io.BufferedReader) content_type = attr.ib(type=str) - headers = attr.ib(type=CIMultiDictProxy) + headers = attr.ib(type=CIMultiDictProxy) # type: CIMultiDictProxy[str] _TCHAR = string.digits + string.ascii_letters + r"!#$%&'*+.^_`|~-" @@ -52,7 +64,7 @@ qdtext=_QDTEXT, quoted_pair=_QUOTED_PAIR) _FORWARDED_PAIR = ( - r'({token})=({token}|{quoted_string})'.format( + r'({token})=({token}|{quoted_string})(:\d{{1,4}})?'.format( token=_TOKEN, quoted_string=_QUOTED_STRING)) @@ -66,7 +78,7 @@ ############################################################ -class BaseRequest(collections.MutableMapping, HeadersMixin): +class BaseRequest(MutableMapping[str, Any], HeadersMixin): POST_METHODS = {hdrs.METH_PATCH, hdrs.METH_POST, hdrs.METH_PUT, hdrs.METH_TRACE, hdrs.METH_DELETE} @@ -74,13 +86,19 @@ ATTRS = HeadersMixin.ATTRS | frozenset([ '_message', '_protocol', '_payload_writer', '_payload', '_headers', '_method', '_version', '_rel_url', '_post', '_read_bytes', - '_state', '_cache', '_task', '_client_max_size', '_loop']) + '_state', '_cache', '_task', '_client_max_size', '_loop', + '_transport_sslcontext', '_transport_peername']) - def __init__(self, message, payload, protocol, payload_writer, task, - loop, - *, client_max_size=1024**2, - state=None, - scheme=None, host=None, remote=None): + 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 @@ -92,15 +110,20 @@ self._method = message.method self._version = message.version self._rel_url = message.url - self._post = None - self._read_bytes = None + self._post = None # type: Optional[MultiDictProxy[Union[str, bytes, FileField]]] # noqa + self._read_bytes = None # type: Optional[bytes] self._state = state - self._cache = {} + 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: @@ -108,9 +131,10 @@ if remote is not None: self._cache['remote'] = remote - def clone(self, *, method=sentinel, rel_url=sentinel, - headers=sentinel, scheme=sentinel, host=sentinel, - remote=sentinel): + 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 @@ -121,17 +145,18 @@ if self._read_bytes: raise RuntimeError("Cannot clone request " - "after reading it's content") + "after reading its content") - dct = {} + dct = {} # type: Dict[str, Any] if method is not sentinel: dct['method'] = method if rel_url is not sentinel: - rel_url = URL(rel_url) - dct['url'] = rel_url - dct['path'] = str(rel_url) + new_url = URL(rel_url) + dct['url'] = new_url + dct['path'] = str(new_url) if headers is not sentinel: - dct['headers'] = CIMultiDict(headers) + # 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()) @@ -157,61 +182,67 @@ **kwargs) @property - def task(self): + def task(self) -> 'asyncio.Task[None]': return self._task @property - def protocol(self): + def protocol(self) -> 'RequestHandler': return self._protocol @property - def transport(self): + def transport(self) -> Optional[asyncio.Transport]: if self._protocol is None: return None return self._protocol.transport @property - def writer(self): + def writer(self) -> AbstractStreamWriter: return self._payload_writer - @property - def message(self): + @reify + def message(self) -> RawRequestMessage: + warnings.warn("Request.message is deprecated", + DeprecationWarning, + stacklevel=3) return self._message - @property - def rel_url(self): + @reify + def rel_url(self) -> URL: return self._rel_url - @property - def loop(self): + @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): + def __getitem__(self, key: str) -> Any: return self._state[key] - def __setitem__(self, key, value): + def __setitem__(self, key: str, value: Any) -> None: self._state[key] = value - def __delitem__(self, key): + def __delitem__(self, key: str) -> None: del self._state[key] - def __len__(self): + def __len__(self) -> int: return len(self._state) - def __iter__(self): + def __iter__(self) -> Iterator[str]: return iter(self._state) ######## - @property - def secure(self): + @reify + def secure(self) -> bool: """A bool indicating if the request is handled with SSL.""" return self.scheme == 'https' @reify - def forwarded(self): + 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: @@ -235,7 +266,7 @@ length = len(field_value) pos = 0 need_separator = False - elem = {} + elem = {} # type: Dict[str, str] elems.append(types.MappingProxyType(elem)) while 0 <= pos < length: match = _FORWARDED_PAIR_RE.match(field_value, pos) @@ -244,11 +275,13 @@ # bad syntax here, skip to next comma pos = field_value.find(',', pos) else: - (name, value) = match.groups() + 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 @@ -271,7 +304,7 @@ return tuple(elems) @reify - def scheme(self): + def scheme(self) -> str: """A string representing the scheme of the request. Hostname is resolved in this order: @@ -281,21 +314,21 @@ 'http' or 'https'. """ - if self.transport.get_extra_info('sslcontext'): + if self._transport_sslcontext: return 'https' else: return 'http' - @property - def method(self): + @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 - @property - def version(self): + @reify + def version(self) -> Tuple[int, int]: """Read only property for getting HTTP version of request. Returns aiohttp.protocol.HttpVersion instance. @@ -303,7 +336,7 @@ return self._version @reify - def host(self): + def host(self) -> str: """Hostname of the request. Hostname is resolved in this order: @@ -319,7 +352,7 @@ return socket.getfqdn() @reify - def remote(self): + def remote(self) -> Optional[str]: """Remote IP of client initiated HTTP request. The IP is resolved in this order: @@ -327,21 +360,18 @@ - overridden value by .clone(remote=new_remote) call. - peername of opened socket """ - if self.transport is None: - return None - peername = self.transport.get_extra_info('peername') - if isinstance(peername, (list, tuple)): - return peername[0] + if isinstance(self._transport_peername, (list, tuple)): + return self._transport_peername[0] else: - return peername + return self._transport_peername @reify - def url(self): + def url(self) -> URL: url = URL.build(scheme=self.scheme, host=self.host) return url.join(self._rel_url) - @property - def path(self): + @reify + def path(self) -> str: """The URL including *PATH INFO* without the host or scheme. E.g., ``/app/blog`` @@ -349,15 +379,15 @@ return self._rel_url.path @reify - def path_qs(self): + 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) - @property - def raw_path(self): + @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 @@ -365,31 +395,31 @@ """ return self._message.path - @property - def query(self): + @reify + def query(self) -> 'MultiDictProxy[str]': """A multidict with all the variables in the query string.""" return self._rel_url.query - @property - def query_string(self): + @reify + def query_string(self) -> str: """The query string in the URL. E.g., id=10 """ return self._rel_url.query_string - @property - def headers(self): + @reify + def headers(self) -> 'CIMultiDictProxy[str]': """A case-insensitive multidict proxy with all headers.""" return self._headers - @property - def raw_headers(self): - """A sequence of pars for all headers.""" + @reify + def raw_headers(self) -> RawHeaders: + """A sequence of pairs for all headers.""" return self._message.raw_headers @staticmethod - def _http_date(_date_str): + def _http_date(_date_str: str) -> Optional[datetime.datetime]: """Process a date string, return a datetime object """ if _date_str is not None: @@ -400,37 +430,36 @@ return None @reify - def if_modified_since(self, _IF_MODIFIED_SINCE=hdrs.IF_MODIFIED_SINCE): + 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 self._http_date(self.headers.get(_IF_MODIFIED_SINCE)) + return self._http_date(self.headers.get(hdrs.IF_MODIFIED_SINCE)) @reify - def if_unmodified_since(self, - _IF_UNMODIFIED_SINCE=hdrs.IF_UNMODIFIED_SINCE): + 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 self._http_date(self.headers.get(_IF_UNMODIFIED_SINCE)) + return self._http_date(self.headers.get(hdrs.IF_UNMODIFIED_SINCE)) @reify - def if_range(self, _IF_RANGE=hdrs.IF_RANGE): + 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 self._http_date(self.headers.get(_IF_RANGE)) + return self._http_date(self.headers.get(hdrs.IF_RANGE)) - @property - def keep_alive(self): + @reify + def keep_alive(self) -> bool: """Is keepalive enabled by client?""" return not self._message.should_close @reify - def cookies(self): + def cookies(self) -> Mapping[str, str]: """Return request cookies. A read-only dictionary-like object. @@ -440,14 +469,14 @@ return MappingProxyType( {key: val.value for key, val in parsed.items()}) - @property - def http_range(self, *, _RANGE=hdrs.RANGE): + @reify + def http_range(self) -> slice: """The content of Range HTTP header. Return a slice instance. """ - rng = self._headers.get(_RANGE) + rng = self._headers.get(hdrs.RANGE) start, end = None, None if rng is not None: try: @@ -476,13 +505,13 @@ return slice(start, end, 1) - @property - def content(self): + @reify + def content(self) -> StreamReader: """Return raw payload stream.""" return self._payload @property - def has_body(self): + 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", @@ -490,16 +519,16 @@ return not self._payload.at_eof() @property - def can_read_body(self): + def can_read_body(self) -> bool: """Return True if request's HTTP BODY can be read, False otherwise.""" return not self._payload.at_eof() - @property - def body_exists(self): + @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): + async def release(self) -> None: """Release request. Eat unread part of HTTP BODY if present. @@ -507,7 +536,7 @@ while not self._payload.at_eof(): await self._payload.readany() - async def read(self): + async def read(self) -> bytes: """Read request body if present. Returns bytes object with full request content. @@ -517,30 +546,34 @@ while True: chunk = await self._payload.readany() body.extend(chunk) - if self._client_max_size \ - and len(body) >= self._client_max_size: - raise HTTPRequestEntityTooLarge + 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): + 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=json.loads): + 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, *, reader=multipart.MultipartReader): + async def multipart(self) -> MultipartReader: """Return async iterator to process BODY as multipart.""" - return reader(self._headers, self._payload) + return MultipartReader(self._headers, self._payload) - async def post(self): + async def post(self) -> 'MultiDictProxy[Union[str, bytes, FileField]]': """Return POST parameters.""" if self._post is not None: return self._post @@ -555,15 +588,15 @@ self._post = MultiDictProxy(MultiDict()) return self._post - out = MultiDict() + 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 - max_size = self._client_max_size content_type = field.headers.get(hdrs.CONTENT_TYPE) if field.filename: @@ -575,13 +608,16 @@ tmp.write(chunk) size += len(chunk) if 0 < max_size < size: - raise ValueError( - 'Maximum request body size exceeded') + raise HTTPRequestEntityTooLarge( + max_size=max_size, + actual_size=size + ) chunk = await field.read_chunk(size=2**16) tmp.seek(0) ff = FileField(field.name, field.filename, - tmp, content_type, field.headers) + cast(io.BufferedReader, tmp), + content_type, field.headers) out.add(field.name, ff) else: value = await field.read(decode=True) @@ -592,8 +628,10 @@ out.add(field.name, value) size += len(value) if 0 < max_size < size: - raise ValueError( - 'Maximum request body size exceeded') + raise HTTPRequestEntityTooLarge( + max_size=max_size, + actual_size=size + ) field = await multipart.next() else: @@ -609,31 +647,34 @@ self._post = MultiDictProxy(out) return self._post - def __repr__(self): + def __repr__(self) -> str: ascii_encodable_path = self.path.encode('ascii', 'backslashreplace') \ .decode('ascii') return "<{} {} {} >".format(self.__class__.__name__, self._method, ascii_encodable_path) - @asyncio.coroutine - def _prepare_hook(self, response): + def __eq__(self, other: object) -> bool: + return id(self) == id(other) + + async def _prepare_hook(self, response: StreamResponse) -> None: return - yield # pragma: no cover class Request(BaseRequest): ATTRS = BaseRequest.ATTRS | frozenset(['_match_info']) - def __init__(self, *args, **kwargs): + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) # matchdict, route_name, handler # or information about traversal lookup - self._match_info = None # initialized after route resolving + + # initialized after route resolving + self._match_info = None # type: Optional[UrlMappingMatchInfo] if DEBUG: - def __setattr__(self, name, val): + 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__, @@ -642,31 +683,47 @@ stacklevel=2) super().__setattr__(name, val) - def clone(self, *, method=sentinel, rel_url=sentinel, - headers=sentinel, scheme=sentinel, host=sentinel, - remote=sentinel): + 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) - ret._match_info = self._match_info - return ret + new_ret = cast(Request, ret) + new_ret._match_info = self._match_info + return new_ret - @property - def match_info(self): + @reify + def match_info(self) -> 'UrlMappingMatchInfo': """Result of route resolving.""" - return self._match_info + match_info = self._match_info + assert match_info is not None + return match_info @property - def app(self): + def app(self) -> 'Application': """Application instance.""" - return self._match_info.current_app + 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): + 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: + for app in match_info._apps: await app.on_response_prepare.send(self, response) diff -Nru python-aiohttp-3.1.3/aiohttp/web_response.py python-aiohttp-3.5.1/aiohttp/web_response.py --- python-aiohttp-3.1.3/aiohttp/web_response.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/web_response.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,4 +1,5 @@ -import collections +import asyncio # noqa +import collections # noqa import datetime import enum import json @@ -6,19 +7,32 @@ import time import warnings import zlib +from concurrent.futures import Executor from email.utils import parsedate from http.cookies import SimpleCookie +from typing import (TYPE_CHECKING, Any, Dict, Iterator, Mapping, # noqa + MutableMapping, Optional, Tuple, Union, cast) -from multidict import CIMultiDict, CIMultiDictProxy +from multidict import CIMultiDict, istr from . import hdrs, payload +from .abc import AbstractStreamWriter from .helpers import HeadersMixin, rfc822_formatted_time, sentinel 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 # noqa + BaseClass = MutableMapping[str, Any] +else: + BaseClass = collections.MutableMapping + + class ContentCoding(enum.Enum): # The content codings that we have support for. # @@ -34,56 +48,62 @@ ############################################################ -class StreamResponse(collections.MutableMapping, HeadersMixin): +class StreamResponse(BaseClass, HeadersMixin): _length_check = True - def __init__(self, *, status=200, reason=None, headers=None): + def __init__(self, *, + status: int=200, + reason: Optional[str]=None, + headers: Optional[LooseHeaders]=None) -> None: self._body = None - self._keep_alive = None + self._keep_alive = None # type: Optional[bool] self._chunked = False self._compression = False - self._compression_force = False + self._compression_force = None # type: Optional[ContentCoding] self._cookies = SimpleCookie() - self._req = None - self._payload_writer = None + self._req = None # type: Optional[BaseRequest] + self._payload_writer = None # type: Optional[AbstractStreamWriter] self._eof_sent = False self._body_length = 0 - self._state = {} + self._state = {} # type: Dict[str, Any] if headers is not None: - self._headers = CIMultiDict(headers) + self._headers = CIMultiDict(headers) # type: CIMultiDict[str] else: - self._headers = CIMultiDict() + self._headers = CIMultiDict() # type: CIMultiDict[str] self.set_status(status, reason) @property - def prepared(self): + def prepared(self) -> bool: return self._payload_writer is not None @property - def task(self): + def task(self) -> 'asyncio.Task[None]': return getattr(self._req, 'task', None) @property - def status(self): + def status(self) -> int: return self._status @property - def chunked(self): + def chunked(self) -> bool: return self._chunked @property - def compression(self): + def compression(self) -> bool: return self._compression @property - def reason(self): + def reason(self) -> str: return self._reason - def set_status(self, status, reason=None, _RESPONSES=RESPONSES): + 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' @@ -96,22 +116,23 @@ self._reason = reason @property - def keep_alive(self): + def keep_alive(self) -> Optional[bool]: return self._keep_alive - def force_close(self): + def force_close(self) -> None: self._keep_alive = False @property - def body_length(self): + def body_length(self) -> int: return self._body_length @property - def output_length(self): + 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=None): + def enable_chunked_encoding(self, chunk_size: Optional[int]=None) -> None: """Enables automatic chunked transfer encoding.""" self._chunked = True @@ -121,11 +142,15 @@ if chunk_size is not None: warnings.warn('Chunk size is deprecated #1615', DeprecationWarning) - def enable_compression(self, force=None): + 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 " @@ -135,16 +160,21 @@ self._compression_force = force @property - def headers(self): + def headers(self) -> 'CIMultiDict[str]': return self._headers @property - def cookies(self): + def cookies(self) -> SimpleCookie: return self._cookies - def set_cookie(self, name, value, *, expires=None, - domain=None, max_age=None, path='/', - secure=None, httponly=None, version=None): + 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[str]=None, + httponly: Optional[str]=None, + version: Optional[str]=None) -> None: """Set or update response cookie. Sets new cookie or updates existent with new value. @@ -168,7 +198,7 @@ c['domain'] = domain if max_age is not None: - c['max-age'] = max_age + c['max-age'] = str(max_age) elif 'max-age' in c: del c['max-age'] @@ -181,7 +211,9 @@ if version is not None: c['version'] = version - def del_cookie(self, name, *, domain=None, path='/'): + def del_cookie(self, name: str, *, + domain: Optional[str]=None, + path: str='/') -> None: """Delete cookie. Creates new empty expired cookie. @@ -193,12 +225,12 @@ domain=domain, path=path) @property - def content_length(self): + def content_length(self) -> Optional[int]: # Just a placeholder for adding setter return super().content_length @content_length.setter - def content_length(self, value): + def content_length(self, value: Optional[int]) -> None: if value is not None: value = int(value) if self._chunked: @@ -209,27 +241,28 @@ self._headers.pop(hdrs.CONTENT_LENGTH, None) @property - def content_type(self): + def content_type(self) -> str: # Just a placeholder for adding setter return super().content_type @content_type.setter - def content_type(self, value): + 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): + def charset(self) -> Optional[str]: # Just a placeholder for adding setter return super().charset @charset.setter - def charset(self, value): + 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: @@ -237,12 +270,12 @@ self._generate_content_type_header() @property - def last_modified(self, _LAST_MODIFIED=hdrs.LAST_MODIFIED): + def last_modified(self) -> Optional[datetime.datetime]: """The value of Last-Modified HTTP header, or None. This header is represented as a `datetime` object. """ - httpdate = self.headers.get(_LAST_MODIFIED) + httpdate = self._headers.get(hdrs.LAST_MODIFIED) if httpdate is not None: timetuple = parsedate(httpdate) if timetuple is not None: @@ -251,65 +284,66 @@ return None @last_modified.setter - def last_modified(self, value): + def last_modified(self, + value: Optional[ + Union[int, float, datetime.datetime, str]]) -> None: if value is None: - self.headers.pop(hdrs.LAST_MODIFIED, None) + self._headers.pop(hdrs.LAST_MODIFIED, None) elif isinstance(value, (int, float)): - self.headers[hdrs.LAST_MODIFIED] = time.strftime( + 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( + 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 + self._headers[hdrs.LAST_MODIFIED] = value - def _generate_content_type_header(self, CONTENT_TYPE=hdrs.CONTENT_TYPE): - params = '; '.join("%s=%s" % i for i in self._content_dict.items()) + 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("{}={}".format(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 + self._headers[CONTENT_TYPE] = ctype - def _do_start_compression(self, coding): + async def _do_start_compression(self, coding: ContentCoding) -> None: if coding != ContentCoding.identity: - self.headers[hdrs.CONTENT_ENCODING] = coding.value + 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) - def _start_compression(self, request): + async def _start_compression(self, request: 'BaseRequest') -> None: if self._compression_force: - self._do_start_compression(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: - self._do_start_compression(coding) + await self._do_start_compression(coding) return - async def prepare(self, request): + async def prepare( + self, + request: 'BaseRequest' + ) -> Optional[AbstractStreamWriter]: if self._eof_sent: - return + return None if self._payload_writer is not None: return self._payload_writer await request._prepare_hook(self) return await self._start(request) - async def _start(self, request, - HttpVersion10=HttpVersion10, - HttpVersion11=HttpVersion11, - CONNECTION=hdrs.CONNECTION, - DATE=hdrs.DATE, - SERVER=hdrs.SERVER, - CONTENT_TYPE=hdrs.CONTENT_TYPE, - CONTENT_LENGTH=hdrs.CONTENT_LENGTH, - SET_COOKIE=hdrs.SET_COOKIE, - SERVER_SOFTWARE=SERVER_SOFTWARE, - TRANSFER_ENCODING=hdrs.TRANSFER_ENCODING): + async def _start(self, request: 'BaseRequest') -> AbstractStreamWriter: self._req = request keep_alive = self._keep_alive @@ -323,10 +357,10 @@ headers = self._headers for cookie in self._cookies.values(): value = cookie.output(header='')[1:] - headers.add(SET_COOKIE, value) + headers.add(hdrs.SET_COOKIE, value) if self._compression: - self._start_compression(request) + await self._start_compression(request) if self._chunked: if version != HttpVersion11: @@ -334,41 +368,41 @@ "Using chunked encoding is forbidden " "for HTTP/{0.major}.{0.minor}".format(request.version)) writer.enable_chunking() - headers[TRANSFER_ENCODING] = 'chunked' - if CONTENT_LENGTH in headers: - del headers[CONTENT_LENGTH] + 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: writer.enable_chunking() - headers[TRANSFER_ENCODING] = 'chunked' - if CONTENT_LENGTH in headers: - del headers[CONTENT_LENGTH] + headers[hdrs.TRANSFER_ENCODING] = 'chunked' + if hdrs.CONTENT_LENGTH in headers: + del headers[hdrs.CONTENT_LENGTH] else: keep_alive = False - headers.setdefault(CONTENT_TYPE, 'application/octet-stream') - headers.setdefault(DATE, rfc822_formatted_time()) - headers.setdefault(SERVER, SERVER_SOFTWARE) + headers.setdefault(hdrs.CONTENT_TYPE, 'application/octet-stream') + headers.setdefault(hdrs.DATE, rfc822_formatted_time()) + headers.setdefault(hdrs.SERVER, SERVER_SOFTWARE) # connection header - if CONNECTION not in headers: + if hdrs.CONNECTION not in headers: if keep_alive: if version == HttpVersion10: - headers[CONNECTION] = 'keep-alive' + headers[hdrs.CONNECTION] = 'keep-alive' else: if version == HttpVersion11: - headers[CONNECTION] = 'close' + headers[hdrs.CONNECTION] = 'close' # status line - status_line = 'HTTP/{}.{} {} {}\r\n'.format( + status_line = 'HTTP/{}.{} {} {}'.format( version[0], version[1], self._status, self._reason) await writer.write_headers(status_line, headers) return writer - async def write(self, data): + async def write(self, data: bytes) -> None: assert isinstance(data, (bytes, bytearray, memoryview)), \ "data argument must be byte-ish (%r)" % type(data) @@ -379,7 +413,7 @@ await self._payload_writer.write(data) - async def drain(self): + 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" @@ -388,7 +422,7 @@ stacklevel=2) await self._payload_writer.drain() - async def write_eof(self, data=b''): + async def write_eof(self, data: bytes=b'') -> None: assert isinstance(data, (bytes, bytearray, memoryview)), \ "data argument must be byte-ish (%r)" % type(data) @@ -404,54 +438,67 @@ self._body_length = self._payload_writer.output_size self._payload_writer = None - def __repr__(self): + def __repr__(self) -> str: if self._eof_sent: info = "eof" elif self.prepared: + assert self._req is not None info = "{} {} ".format(self._req.method, self._req.path) else: info = "not prepared" return "<{} {} {}>".format(self.__class__.__name__, self.reason, info) - def __getitem__(self, key): + def __getitem__(self, key: str) -> Any: return self._state[key] - def __setitem__(self, key, value): + def __setitem__(self, key: str, value: Any) -> None: self._state[key] = value - def __delitem__(self, key): + def __delitem__(self, key: str) -> None: del self._state[key] - def __len__(self): + def __len__(self) -> int: return len(self._state) - def __iter__(self): + def __iter__(self) -> Iterator[str]: return iter(self._state) - def __hash__(self): + 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=None, status=200, - reason=None, text=None, headers=None, content_type=None, - charset=None): + 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: 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: - headers = CIMultiDict() - elif not isinstance(headers, (CIMultiDict, CIMultiDictProxy)): - headers = CIMultiDict(headers) + 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 headers: + 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 " @@ -465,12 +512,12 @@ content_type = 'text/plain' if charset is None: charset = 'utf-8' - headers[hdrs.CONTENT_TYPE] = ( + real_headers[hdrs.CONTENT_TYPE] = ( content_type + '; charset=' + charset) body = text.encode(charset) text = None else: - if hdrs.CONTENT_TYPE in headers: + 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 " @@ -479,28 +526,30 @@ if content_type is not None: if charset is not None: content_type += '; charset=' + charset - headers[hdrs.CONTENT_TYPE] = content_type + real_headers[hdrs.CONTENT_TYPE] = content_type - super().__init__(status=status, reason=reason, headers=headers) + 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 + self._compressed_body = None # type: Optional[bytes] + self._zlib_executor_size = zlib_executor_size + self._zlib_executor = zlib_executor @property - def body(self): + def body(self) -> Optional[Union[bytes, Payload]]: return self._body @body.setter - def body(self, body, - CONTENT_TYPE=hdrs.CONTENT_TYPE, - CONTENT_LENGTH=hdrs.CONTENT_LENGTH): + 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 - self._body_payload = False + self._body = None # type: Optional[bytes] + self._body_payload = False # type: bool elif isinstance(body, (bytes, bytearray)): self._body = body self._body_payload = False @@ -533,13 +582,13 @@ self._compressed_body = None @property - def text(self): + 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): + def text(self, text: str) -> None: assert text is None or isinstance(text, str), \ "text argument must be str (%r)" % type(text) @@ -553,11 +602,11 @@ self._compressed_body = None @property - def content_length(self): + def content_length(self) -> Optional[int]: if self._chunked: return None - if hdrs.CONTENT_LENGTH in self.headers: + if hdrs.CONTENT_LENGTH in self._headers: return super().content_length if self._compressed_body is not None: @@ -572,29 +621,33 @@ return 0 @content_length.setter - def content_length(self, value): + def content_length(self, value: Optional[int]) -> None: raise RuntimeError("Content length is set automatically") - async def write_eof(self): + async def write_eof(self, data: bytes=b'') -> None: if self._eof_sent: return - if self._compressed_body is not None: - body = self._compressed_body + if self._compressed_body is None: + body = self._body # type: Optional[Union[bytes, Payload]] else: - body = self._body + body = self._compressed_body + assert not data, "data arg is not supported, got {!r}".format(data) + 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: - await body.write(self._payload_writer) + payload = cast(Payload, body) + await payload.write(self._payload_writer) await super().write_eof() else: - await super().write_eof(body) + await super().write_eof(cast(bytes, body)) else: await super().write_eof() - async def _start(self, request): + 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: @@ -604,25 +657,46 @@ return await super()._start(request) - def _do_start_compression(self, coding): + def _compress_body(self, zlib_mode: int) -> None: + 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 super()._do_start_compression(coding) + 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.value == 'gzip' else -zlib.MAX_WBITS) - compressobj = zlib.compressobj(wbits=zlib_mode) - self._compressed_body = compressobj.compress(self._body) +\ - compressobj.flush() + 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(self._compressed_body)) + self._headers[hdrs.CONTENT_LENGTH] = str(len(body_out)) -def json_response(data=sentinel, *, text=None, body=None, status=200, - reason=None, headers=None, content_type='application/json', - dumps=json.dumps): +def json_response(data: Any=sentinel, *, + text: str=None, + body: bytes=None, + status: int=200, + reason: Optional[str]=None, + headers: LooseHeaders=None, + content_type: str='application/json', + dumps: JSONEncoder=json.dumps) -> Response: if data is not sentinel: if text or body: raise ValueError( diff -Nru python-aiohttp-3.1.3/aiohttp/web_routedef.py python-aiohttp-3.5.1/aiohttp/web_routedef.py --- python-aiohttp-3.1.3/aiohttp/web_routedef.py 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/web_routedef.py 2018-12-24 20:58:54.000000000 +0000 @@ -0,0 +1,183 @@ +import abc +import os # noqa +from typing import (TYPE_CHECKING, Any, Awaitable, Callable, Dict, Iterator, + List, Optional, Sequence, Union, overload) + +import attr + +from . import hdrs +from .abc import AbstractView +from .typedefs import PathLike + + +if TYPE_CHECKING: # pragma: no cover + from .web_urldispatcher import UrlDispatcher + from .web_request import Request + from .web_response import StreamResponse +else: + Request = StreamResponse = UrlDispatcher = 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) -> None: + pass # pragma: no cover + + +_SimpleHandler = Callable[[Request], Awaitable[StreamResponse]] +_HandlerType = Union[AbstractView, _SimpleHandler] + + +@attr.s(frozen=True, repr=False, slots=True) +class RouteDef(AbstractRouteDef): + method = attr.ib(type=str) + path = attr.ib(type=str) + handler = attr.ib() # type: _HandlerType + kwargs = attr.ib(type=Dict[str, Any]) + + def __repr__(self) -> str: + info = [] + for name, value in sorted(self.kwargs.items()): + info.append(", {}={!r}".format(name, value)) + return (" {handler.__name__!r}" + "{info}>".format(method=self.method, path=self.path, + handler=self.handler, info=''.join(info))) + + def register(self, router: UrlDispatcher) -> None: + if self.method in hdrs.METH_ALL: + reg = getattr(router, 'add_'+self.method.lower()) + reg(self.path, self.handler, **self.kwargs) + else: + router.add_route(self.method, self.path, self.handler, + **self.kwargs) + + +@attr.s(frozen=True, repr=False, slots=True) +class StaticDef(AbstractRouteDef): + prefix = attr.ib(type=str) + path = attr.ib() # type: PathLike + kwargs = attr.ib(type=Dict[str, Any]) + + def __repr__(self) -> str: + info = [] + for name, value in sorted(self.kwargs.items()): + info.append(", {}={!r}".format(name, value)) + return (" {path}" + "{info}>".format(prefix=self.prefix, path=self.path, + info=''.join(info))) + + def register(self, router: UrlDispatcher) -> None: + router.add_static(self.prefix, self.path, **self.kwargs) + + +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: 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 "".format(len(self._items)) + + @overload + def __getitem__(self, index: int) -> AbstractRouteDef: ... # noqa + + @overload # noqa + def __getitem__(self, index: slice) -> List[AbstractRouteDef]: ... # noqa + + def __getitem__(self, index): # type: ignore # noqa + 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 -Nru python-aiohttp-3.1.3/aiohttp/web_runner.py python-aiohttp-3.5.1/aiohttp/web_runner.py --- python-aiohttp-3.1.3/aiohttp/web_runner.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/web_runner.py 2018-12-24 20:58:54.000000000 +0000 @@ -2,13 +2,21 @@ 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 -__all__ = ('TCPSite', 'UnixSite', 'SockSite', 'BaseRunner', +try: + from ssl import SSLContext +except ImportError: + SSLContext = object # type: ignore + + +__all__ = ('BaseSite', 'TCPSite', 'UnixSite', 'SockSite', 'BaseRunner', 'AppRunner', 'ServerRunner', 'GracefulExit') @@ -16,7 +24,7 @@ code = 1 -def _raise_graceful_exit(): +def _raise_graceful_exit() -> None: raise GracefulExit() @@ -24,27 +32,28 @@ __slots__ = ('_runner', '_shutdown_timeout', '_ssl_context', '_backlog', '_server') - def __init__(self, runner, *, - shutdown_timeout=60.0, ssl_context=None, - backlog=128): + 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 + self._server = None # type: Optional[asyncio.AbstractServer] @property @abstractmethod - def name(self): + def name(self) -> str: pass # pragma: no cover @abstractmethod - async def start(self): + async def start(self) -> None: self._runner._reg_site(self) - async def stop(self): + async def stop(self) -> None: self._runner._check_site(self) if self._server is None: self._runner._unreg_site(self) @@ -52,6 +61,7 @@ self._server.close() 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) @@ -59,10 +69,12 @@ class TCPSite(BaseSite): __slots__ = ('_host', '_port', '_reuse_address', '_reuse_port') - def __init__(self, runner, host=None, port=None, *, - shutdown_timeout=60.0, ssl_context=None, - backlog=128, reuse_address=None, - reuse_port=None): + def __init__(self, runner: 'BaseRunner', + host: str=None, port: 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) if host is None: @@ -75,15 +87,17 @@ self._reuse_port = reuse_port @property - def name(self): + def name(self) -> str: scheme = 'https' if self._ssl_context else 'http' return str(URL.build(scheme=scheme, host=self._host, port=self._port)) - async def start(self): + 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( - self._runner.server, self._host, self._port, + server, self._host, self._port, ssl=self._ssl_context, backlog=self._backlog, reuse_address=self._reuse_address, reuse_port=self._reuse_port) @@ -92,32 +106,36 @@ class UnixSite(BaseSite): __slots__ = ('_path', ) - def __init__(self, runner, path, *, - shutdown_timeout=60.0, ssl_context=None, - backlog=128): + 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): + def name(self) -> str: scheme = 'https' if self._ssl_context else 'http' return '{}://unix:{}:'.format(scheme, self._path) - async def start(self): + 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( - self._runner.server, self._path, + server, self._path, ssl=self._ssl_context, backlog=self._backlog) class SockSite(BaseSite): __slots__ = ('_sock', '_name') - def __init__(self, runner, sock, *, - shutdown_timeout=60.0, ssl_context=None, - backlog=128): + 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 @@ -130,35 +148,49 @@ self._name = name @property - def name(self): + def name(self) -> str: return self._name - async def start(self): + 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( - self._runner.server, sock=self._sock, + 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=False, **kwargs): + def __init__(self, *, handle_signals: bool=False, **kwargs: Any) -> None: self._handle_signals = handle_signals self._kwargs = kwargs - self._server = None - self._sites = set() + self._server = None # type: Optional[Server] + self._sites = [] # type: List[BaseSite] @property - def server(self): + def server(self) -> Optional[Server]: return self._server @property - def sites(self): + def addresses(self) -> List[str]: + ret = [] # type: List[str] + 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): + async def setup(self) -> None: loop = asyncio.get_event_loop() if self._handle_signals: @@ -172,10 +204,10 @@ self._server = await self._make_server() @abstractmethod - async def shutdown(self): + async def shutdown(self) -> None: pass # pragma: no cover - async def cleanup(self): + async def cleanup(self) -> None: loop = asyncio.get_event_loop() if self._server is None: @@ -199,25 +231,25 @@ pass @abstractmethod - async def _make_server(self): + async def _make_server(self) -> Server: pass # pragma: no cover @abstractmethod - async def _cleanup_server(self): + async def _cleanup_server(self) -> None: pass # pragma: no cover - def _reg_site(self, site): + def _reg_site(self, site: BaseSite) -> None: if site in self._sites: raise RuntimeError("Site {} is already registered in runner {}" .format(site, self)) - self._sites.add(site) + self._sites.append(site) - def _check_site(self, site): + def _check_site(self, site: BaseSite) -> None: if site not in self._sites: raise RuntimeError("Site {} is not registered in runner {}" .format(site, self)) - def _unreg_site(self, site): + def _unreg_site(self, site: BaseSite) -> None: if site not in self._sites: raise RuntimeError("Site {} is not registered in runner {}" .format(site, self)) @@ -229,17 +261,18 @@ __slots__ = ('_web_server',) - def __init__(self, web_server, *, handle_signals=False, **kwargs): + 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): + async def shutdown(self) -> None: pass - async def _make_server(self): + async def _make_server(self) -> Server: return self._web_server - async def _cleanup_server(self): + async def _cleanup_server(self) -> None: pass @@ -248,7 +281,8 @@ __slots__ = ('_app',) - def __init__(self, app, *, handle_signals=False, **kwargs): + 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 " @@ -256,20 +290,20 @@ self._app = app @property - def app(self): + def app(self) -> Application: return self._app - async def shutdown(self): + async def shutdown(self) -> None: await self._app.shutdown() - async def _make_server(self): + 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) + return self._app._make_handler(loop=loop, **self._kwargs) - async def _cleanup_server(self): + async def _cleanup_server(self) -> None: await self._app.cleanup() diff -Nru python-aiohttp-3.1.3/aiohttp/web_server.py python-aiohttp-3.5.1/aiohttp/web_server.py --- python-aiohttp-3.1.3/aiohttp/web_server.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/web_server.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,7 +1,12 @@ """Low level HTTP server.""" import asyncio +from typing import Any, Awaitable, Callable, Dict, List, Optional # noqa -from .web_protocol import RequestHandler +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 @@ -10,35 +15,44 @@ class Server: - def __init__(self, handler, *, request_factory=None, loop=None, **kwargs): - if loop is None: - loop = asyncio.get_event_loop() - self._loop = loop - self._connections = {} + 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): + def connections(self) -> List[RequestHandler]: return list(self._connections.keys()) - def connection_made(self, handler, transport): + def connection_made(self, handler: RequestHandler, + transport: asyncio.Transport) -> None: self._connections[handler] = transport - def connection_lost(self, handler, exc=None): + 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, payload, protocol, writer, task): + 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=None): + async def shutdown(self, timeout: Optional[float]=None) -> None: coros = [conn.shutdown(timeout) for conn in self._connections] await asyncio.gather(*coros, loop=self._loop) self._connections.clear() - def __call__(self): + def __call__(self) -> RequestHandler: return RequestHandler(self, loop=self._loop, **self._kwargs) diff -Nru python-aiohttp-3.1.3/aiohttp/_websocket.c python-aiohttp-3.5.1/aiohttp/_websocket.c --- python-aiohttp-3.1.3/aiohttp/_websocket.c 2018-04-13 10:01:36.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/_websocket.c 2018-12-24 20:59:11.000000000 +0000 @@ -1,4 +1,4 @@ -/* Generated by Cython 0.28.1 */ +/* Generated by Cython 0.29.2 */ /* BEGIN: Cython Metadata { @@ -20,7 +20,8 @@ #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_28_1" +#define CYTHON_ABI "0_29_2" +#define CYTHON_HEX_VERSION 0x001D02F0 #define CYTHON_FUTURE_DIVISION 0 #include #ifndef offsetof @@ -91,6 +92,10 @@ #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 @@ -128,6 +133,10 @@ #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 @@ -181,11 +190,17 @@ #define CYTHON_FAST_PYCALL 1 #endif #ifndef CYTHON_PEP489_MULTI_PHASE_INIT - #define CYTHON_PEP489_MULTI_PHASE_INIT (0 && PY_VERSION_HEX >= 0x03050000) + #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) @@ -195,6 +210,9 @@ #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 @@ -321,6 +339,9 @@ #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 @@ -334,15 +355,40 @@ #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))))) + ((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_USE_DICT_VERSIONS +#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);\ + }\ + } +#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 #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) @@ -450,8 +496,8 @@ #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)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) -#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) +#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 @@ -466,6 +512,7 @@ #define PyString_Type PyUnicode_Type #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact + #define PyObject_Unicode PyObject_Str #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) @@ -606,6 +653,9 @@ (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) @@ -662,8 +712,9 @@ #define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) #define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) -#define __Pyx_PyBool_FromLong(b) ((b) ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False)) +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)) @@ -744,7 +795,7 @@ 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)); + __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); @@ -770,7 +821,7 @@ static PyObject *__pyx_m = NULL; static PyObject *__pyx_d; static PyObject *__pyx_b; -static PyObject *__pyx_cython_runtime; +static PyObject *__pyx_cython_runtime = NULL; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; static PyObject *__pyx_empty_unicode; @@ -891,6 +942,18 @@ #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 */ @@ -908,6 +971,17 @@ /* 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 + /* PyThreadStateGet.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; @@ -995,21 +1069,6 @@ /* CheckBinaryVersion.proto */ static int __Pyx_check_binary_version(void); -/* PyIdentifierFromString.proto */ -#if !defined(__Pyx_PyIdentifier_FromString) -#if PY_MAJOR_VERSION < 3 - #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) -#else - #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) -#endif -#endif - -/* ModuleImport.proto */ -static PyObject *__Pyx_ImportModule(const char *name); - -/* TypeImport.proto */ -static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); - /* InitStrings.proto */ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); @@ -1110,6 +1169,7 @@ 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"; @@ -1131,6 +1191,7 @@ 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; @@ -1145,14 +1206,14 @@ * from libc.stdint cimport uint32_t, uint64_t, uintmax_t * * def _websocket_mask_cython(object mask, object data): # <<<<<<<<<<<<<< - * """Note, this function mutates it's `data` argument + * """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 it's `data` argument\n "; -static PyMethodDef __pyx_mdef_7aiohttp_10_websocket_1_websocket_mask_cython = {"_websocket_mask_cython", (PyCFunction)__pyx_pw_7aiohttp_10_websocket_1_websocket_mask_cython, METH_VARARGS|METH_KEYWORDS, __pyx_doc_7aiohttp_10_websocket__websocket_mask_cython}; +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; @@ -1516,7 +1577,7 @@ * from libc.stdint cimport uint32_t, uint64_t, uintmax_t * * def _websocket_mask_cython(object mask, object data): # <<<<<<<<<<<<<< - * """Note, this function mutates it's `data` argument + * """Note, this function mutates its `data` argument * """ */ @@ -1570,6 +1631,15 @@ 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}, @@ -1582,6 +1652,7 @@ {&__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}, @@ -1589,14 +1660,14 @@ {&__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 int __Pyx_InitCachedBuiltins(void) { +static CYTHON_SMALL_CODE int __Pyx_InitCachedBuiltins(void) { __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 53, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; } -static int __Pyx_InitCachedConstants(void) { +static CYTHON_SMALL_CODE int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); @@ -1604,7 +1675,7 @@ * from libc.stdint cimport uint32_t, uint64_t, uintmax_t * * def _websocket_mask_cython(object mask, object data): # <<<<<<<<<<<<<< - * """Note, this function mutates it's `data` argument + * """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, 9, __pyx_L1_error) @@ -1618,20 +1689,20 @@ return -1; } -static int __Pyx_InitGlobals(void) { +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 int __Pyx_modinit_global_init_code(void); /*proto*/ -static int __Pyx_modinit_variable_export_code(void); /*proto*/ -static int __Pyx_modinit_function_export_code(void); /*proto*/ -static int __Pyx_modinit_type_init_code(void); /*proto*/ -static int __Pyx_modinit_type_import_code(void); /*proto*/ -static int __Pyx_modinit_variable_import_code(void); /*proto*/ -static int __Pyx_modinit_function_import_code(void); /*proto*/ +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 @@ -1667,20 +1738,34 @@ static int __Pyx_modinit_type_import_code(void) { __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("__Pyx_modinit_type_import_code", 0); /*--- Type import code ---*/ - __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", - #if CYTHON_COMPILING_IN_PYPY + __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 - 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) __PYX_ERR(1, 9, __pyx_L1_error) - __pyx_ptype_7cpython_4bool_bool = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "bool", sizeof(PyBoolObject), 0); if (unlikely(!__pyx_ptype_7cpython_4bool_bool)) __PYX_ERR(2, 8, __pyx_L1_error) - __pyx_ptype_7cpython_7complex_complex = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "complex", sizeof(PyComplexObject), 0); if (unlikely(!__pyx_ptype_7cpython_7complex_complex)) __PYX_ERR(3, 15, __pyx_L1_error) + __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; } @@ -1715,15 +1800,6 @@ #define __Pyx_PyMODINIT_FUNC PyMODINIT_FUNC #endif #endif -#ifndef CYTHON_SMALL_CODE -#if defined(__clang__) - #define CYTHON_SMALL_CODE -#elif defined(__GNUC__) - #define CYTHON_SMALL_CODE __attribute__((optimize("Os"))) -#else - #define CYTHON_SMALL_CODE -#endif -#endif #if PY_MAJOR_VERSION < 3 @@ -1736,11 +1812,36 @@ { return PyModuleDef_Init(&__pyx_moduledef); } -static int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name) { +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)) { - result = PyDict_SetItemString(moddict, to_name, 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(); @@ -1749,8 +1850,10 @@ } return result; } -static PyObject* __pyx_pymod_create(PyObject *spec, CYTHON_UNUSED PyModuleDef *def) { +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"); @@ -1760,10 +1863,10 @@ 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__") < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__") < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__") < 0)) goto bad; - if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__") < 0)) 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); @@ -1771,14 +1874,18 @@ } -static int __pyx_pymod_exec__websocket(PyObject *__pyx_pyinit_module) +static CYTHON_SMALL_CODE int __pyx_pymod_exec__websocket(PyObject *__pyx_pyinit_module) #endif #endif { PyObject *__pyx_t_1 = NULL; __Pyx_RefNannyDeclarations #if CYTHON_PEP489_MULTI_PHASE_INIT - if (__pyx_m && __pyx_m == __pyx_pyinit_module) return 0; + 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 @@ -1793,6 +1900,9 @@ #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) @@ -1847,7 +1957,7 @@ if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif if (__pyx_module_is_main_aiohttp___websocket) { - if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) + 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 { @@ -1878,7 +1988,7 @@ * from libc.stdint cimport uint32_t, uint64_t, uintmax_t * * def _websocket_mask_cython(object mask, object data): # <<<<<<<<<<<<<< - * """Note, this function mutates it's `data` argument + * """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, 9, __pyx_L1_error) @@ -1903,9 +2013,9 @@ __Pyx_XDECREF(__pyx_t_1); if (__pyx_m) { if (__pyx_d) { - __Pyx_AddTraceback("init aiohttp._websocket", 0, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("init aiohttp._websocket", __pyx_clineno, __pyx_lineno, __pyx_filename); } - Py_DECREF(__pyx_m); __pyx_m = 0; + Py_CLEAR(__pyx_m); } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "init aiohttp._websocket"); } @@ -1926,9 +2036,9 @@ static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; void *r = NULL; - m = PyImport_ImportModule((char *)modname); + m = PyImport_ImportModule(modname); if (!m) goto end; - p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); + p = PyObject_GetAttrString(m, "RefNannyAPI"); if (!p) goto end; r = PyLong_AsVoidPtr(p); end: @@ -2116,7 +2226,7 @@ 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))); + 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, @@ -2124,16 +2234,15 @@ caller loses its exception */ assert(!PyErr_Occurred()); if ((PY_VERSION_HEX < 0x030700A0) || unlikely(flags & METH_KEYWORDS)) { - return (*((__Pyx_PyCFunctionFastWithKeywords)meth)) (self, args, nargs, NULL); + return (*((__Pyx_PyCFunctionFastWithKeywords)(void*)meth)) (self, args, nargs, NULL); } else { - return (*((__Pyx_PyCFunctionFast)meth)) (self, args, nargs); + return (*((__Pyx_PyCFunctionFast)(void*)meth)) (self, args, nargs); } } #endif /* PyFunctionFastCall */ #if CYTHON_FAST_PYCALL -#include "frameobject.h" static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na, PyObject *globals) { PyFrameObject *f; @@ -2151,7 +2260,7 @@ if (f == NULL) { return NULL; } - fastlocals = f->f_localsplus; + fastlocals = __Pyx_PyFrame_GetLocalsplus(f); for (i = 0; i < na; i++) { Py_INCREF(*args); fastlocals[i] = *args++; @@ -2331,6 +2440,67 @@ } #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 + /* PyErrFetchRestore */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { @@ -2357,17 +2527,22 @@ /* CLineInTraceback */ #ifndef CYTHON_CLINE_IN_TRACEBACK -static int __Pyx_CLineForTraceback(CYTHON_UNUSED PyThreadState *tstate, int c_line) { +static int __Pyx_CLineForTraceback(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)) { - use_cline = __Pyx_PyDict_GetItemStr(*cython_runtime_dict, __pyx_n_s_cline_in_traceback); + __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 { @@ -2384,7 +2559,7 @@ c_line = 0; PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False); } - else if (PyObject_Not(use_cline) != 0) { + else if (use_cline == Py_False || (use_cline != Py_True && PyObject_Not(use_cline) != 0)) { c_line = 0; } __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); @@ -2559,7 +2734,7 @@ /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { - const long neg_one = (long) -1, const_zero = (long) 0; + const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(long) < sizeof(long)) { @@ -2612,7 +2787,7 @@ /* CIntFromPy */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { - const long neg_one = (long) -1, const_zero = (long) 0; + const long neg_one = (long) ((long) 0 - (long) 1), const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { @@ -2801,7 +2976,7 @@ /* CIntFromPy */ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { - const int neg_one = (int) -1, const_zero = (int) 0; + const int neg_one = (int) ((int) 0 - (int) 1), const_zero = (int) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { @@ -3044,14 +3219,42 @@ 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_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 (!strict && (size_t)basicsize > size) { - PyOS_snprintf(warning, sizeof(warning), - "%s.%s size changed, may indicate binary incompatibility. Expected %zd, got %zd", - module_name, class_name, basicsize, size); - if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; - } - else if ((size_t)basicsize != size) { - PyErr_Format(PyExc_ValueError, - "%.200s.%.200s has the wrong size, try recompiling. Expected %zd, got %zd", - module_name, class_name, basicsize, size); - goto bad; - } - return (PyTypeObject *)result; -bad: - Py_XDECREF(py_module); - Py_XDECREF(result); - return NULL; -} -#endif - /* InitStrings */ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { @@ -3269,6 +3389,13 @@ 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)) { @@ -3346,7 +3473,7 @@ if (sizeof(Py_ssize_t) >= sizeof(long)) return PyInt_AS_LONG(b); else - return PyInt_AsSsize_t(x); + return PyInt_AsSsize_t(b); } #endif if (likely(PyLong_CheckExact(b))) { @@ -3400,6 +3527,9 @@ 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); } diff -Nru python-aiohttp-3.1.3/aiohttp/_websocket.pyx python-aiohttp-3.5.1/aiohttp/_websocket.pyx --- python-aiohttp-3.1.3/aiohttp/_websocket.pyx 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/_websocket.pyx 2018-12-24 20:58:54.000000000 +0000 @@ -7,7 +7,7 @@ from libc.stdint cimport uint32_t, uint64_t, uintmax_t def _websocket_mask_cython(object mask, object data): - """Note, this function mutates it's `data` argument + """Note, this function mutates its `data` argument """ cdef: Py_ssize_t data_len, i diff -Nru python-aiohttp-3.1.3/aiohttp/web_urldispatcher.py python-aiohttp-3.5.1/aiohttp/web_urldispatcher.py --- python-aiohttp-3.1.3/aiohttp/web_urldispatcher.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/web_urldispatcher.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,112 +1,87 @@ import abc import asyncio import base64 -import collections import hashlib import inspect import keyword import os import re import warnings -from collections.abc import Container, Iterable, Sequence, Sized 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, # noqa + Dict, Generator, Iterable, Iterator, List, Mapping, + Optional, Set, Sized, Tuple, Union, cast) -import attr from yarl import URL from . import hdrs from .abc import AbstractMatchInfo, AbstractRouter, AbstractView +from .helpers import DEBUG from .http import HttpVersion11 -from .web_exceptions import (HTTPExpectationFailed, HTTPForbidden, - HTTPMethodNotAllowed, HTTPNotFound) +from .typedefs import PathLike +from .web_exceptions import (HTTPException, HTTPExpectationFailed, + HTTPForbidden, HTTPMethodNotAllowed, HTTPNotFound) from .web_fileresponse import FileResponse -from .web_response import Response +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', 'RouteDef', 'StaticDef', 'RouteTableDef', - 'head', 'get', 'post', 'patch', 'put', 'delete', 'route', 'view', - 'static') + 'StaticResource', 'View') + + +if TYPE_CHECKING: # pragma: no cover + from .web_app import Application # noqa + BaseDict = Dict[str, str] +else: + BaseDict = dict HTTP_METHOD_RE = re.compile(r"^[0-9A-Za-z!#\$%&'\*\+\-\.\^_`\|~]+$") ROUTE_RE = re.compile(r'(\{[_a-zA-Z][^{}]*(?:\{[^{}]*\}[^{}]*)*\})') PATH_SEP = re.escape('/') -class AbstractRouteDef(abc.ABC): - @abc.abstractmethod - def register(self, router): - pass # pragma: no cover - - -@attr.s(frozen=True, repr=False, slots=True) -class RouteDef(AbstractRouteDef): - method = attr.ib(type=str) - path = attr.ib(type=str) - handler = attr.ib() - kwargs = attr.ib() - - def __repr__(self): - info = [] - for name, value in sorted(self.kwargs.items()): - info.append(", {}={!r}".format(name, value)) - return (" {handler.__name__!r}" - "{info}>".format(method=self.method, path=self.path, - handler=self.handler, info=''.join(info))) - - def register(self, router): - if self.method in hdrs.METH_ALL: - reg = getattr(router, 'add_'+self.method.lower()) - reg(self.path, self.handler, **self.kwargs) - else: - router.add_route(self.method, self.path, self.handler, - **self.kwargs) +_WebHandler = Callable[[Request], Awaitable[StreamResponse]] +_ExpectHandler = Callable[[Request], Awaitable[None]] +_Resolve = Tuple[Optional[AbstractMatchInfo], Set[str]] -@attr.s(frozen=True, repr=False, slots=True) -class StaticDef(AbstractRouteDef): - prefix = attr.ib(type=str) - path = attr.ib(type=str) - kwargs = attr.ib() +class AbstractResource(Sized, Iterable['AbstractRoute']): - def __repr__(self): - info = [] - for name, value in sorted(self.kwargs.items()): - info.append(", {}={!r}".format(name, value)) - return (" {path}" - "{info}>".format(prefix=self.prefix, path=self.path, - info=''.join(info))) - - def register(self, router): - router.add_static(self.prefix, self.path, **self.kwargs) - - -class AbstractResource(Sized, Iterable): - - def __init__(self, *, name=None): + def __init__(self, *, name: Optional[str]=None) -> None: self._name = name @property - def name(self): + 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): + def url_for(self, **kwargs: str) -> URL: """Construct url for resource with additional params.""" @abc.abstractmethod # pragma: no branch - async def resolve(self, request): + async def resolve(self, request: Request) -> _Resolve: """Resolve resource Return (UrlMappingMatchInfo, allowed_methods) pair.""" @abc.abstractmethod - def add_prefix(self, prefix): + def add_prefix(self, prefix: str) -> None: """Add a prefix to processed URLs. Required for subapplications support. @@ -114,22 +89,23 @@ """ @abc.abstractmethod - def get_info(self): + def get_info(self) -> Dict[str, Any]: """Return a dict with additional info useful for introspection""" - def freeze(self): + def freeze(self) -> None: pass @abc.abstractmethod - def raw_match(self, path): + def raw_match(self, path: str) -> bool: """Perform a raw match against path""" class AbstractRoute(abc.ABC): - def __init__(self, method, handler, *, - expect_handler=None, - resource=None): + def __init__(self, method: str, + handler: Union[_WebHandler, AbstractView], *, + expect_handler: _ExpectHandler=None, + resource: AbstractResource=None) -> None: if expect_handler is None: expect_handler = _default_expect_handler @@ -155,8 +131,8 @@ "use async ones", DeprecationWarning) @wraps(handler) - async def handler_wrapper(*args, **kwargs): - result = old_handler(*args, **kwargs) + async def handler_wrapper(request: Request) -> StreamResponse: + result = old_handler(request) if asyncio.iscoroutine(result): result = await result return result @@ -169,82 +145,87 @@ self._resource = resource @property - def method(self): + def method(self) -> str: return self._method @property - def handler(self): + def handler(self) -> _WebHandler: return self._handler @property @abc.abstractmethod - def name(self): + def name(self) -> Optional[str]: """Optional route's name, always equals to resource's name.""" @property - def resource(self): + def resource(self) -> Optional[AbstractResource]: return self._resource @abc.abstractmethod - def get_info(self): + def get_info(self) -> Dict[str, Any]: """Return a dict with additional info useful for introspection""" @abc.abstractmethod # pragma: no branch - def url_for(self, *args, **kwargs): + def url_for(self, *args: str, **kwargs: str) -> URL: """Construct url for route with additional params.""" - async def handle_expect_header(self, request): - return await self._expect_handler(request) + async def handle_expect_header(self, request: Request) -> None: + await self._expect_handler(request) -class UrlMappingMatchInfo(dict, AbstractMatchInfo): +class UrlMappingMatchInfo(BaseDict, AbstractMatchInfo): - def __init__(self, match_dict, route): + def __init__(self, match_dict: Dict[str, str], route: AbstractRoute): super().__init__(match_dict) self._route = route - self._apps = () - self._current_app = None + self._apps = [] # type: List[Application] + self._current_app = None # type: Optional[Application] self._frozen = False @property - def handler(self): + def handler(self) -> _WebHandler: return self._route.handler @property - def route(self): + def route(self) -> AbstractRoute: return self._route @property - def expect_handler(self): + def expect_handler(self) -> _ExpectHandler: return self._route.handle_expect_header @property - def http_exception(self): + def http_exception(self) -> Optional[HTTPException]: return None - def get_info(self): + def get_info(self) -> Dict[str, str]: return self._route.get_info() @property - def apps(self): - return self._apps + def apps(self) -> Tuple['Application', ...]: + return tuple(self._apps) - def add_app(self, app): + 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 = (app,) + self._apps + self._apps.insert(0, app) @property - def current_app(self): - return self._current_app + def current_app(self) -> 'Application': + app = self._current_app + assert app is not None + return app @contextmanager - def set_current_app(self, app): - assert app in self._apps, ( - "Expected one of the following apps {!r}, got {!r}" - .format(self._apps, app)) + 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: @@ -252,29 +233,29 @@ finally: self._current_app = prev - def freeze(self): + def freeze(self) -> None: self._frozen = True - def __repr__(self): + def __repr__(self) -> str: return "".format(super().__repr__(), self._route) class MatchInfoError(UrlMappingMatchInfo): - def __init__(self, http_exception): + def __init__(self, http_exception: HTTPException) -> None: self._exception = http_exception super().__init__({}, SystemRoute(self._exception)) @property - def http_exception(self): + def http_exception(self) -> HTTPException: return self._exception - def __repr__(self): + def __repr__(self) -> str: return "".format(self._exception.status, self._exception.reason) -async def _default_expect_handler(request): +async def _default_expect_handler(request: Request) -> None: """Default handler for Expect header. Just send "100 Continue" to client. @@ -283,20 +264,21 @@ 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", drain=False) + 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=None): + def __init__(self, *, name: Optional[str]=None) -> None: super().__init__(name=name) - self._routes = [] + self._routes = [] # type: List[ResourceRoute] - def add_route(self, method, handler, *, - expect_handler=None): + def add_route(self, method: str, + handler: Union[AbstractView, _WebHandler], *, + expect_handler: Optional[_ExpectHandler]=None + ) -> 'ResourceRoute': for route_obj in self._routes: if route_obj.method == method or route_obj.method == hdrs.METH_ANY: @@ -309,13 +291,13 @@ self.register_route(route_obj) return route_obj - def register_route(self, route): + def register_route(self, route: 'ResourceRoute') -> None: assert isinstance(route, ResourceRoute), \ 'Instance of Route class is required, got {!r}'.format(route) self._routes.append(route) - async def resolve(self, request): - allowed_methods = set() + 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: @@ -332,10 +314,14 @@ else: return None, allowed_methods - def __len__(self): + @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): + def __iter__(self) -> Iterator[AbstractRoute]: return iter(self._routes) # TODO: implement all abstract methods @@ -343,41 +329,45 @@ class PlainResource(Resource): - def __init__(self, path, *, name=None): + def __init__(self, path: str, *, name: Optional[str]=None) -> None: super().__init__(name=name) assert not path or path.startswith('/') self._path = path - def freeze(self): + @property + def canonical(self) -> str: + return self._path + + def freeze(self) -> None: if not self._path: self._path = '/' - def add_prefix(self, prefix): + 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): + 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): + def raw_match(self, path: str) -> bool: return self._path == path - def get_info(self): + def get_info(self) -> Dict[str, Any]: return {'path': self._path} - def url_for(self): + def url_for(self) -> URL: # type: ignore return URL.build(path=self._path, encoded=True) - def __repr__(self): + def __repr__(self) -> str: name = "'" + self.name + "' " if self.name is not None else "" - return "".format(name=name, + path=self._path) class DynamicResource(Resource): @@ -387,7 +377,7 @@ r'\{(?P[_a-zA-Z][_a-zA-Z0-9]*):(?P.+)\}') GOOD = r'[^{}/]+' - def __init__(self, path, *, name=None): + def __init__(self, path: str, *, name: Optional[str]=None) -> None: super().__init__(name=name) pattern = '' formatter = '' @@ -421,14 +411,18 @@ self._pattern = compiled self._formatter = formatter - def add_prefix(self, prefix): + @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): + def _match(self, path: str) -> Optional[Dict[str, str]]: match = self._pattern.fullmatch(path) if match is None: return None @@ -436,39 +430,43 @@ return {key: URL.build(path=value, encoded=True).path for key, value in match.groupdict().items()} - def raw_match(self, path): + def raw_match(self, path: str) -> bool: return self._formatter == path - def get_info(self): + def get_info(self) -> Dict[str, Any]: return {'formatter': self._formatter, 'pattern': self._pattern} - def url_for(self, **parts): + def url_for(self, **parts: str) -> URL: url = self._formatter.format_map({k: URL.build(path=v).raw_path for k, v in parts.items()}) return URL.build(path=url) - def __repr__(self): + 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, *, name=None): + 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 = URL.build(path=prefix).raw_path - def add_prefix(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 - def raw_match(self, prefix): + def raw_match(self, prefix: str) -> bool: return False # TODO: impl missing abstract methods @@ -477,10 +475,12 @@ class StaticResource(PrefixResource): VERSION_KEY = 'v' - def __init__(self, prefix, directory, *, name=None, - expect_handler=None, chunk_size=256 * 1024, - show_index=False, follow_symlinks=False, - append_version=False): + 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) @@ -505,7 +505,8 @@ 'HEAD': ResourceRoute('HEAD', self._handle, self, expect_handler=expect_handler)} - def url_for(self, *, filename, append_version=None): + def url_for(self, *, filename: Union[str, Path], # type: ignore + append_version: Optional[bool]=None) -> URL: if append_version is None: append_version = self._append_version if isinstance(filename, Path): @@ -517,7 +518,7 @@ # filename is not encoded url = URL.build(path=self._prefix + filename) - if append_version is True: + if append_version: try: if filename.startswith('/'): filename = filename[1:] @@ -539,24 +540,24 @@ return url @staticmethod - def _get_file_hash(byte_array): + 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): + def get_info(self) -> Dict[str, Any]: return {'directory': self._directory, 'prefix': self._prefix} - def set_options_route(self, handler): + def set_options_route(self, handler: _WebHandler) -> 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): + async def resolve(self, request: Request) -> _Resolve: path = request.rel_url.raw_path method = request.method allowed_methods = set(self._routes) @@ -571,13 +572,13 @@ return (UrlMappingMatchInfo(match_dict, self._routes[method]), allowed_methods) - def __len__(self): + def __len__(self) -> int: return len(self._routes) - def __iter__(self): + def __iter__(self) -> Iterator[AbstractRoute]: return iter(self._routes.values()) - async def _handle(self, request): + async def _handle(self, request: Request) -> StreamResponse: rel_url = request.match_info['filename'] try: filename = Path(rel_url) @@ -599,24 +600,22 @@ request.app.logger.exception(error) raise HTTPNotFound() from error - # on opening a dir, load it's contents if allowed + # on opening a dir, load its contents if allowed if filepath.is_dir(): if self._show_index: try: - ret = Response(text=self._directory_as_html(filepath), - content_type="text/html") + return Response(text=self._directory_as_html(filepath), + content_type="text/html") except PermissionError: raise HTTPForbidden() else: raise HTTPForbidden() elif filepath.is_file(): - ret = FileResponse(filepath, chunk_size=self._chunk_size) + return FileResponse(filepath, chunk_size=self._chunk_size) else: raise HTTPNotFound - return ret - - def _directory_as_html(self, filepath): + def _directory_as_html(self, filepath: Path) -> str: # returns directory's index as html # sanity check @@ -651,34 +650,34 @@ return html - def __repr__(self): + def __repr__(self) -> str: name = "'" + self.name + "'" if self.name is not None else "" - return " {directory!r}".format( + return " {directory!r}>".format( name=name, path=self._prefix, directory=self._directory) class PrefixedSubAppResource(PrefixResource): - def __init__(self, prefix, app): + 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): + 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, **kwargs): + def url_for(self, *args: str, **kwargs: str) -> URL: raise RuntimeError(".url_for() is not supported " "by sub-application root") - def get_info(self): + def get_info(self) -> Dict[str, Any]: return {'app': self._app, 'prefix': self._prefix} - async def resolve(self, request): + async def resolve(self, request: Request) -> _Resolve: if not request.url.raw_path.startswith(self._prefix): return None, set() match_info = await self._app.router.resolve(request) @@ -689,76 +688,180 @@ methods = set() return match_info, methods - def __len__(self): + def __len__(self) -> int: return len(self._app.router.routes()) - def __iter__(self): + def __iter__(self) -> Iterator[AbstractRoute]: return iter(self._app.router.routes()) - def __repr__(self): + 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) -> Dict[str, Any]: + """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) + if not all( + self.re_part.fullmatch(x) + for x in url.raw_host.split(".")): # type: ignore + raise ValueError("Domain not valid") + if url.port == 80: + return url.raw_host # type: ignore + return '{}:{}'.format(url.raw_host, url.port) + + async def match(self, request: Request) -> bool: + host = request.headers.get(hdrs.HOST) + return host and self.match_domain(host) + + def match_domain(self, host: str) -> bool: + return host.lower() == self._domain + + def get_info(self) -> Dict[str, Any]: + 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) -> Dict[str, Any]: + 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, handler, resource, *, - expect_handler=None): + def __init__(self, method: str, + handler: Union[_WebHandler, AbstractView], + resource: AbstractResource, *, + expect_handler: Optional[_ExpectHandler]=None) -> None: super().__init__(method, handler, expect_handler=expect_handler, resource=resource) - def __repr__(self): + def __repr__(self) -> str: return " {handler!r}".format( method=self.method, resource=self._resource, handler=self.handler) @property - def name(self): - return self._resource.name + def name(self) -> Optional[str]: + return self._resource.name # type: ignore - def url_for(self, *args, **kwargs): + def url_for(self, *args: str, **kwargs: str) -> URL: """Construct url for route with additional params.""" - return self._resource.url_for(*args, **kwargs) + return self._resource.url_for(*args, **kwargs) # type: ignore - def get_info(self): - return self._resource.get_info() + def get_info(self) -> Dict[str, Any]: + return self._resource.get_info() # type: ignore class SystemRoute(AbstractRoute): - def __init__(self, http_exception): - super().__init__(hdrs.METH_ANY, self._handler) + def __init__(self, http_exception: HTTPException) -> None: + super().__init__(hdrs.METH_ANY, self._handle) self._http_exception = http_exception - def url_for(self, *args, **kwargs): + def url_for(self, *args: str, **kwargs: str) -> URL: raise RuntimeError(".url_for() is not allowed for SystemRoute") @property - def name(self): + def name(self) -> Optional[str]: return None - def get_info(self): + def get_info(self) -> Dict[str, Any]: return {'http_exception': self._http_exception} - async def _handler(self, request): + async def _handle(self, request: Request) -> StreamResponse: raise self._http_exception @property - def status(self): + def status(self) -> int: return self._http_exception.status @property - def reason(self): + def reason(self) -> str: return self._http_exception.reason - def __repr__(self): + def __repr__(self) -> str: return "".format(self=self) class View(AbstractView): - async def _iter(self): + async def _iter(self) -> StreamResponse: if self.request.method not in hdrs.METH_ALL: self._raise_allowed_methods() method = getattr(self, self.request.method.lower(), None) @@ -767,60 +870,62 @@ resp = await method() return resp - def __await__(self): + def __await__(self) -> Generator[Any, None, StreamResponse]: return self._iter().__await__() - def _raise_allowed_methods(self): + 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, Container): +class ResourcesView(Sized, + Iterable[AbstractResource], + Container[AbstractResource]): - def __init__(self, resources): + def __init__(self, resources: List[AbstractResource]) -> None: self._resources = resources - def __len__(self): + def __len__(self) -> int: return len(self._resources) - def __iter__(self): + def __iter__(self) -> Iterator[AbstractResource]: yield from self._resources - def __contains__(self, resource): + def __contains__(self, resource: object) -> bool: return resource in self._resources -class RoutesView(Sized, Iterable, Container): +class RoutesView(Sized, Iterable[AbstractRoute], Container[AbstractRoute]): - def __init__(self, resources): - self._routes = [] + def __init__(self, resources: List[AbstractResource]): + self._routes = [] # type: List[AbstractRoute] for resource in resources: - for route_obj in resource: - self._routes.append(route_obj) + for route in resource: + self._routes.append(route) - def __len__(self): + def __len__(self) -> int: return len(self._routes) - def __iter__(self): + def __iter__(self) -> Iterator[AbstractRoute]: yield from self._routes - def __contains__(self, route_obj): - return route_obj in self._routes + def __contains__(self, route: object) -> bool: + return route in self._routes -class UrlDispatcher(AbstractRouter, collections.abc.Mapping): +class UrlDispatcher(AbstractRouter, Mapping[str, AbstractResource]): NAME_SPLIT_RE = re.compile(r'[.:-]') - def __init__(self): + def __init__(self) -> None: super().__init__() - self._resources = [] - self._named_resources = {} + self._resources = [] # type: List[AbstractResource] + self._named_resources = {} # type: Dict[str, AbstractResource] - async def resolve(self, request): + async def resolve(self, request: Request) -> AbstractMatchInfo: method = request.method - allowed_methods = set() + allowed_methods = set() # type: Set[str] for resource in self._resources: match_dict, allowed = await resource.resolve(request) @@ -835,28 +940,28 @@ else: return MatchInfoError(HTTPNotFound()) - def __iter__(self): + def __iter__(self) -> Iterator[str]: return iter(self._named_resources) - def __len__(self): + def __len__(self) -> int: return len(self._named_resources) - def __contains__(self, name): - return name in self._named_resources + def __contains__(self, resource: object) -> bool: + return resource in self._named_resources - def __getitem__(self, name): + def __getitem__(self, name: str) -> AbstractResource: return self._named_resources[name] - def resources(self): + def resources(self) -> ResourcesView: return ResourcesView(self._resources) - def routes(self): + def routes(self) -> RoutesView: return RoutesView(self._resources) - def named_resources(self): + def named_resources(self) -> Mapping[str, AbstractResource]: return MappingProxyType(self._named_resources) - def register_resource(self, resource): + def register_resource(self, resource: AbstractResource) -> None: assert isinstance(resource, AbstractResource), \ 'Instance of AbstractResource class is required, got {!r}'.format( resource) @@ -881,14 +986,15 @@ self._named_resources[name] = resource self._resources.append(resource) - def add_resource(self, path, *, name=None): + 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 resource + return cast(Resource, resource) if not ('{' in path or '}' in path or ROUTE_RE.search(path)): url = URL.build(path=path) resource = PlainResource(url.raw_path, name=name) @@ -898,16 +1004,21 @@ self.register_resource(resource) return resource - def add_route(self, method, path, handler, - *, name=None, expect_handler=None): + def add_route(self, method: str, path: str, + handler: Union[_WebHandler, 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, path, *, name=None, expect_handler=None, - chunk_size=256 * 1024, - show_index=False, follow_symlinks=False, - append_version=False): + 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 @@ -927,13 +1038,23 @@ self.register_resource(resource) return resource - def add_head(self, path, handler, **kwargs): + def add_head(self, path: str, handler: _WebHandler, + **kwargs: Any) -> AbstractRoute: """ Shortcut for add_route with method HEAD """ return self.add_route(hdrs.METH_HEAD, path, handler, **kwargs) - def add_get(self, path, handler, *, name=None, allow_head=True, **kwargs): + def add_options(self, path: str, handler: _WebHandler, + **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: _WebHandler, *, + 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 @@ -943,133 +1064,50 @@ resource.add_route(hdrs.METH_HEAD, handler, **kwargs) return resource.add_route(hdrs.METH_GET, handler, **kwargs) - def add_post(self, path, handler, **kwargs): + def add_post(self, path: str, handler: _WebHandler, + **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, handler, **kwargs): + def add_put(self, path: str, handler: _WebHandler, + **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, handler, **kwargs): + def add_patch(self, path: str, handler: _WebHandler, + **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, handler, **kwargs): + def add_delete(self, path: str, handler: _WebHandler, + **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, handler, **kwargs): + def add_view(self, path: str, handler: 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): + def freeze(self) -> None: super().freeze() for resource in self._resources: resource.freeze() - def add_routes(self, routes): + def add_routes(self, routes: Iterable[AbstractRouteDef]) -> None: """Append routes to route table. Parameter should be a sequence of RouteDef objects. """ - for route_obj in routes: - route_obj.register(self) - - -def route(method, path, handler, **kwargs): - return RouteDef(method, path, handler, kwargs) - - -def head(path, handler, **kwargs): - return route(hdrs.METH_HEAD, path, handler, **kwargs) - - -def get(path, handler, *, name=None, allow_head=True, **kwargs): - return route(hdrs.METH_GET, path, handler, name=name, - allow_head=allow_head, **kwargs) - - -def post(path, handler, **kwargs): - return route(hdrs.METH_POST, path, handler, **kwargs) - - -def put(path, handler, **kwargs): - return route(hdrs.METH_PUT, path, handler, **kwargs) - - -def patch(path, handler, **kwargs): - return route(hdrs.METH_PATCH, path, handler, **kwargs) - - -def delete(path, handler, **kwargs): - return route(hdrs.METH_DELETE, path, handler, **kwargs) - - -def view(path, handler, **kwargs): - return route(hdrs.METH_ANY, path, handler, **kwargs) - - -def static(prefix, path, **kwargs): - return StaticDef(prefix, path, kwargs) - - -class RouteTableDef(Sequence): - """Route definition table""" - def __init__(self): - self._items = [] - - def __repr__(self): - return "".format(len(self._items)) - - def __getitem__(self, index): - return self._items[index] - - def __iter__(self): - return iter(self._items) - - def __len__(self): - return len(self._items) - - def __contains__(self, item): - return item in self._items - - def route(self, method, path, **kwargs): - def inner(handler): - self._items.append(RouteDef(method, path, handler, kwargs)) - return handler - return inner - - def head(self, path, **kwargs): - return self.route(hdrs.METH_HEAD, path, **kwargs) - - def get(self, path, **kwargs): - return self.route(hdrs.METH_GET, path, **kwargs) - - def post(self, path, **kwargs): - return self.route(hdrs.METH_POST, path, **kwargs) - - def put(self, path, **kwargs): - return self.route(hdrs.METH_PUT, path, **kwargs) - - def patch(self, path, **kwargs): - return self.route(hdrs.METH_PATCH, path, **kwargs) - - def delete(self, path, **kwargs): - return self.route(hdrs.METH_DELETE, path, **kwargs) - - def view(self, path, **kwargs): - return self.route(hdrs.METH_ANY, path, **kwargs) - - def static(self, prefix, path, **kwargs): - self._items.append(StaticDef(prefix, path, kwargs)) + for route_def in routes: + route_def.register(self) diff -Nru python-aiohttp-3.1.3/aiohttp/web_ws.py python-aiohttp-3.5.1/aiohttp/web_ws.py --- python-aiohttp-3.1.3/aiohttp/web_ws.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/web_ws.py 2018-12-24 20:58:54.000000000 +0000 @@ -3,19 +3,23 @@ import binascii import hashlib import json +from typing import Any, Iterable, Optional, Tuple 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, WSMessage, WSMsgType, ws_ext_gen, ws_ext_parse) from .log import ws_logger from .streams import EofStream, FlowControlDataQueue +from .typedefs import JSONDecoder, JSONEncoder from .web_exceptions import HTTPBadRequest, HTTPException, HTTPMethodNotAllowed +from .web_request import BaseRequest from .web_response import StreamResponse @@ -27,30 +31,32 @@ @attr.s(frozen=True, slots=True) class WebSocketReady: ok = attr.ib(type=bool) - protocol = attr.ib(type=str) + protocol = attr.ib(type=Optional[str]) - def __bool__(self): + def __bool__(self) -> bool: return self.ok class WebSocketResponse(StreamResponse): def __init__(self, *, - timeout=10.0, receive_timeout=None, - autoclose=True, autoping=True, heartbeat=None, - protocols=(), compress=True): + 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 - self._writer = None - self._reader = None + 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 - self._loop = None - self._waiting = None - self._exception = None + 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 @@ -61,8 +67,9 @@ self._pong_heartbeat = heartbeat / 2.0 self._pong_response_cb = None self._compress = compress + self._max_msg_size = max_msg_size - def _cancel_heartbeat(self): + def _cancel_heartbeat(self) -> None: if self._pong_response_cb is not None: self._pong_response_cb.cancel() self._pong_response_cb = None @@ -71,44 +78,48 @@ self._heartbeat_cb.cancel() self._heartbeat_cb = None - def _reset_heartbeat(self): + 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): + 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()) + self._loop.create_task(self._writer.ping()) # type: ignore 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): + 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 = 1006 self._exception = asyncio.TimeoutError() self._req.transport.close() - async def prepare(self, request): + 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): + def _handshake(self, request: BaseRequest) -> Tuple['CIMultiDict[str]', + str, + bool, + bool]: headers = request.headers if request.method != hdrs.METH_GET: raise HTTPMethodNotAllowed(request.method, [hdrs.METH_GET]) @@ -157,14 +168,15 @@ accept_val = base64.b64encode( hashlib.sha1(key.encode() + WS_KEY).digest()).decode() - response_headers = CIMultiDict({hdrs.UPGRADE: 'websocket', - hdrs.CONNECTION: 'upgrade', - hdrs.TRANSFER_ENCODING: 'chunked', - hdrs.SEC_WEBSOCKET_ACCEPT: accept_val}) + response_headers = CIMultiDict( # type: ignore + {hdrs.UPGRADE: 'websocket', + hdrs.CONNECTION: 'upgrade', + hdrs.TRANSFER_ENCODING: 'chunked', + hdrs.SEC_WEBSOCKET_ACCEPT: accept_val}) notakeover = False - compress = self._compress - if compress: + 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 @@ -176,10 +188,13 @@ if protocol: response_headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = protocol - return (response_headers, protocol, compress, notakeover) + return (response_headers, # type: ignore + protocol, + compress, + notakeover) - def _pre_start(self, request): - self._loop = request.loop + def _pre_start(self, request: BaseRequest) -> Tuple[str, WebSocketWriter]: + self._loop = request._loop headers, protocol, compress, notakeover = self._handshake( request) @@ -190,24 +205,29 @@ self.headers.update(headers) self.force_close() self._compress = compress + transport = request._protocol.transport + assert transport is not None writer = WebSocketWriter(request._protocol, - request._protocol.transport, + transport, compress=compress, notakeover=notakeover) return protocol, writer - def _post_start(self, request, protocol, writer): + def _post_start(self, request: BaseRequest, + protocol: str, writer: WebSocketWriter) -> None: self._ws_protocol = protocol self._writer = writer + loop = self._loop + assert loop is not None self._reader = FlowControlDataQueue( - request._protocol, limit=2 ** 16, loop=self._loop) + request._protocol, limit=2 ** 16, loop=loop) request.protocol.set_parser(WebSocketReader( - self._reader, compress=self._compress)) + self._reader, self._max_msg_size, compress=self._compress)) # disable HTTP keepalive for WebSocket request.protocol.keep_alive(False) - def can_prepare(self, request): + def can_prepare(self, request: BaseRequest) -> WebSocketReady: if self._writer is not None: raise RuntimeError('Already started') try: @@ -218,43 +238,44 @@ return WebSocketReady(True, protocol) @property - def closed(self): + def closed(self) -> bool: return self._closed @property - def close_code(self): + def close_code(self) -> Optional[int]: return self._close_code @property - def ws_protocol(self): + def ws_protocol(self) -> Optional[str]: return self._ws_protocol @property - def compress(self): + def compress(self) -> bool: return self._compress - def exception(self): + def exception(self) -> Optional[BaseException]: return self._exception - async def ping(self, message='b'): + 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='b'): + 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, compress=None): + 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, compress=None): + 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)): @@ -262,10 +283,11 @@ type(data)) await self._writer.send(data, binary=True, compress=compress) - async def send_json(self, data, compress=None, *, dumps=json.dumps): + 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): + async def write_eof(self) -> None: # type: ignore if self._eof_sent: return if self._payload_writer is None: @@ -274,23 +296,27 @@ await self.close() self._eof_sent = True - async def close(self, *, code=1000, message=b''): + async def close(self, *, code: int=1000, 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: - self._reader.feed_data(WS_CLOSING_MESSAGE, 0) + reader.feed_data(WS_CLOSING_MESSAGE, 0) await self._waiting if not self._closed: self._closed = True try: await self._writer.close(code, message) - await self._payload_writer.drain() + writer = self._payload_writer + assert writer is not None + await writer.drain() except (asyncio.CancelledError, asyncio.TimeoutError): self._close_code = 1006 raise @@ -302,9 +328,11 @@ if self._closing: return True + reader = self._reader + assert reader is not None try: with async_timeout.timeout(self._timeout, loop=self._loop): - msg = await self._reader.read() + msg = await reader.read() except asyncio.CancelledError: self._close_code = 1006 raise @@ -323,10 +351,12 @@ else: return False - async def receive(self, timeout=None): + 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( @@ -341,7 +371,7 @@ return WS_CLOSING_MESSAGE try: - self._waiting = self._loop.create_future() + self._waiting = loop.create_future() try: with async_timeout.timeout( timeout or self._receive_timeout, loop=self._loop): @@ -384,7 +414,7 @@ return msg - async def receive_str(self, *, timeout=None): + async def receive_str(self, *, timeout: Optional[float]=None) -> str: msg = await self.receive(timeout) if msg.type != WSMsgType.TEXT: raise TypeError( @@ -392,7 +422,7 @@ msg.type, msg.data)) return msg.data - async def receive_bytes(self, *, timeout=None): + async def receive_bytes(self, *, timeout: Optional[float]=None) -> bytes: msg = await self.receive(timeout) if msg.type != WSMsgType.BINARY: raise TypeError( @@ -400,17 +430,18 @@ msg.data)) return msg.data - async def receive_json(self, *, loads=json.loads, timeout=None): + 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): + async def write(self, data: bytes) -> None: raise RuntimeError("Cannot call .write() for websocket") - def __aiter__(self): + def __aiter__(self) -> 'WebSocketResponse': return self - async def __anext__(self): + async def __anext__(self) -> WSMessage: msg = await self.receive() if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, diff -Nru python-aiohttp-3.1.3/aiohttp/worker.py python-aiohttp-3.5.1/aiohttp/worker.py --- python-aiohttp-3.1.3/aiohttp/worker.py 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp/worker.py 2018-12-24 20:58:54.000000000 +0000 @@ -6,19 +6,24 @@ import signal import sys from contextlib import suppress +from types import FrameType +from typing import Any, Optional # noqa from gunicorn.config import AccessLogFormat as GunicornAccessLogFormat from gunicorn.workers import base from aiohttp import web -from .helpers import AccessLogger, set_result +from .helpers import set_result +from .web_log import AccessLogger try: import ssl + SSLContext = ssl.SSLContext # noqa except ImportError: # pragma: no cover - ssl = None + ssl = None # type: ignore + SSLContext = object # type: ignore __all__ = ('GunicornWebWorker', @@ -31,15 +36,15 @@ DEFAULT_AIOHTTP_LOG_FORMAT = AccessLogger.LOG_FORMAT DEFAULT_GUNICORN_LOG_FORMAT = GunicornAccessLogFormat.default - def __init__(self, *args, **kw): # pragma: no cover + def __init__(self, *args: Any, **kw: Any) -> None: # pragma: no cover super().__init__(*args, **kw) - self._runner = None - self._task = None + self._runner = None # type: Optional[web.AppRunner] + self._task = None # type: Optional[asyncio.Task[None]] self.exit_code = 0 - self._notify_waiter = None + self._notify_waiter = None # type: Optional[asyncio.Future[bool]] - def init_process(self): + def init_process(self) -> None: # create new event_loop after fork asyncio.get_event_loop().close() @@ -48,7 +53,7 @@ super().init_process() - def run(self): + def run(self) -> None: access_log = self.log.access_log if self.cfg.accesslog else None params = dict( logger=self.log, @@ -56,36 +61,42 @@ access_log=access_log, access_log_format=self._get_valid_log_format( self.cfg.access_log_format)) - if asyncio.iscoroutinefunction(self.wsgi): - self.wsgi = self.loop.run_until_complete(self.wsgi()) + if asyncio.iscoroutinefunction(self.wsgi): # type: ignore + self.wsgi = self.loop.run_until_complete( + self.wsgi()) # type: ignore self._runner = web.AppRunner(self.wsgi, **params) self.loop.run_until_complete(self._runner.setup()) self._task = self.loop.create_task(self._run()) with suppress(Exception): # ignore all finalization problems self.loop.run_until_complete(self._task) - if hasattr(self.loop, 'shutdown_asyncgens'): - self.loop.run_until_complete(self.loop.shutdown_asyncgens()) + if sys.version_info >= (3, 6): + if hasattr(self.loop, 'shutdown_asyncgens'): + self.loop.run_until_complete(self.loop.shutdown_asyncgens()) self.loop.close() sys.exit(self.exit_code) - async def _run(self): + async def _run(self) -> None: ctx = self._create_ssl_context(self.cfg) if self.cfg.is_ssl else None + runner = self._runner + assert runner is not None + server = runner.server + assert server is not None for sock in self.sockets: site = web.SockSite( - self._runner, sock, ssl_context=ctx, + 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: + while self.alive: # type: ignore self.notify() - cnt = self._runner.server.requests_count + 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) @@ -98,17 +109,19 @@ except BaseException: pass - await self._runner.cleanup() + await runner.cleanup() - def _wait_next_notify(self): + def _wait_next_notify(self) -> 'asyncio.Future[bool]': self._notify_waiter_done() - self._notify_waiter = waiter = self.loop.create_future() + 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=None): + def _notify_waiter_done(self, waiter: 'asyncio.Future[bool]'=None) -> None: if waiter is None: waiter = self._notify_waiter if waiter is not None: @@ -117,7 +130,7 @@ if waiter is self._notify_waiter: self._notify_waiter = None - def init_signals(self): + def init_signals(self) -> None: # Set up signals through the event loop API. self.loop.add_signal_handler(signal.SIGQUIT, self.handle_quit, @@ -143,7 +156,7 @@ signal.siginterrupt(signal.SIGTERM, False) signal.siginterrupt(signal.SIGUSR1, False) - def handle_quit(self, sig, frame): + def handle_quit(self, sig: int, frame: FrameType) -> None: self.alive = False # worker_int callback @@ -152,14 +165,14 @@ # wakeup closing process self._notify_waiter_done() - def handle_abort(self, sig, frame): + 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): + def _create_ssl_context(cfg: Any) -> 'SSLContext': """ Creates SSLContext instance for usage in asyncio.create_server. See ssl.SSLSocket.__init__ for more details. @@ -176,7 +189,7 @@ ctx.set_ciphers(cfg.ciphers) return ctx - def _get_valid_log_format(self, source_format): + 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): @@ -193,7 +206,7 @@ class GunicornUVLoopWebWorker(GunicornWebWorker): - def init_process(self): + def init_process(self) -> None: import uvloop # Close any existing event loop before setting a @@ -210,7 +223,7 @@ class GunicornTokioWebWorker(GunicornWebWorker): - def init_process(self): # pragma: no cover + def init_process(self) -> None: # pragma: no cover import tokio # Close any existing event loop before setting a diff -Nru python-aiohttp-3.1.3/aiohttp.egg-info/PKG-INFO python-aiohttp-3.5.1/aiohttp.egg-info/PKG-INFO --- python-aiohttp-3.1.3/aiohttp.egg-info/PKG-INFO 2018-04-13 10:03:22.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp.egg-info/PKG-INFO 2018-12-24 20:59:57.000000000 +0000 @@ -1,13 +1,22 @@ -Metadata-Version: 1.2 +Metadata-Version: 2.1 Name: aiohttp -Version: 3.1.3 +Version: 3.5.1 Summary: Async http client/server framework (asyncio) -Home-page: https://github.com/aio-libs/aiohttp/ +Home-page: https://github.com/aio-libs/aiohttp Author: Nikolay Kim Author-email: fafhrd91@gmail.com Maintainer: Nikolay Kim , Andrew Svetlov Maintainer-email: aio-libs@googlegroups.com License: Apache 2 +Project-URL: CI: Circle, https://circleci.com/gh/aio-libs/aiohttp +Project-URL: CI: Shippable, https://app.shippable.com/github/aio-libs/aiohttp +Project-URL: Docs: RTD, https://docs.aiohttp.org +Project-URL: GitHub: repo, https://github.com/aio-libs/aiohttp +Project-URL: Chat: Gitter, https://gitter.im/aio-libs/Lobby +Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/aiohttp +Project-URL: CI: AppVeyor, https://ci.appveyor.com/project/aio-libs/aiohttp +Project-URL: CI: Travis, https://travis-ci.com/aio-libs/aiohttp +Project-URL: GitHub: issues, https://github.com/aio-libs/aiohttp/issues Description: ================================== Async http client/server framework ================================== @@ -17,21 +26,28 @@ :width: 64px :alt: aiohttp logo - .. image:: https://travis-ci.org/aio-libs/aiohttp.svg?branch=master - :target: https://travis-ci.org/aio-libs/aiohttp + | + + .. image:: https://travis-ci.com/aio-libs/aiohttp.svg?branch=master + :target: https://travis-ci.com/aio-libs/aiohttp :align: right :alt: Travis status for master branch + .. image:: https://ci.appveyor.com/api/projects/status/tnddy9k6pphl8w7k/branch/master?svg=true + :target: https://ci.appveyor.com/project/aio-libs/aiohttp + :align: right + :alt: AppVeyor 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://badge.fury.io/py/aiohttp + :target: https://pypi.org/project/aiohttp :alt: Latest PyPI package version .. image:: https://readthedocs.org/projects/aiohttp/badge/?version=latest - :target: http://docs.aiohttp.org/ + :target: https://docs.aiohttp.org/ :alt: Latest Read The Docs .. image:: https://badges.gitter.im/Join%20Chat.svg @@ -42,9 +58,9 @@ ============ - Supports both client and server side of HTTP protocol. - - Supports both client and server Web-Sockets out-of-the-box without the + - Supports both client and server Web-Sockets out-of-the-box and avoids Callback Hell. - - Web-server has middlewares and pluggable routing. + - Provides Web-server with middlewares and pluggable routing. Getting started @@ -53,18 +69,16 @@ Client ------ - To retrieve something from the web: + To get something from the web: .. code-block:: python import aiohttp import asyncio - import async_timeout async def fetch(session, url): - async with async_timeout.timeout(10): - async with session.get(url) as response: - return await response.text() + async with session.get(url) as response: + return await response.text() async def main(): async with aiohttp.ClientSession() as session: @@ -79,10 +93,11 @@ Server ------ - This is simple usage example: + An example using a simple server: .. code-block:: python + # examples/server_simple.py from aiohttp import web async def handle(request): @@ -95,11 +110,11 @@ await ws.prepare(request) async for msg in ws: - if msg.type == web.MsgType.text: + if msg.type == web.WSMsgType.text: await ws.send_str("Hello, {}".format(msg.data)) - elif msg.type == web.MsgType.binary: + elif msg.type == web.WSMsgType.binary: await ws.send_bytes(msg.data) - elif msg.type == web.MsgType.close: + elif msg.type == web.WSMsgType.close: break return ws @@ -118,6 +133,13 @@ https://aiohttp.readthedocs.io/ + + Demos + ===== + + https://github.com/aio-libs/aiohttp-demos + + External links ============== @@ -175,20 +197,20 @@ ======== The aiohttp community would like to thank Keepsafe - (https://www.getkeepsafe.com) for it's support in the early days of + (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: + The latest developer version is available in a GitHub repository: https://github.com/aio-libs/aiohttp Benchmarks ========== - If you are interested in by efficiency, AsyncIO community maintains a + 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 @@ -208,112 +230,95 @@ .. towncrier release notes start - 3.1.3 (2018-04-12) - ================== - - - Fix cancellation broadcast during DNS resolve (`#2910 `_) - - - 3.1.2 (2018-04-05) - ================== - - - Make ``LineTooLong`` exception more detailed about actual data size (`#2863 `_) - - Call ``on_chunk_sent`` when write_eof takes as a param the last chunk (`#2909 `_) - - - 3.1.1 (2018-03-27) - ================== - - - Support *asynchronous iterators* (and *asynchronous generators* as - well) in both client and server API as request / response BODY - payloads. (`#2802 `_) - - - 3.1.0 (2018-03-21) - ================== + 3.5.1 (2018-12-24) + ==================== - Welcome to aiohttp 3.1 release. + - Fix a regression about ``ClientSession._requote_redirect_url`` modification in debug + mode. - This is an *incremental* release, fully backward compatible with *aiohttp 3.0*. + 3.5.0 (2018-12-22) + ==================== - But we have added several new features. - - The most visible one is ``app.add_routes()`` (an alias for existing - ``app.router.add_routes()``. The addition is very important because - all *aiohttp* docs now uses ``app.add_routes()`` call in code - snippets. All your existing code still do register routes / resource - without any warning but you've got the idea for a favorite way: noisy - ``app.router.add_get()`` is replaced by ``app.add_routes()``. - - The library does not make a preference between decorators:: - - routes = web.RouteTableDef() - - @routes.get('/') - async def hello(request): - return web.Response(text="Hello, world") - - app.add_routes(routes) - - and route tables as a list:: - - async def hello(request): - return web.Response(text="Hello, world") - - app.add_routes([web.get('/', hello)]) + Features + -------- - Both ways are equal, user may decide basing on own code taste. + - The library type annotations are checked in strict mode now. + - Add support for setting cookies for individual request (`#2387 `_) + - Application.add_domain implementation (`#2809 `_) + - The default ``app`` in the request returned by ``test_utils.make_mocked_request`` + can now have objects assigned to it and retrieved using the ``[]`` operator. (`#3174 `_) + - Make ``request.url`` accessible when transport is closed. (`#3177 `_) + - Add ``zlib_executor_size`` argument to ``Response`` constructor to allow compression to run in a background executor to avoid blocking the main thread and potentially triggering health check failures. (`#3205 `_) + - Enable users to set `ClientTimeout` in `aiohttp.request` (`#3213 `_) + - Don't raise a warning if ``NETRC`` environment variable is not set and ``~/.netrc`` file + doesn't exist. (`#3267 `_) + - Add default logging handler to web.run_app - Also we have a lot of minor features, bug fixes and documentation - updates, see below. + If the `Application.debug` flag is set and the default logger `aiohttp.access` is used, access logs will now be output using a `stderr` `StreamHandler` if no handlers are attached. Furthermore, if the default logger has no log level set, the log level will be set to `DEBUG`. (`#3324 `_) + - Add method argument to ``session.ws_connect()``. - Features - -------- + Sometimes server API requires a different HTTP method for WebSocket connection establishment. - - Relax JSON content-type checking in the ``ClientResponse.json()`` to allow - "application/xxx+json" instead of strict "application/json". (`#2206 `_) - - Bump C HTTP parser to version 2.8 (`#2730 `_) - - Accept a coroutine as an application factory in ``web.run_app`` and gunicorn - worker. (`#2739 `_) - - Implement application cleanup context (``app.cleanup_ctx`` property). (`#2747 `_) - - Make ``writer.write_headers`` a coroutine. (`#2762 `_) - - Add tracking signals for getting request/response bodies. (`#2767 `_) - - Deprecate ClientResponseError.code in favor of .status to keep similarity - with response classes. (`#2781 `_) - - Implement ``app.add_routes()`` method. (`#2787 `_) - - Implement ``web.static()`` and ``RouteTableDef.static()`` API. (`#2795 `_) - - Install a test event loop as default by ``asyncio.set_event_loop()``. The - change affects aiohttp test utils but backward compatibility is not broken - for 99.99% of use cases. (`#2804 `_) - - Refactor ``ClientResponse`` constructor: make logically required constructor - arguments mandatory, drop ``_post_init()`` method. (`#2820 `_) - - Use ``app.add_routes()`` in server docs everywhere (`#2830 `_) - - Websockets refactoring, all websocket writer methods are converted into - coroutines. (`#2836 `_) - - Provide ``Content-Range`` header for ``Range`` requests (`#2844 `_) + For example, ``Docker exec`` needs POST. (`#3378 `_) + - Create a task per request handling. (`#3406 `_) Bugfixes -------- - - Fix websocket client return EofStream. (`#2784 `_) - - Fix websocket demo. (`#2789 `_) - - Property ``BaseRequest.http_range`` now returns a python-like slice when - requesting the tail of the range. It's now indicated by a negative value in - ``range.start`` rather then in ``range.stop`` (`#2805 `_) - - Close a connection if an unexpected exception occurs while sending a request - (`#2827 `_) - - Fix firing DNS tracing events. (`#2841 `_) + - Enable passing `access_log_class` via `handler_args` (`#3158 `_) + - Return empty bytes with end-of-chunk marker in empty stream reader. (`#3186 `_) + - Accept ``CIMultiDictProxy`` instances for ``headers`` argument in ``web.Response`` + constructor. (`#3207 `_) + - Don't uppercase HTTP method in parser (`#3233 `_) + - Make method match regexp RFC-7230 compliant (`#3235 `_) + - Add ``app.pre_frozen`` state to properly handle startup signals in sub-applications. (`#3237 `_) + - Enhanced parsing and validation of helpers.BasicAuth.decode. (`#3239 `_) + - Change imports from collections module in preparation for 3.8. (`#3258 `_) + - Ensure Host header is added first to ClientRequest to better replicate browser (`#3265 `_) + - Fix forward compatibility with Python 3.8: importing ABCs directly from the collections module will not be supported anymore. (`#3273 `_) + - Keep the query string by `normalize_path_middleware`. (`#3278 `_) + - Fix missing parameter ``raise_for_status`` for aiohttp.request() (`#3290 `_) + - Bracket IPv6 addresses in the HOST header (`#3304 `_) + - Fix default message for server ping and pong frames. (`#3308 `_) + - Fix tests/test_connector.py typo and tests/autobahn/server.py duplicate loop def. (`#3337 `_) + - Fix false-negative indicator end_of_HTTP_chunk in StreamReader.readchunk function (`#3361 `_) + - Release HTTP response before raising status exception (`#3364 `_) + - Fix task cancellation when ``sendfile()`` syscall is used by static file handling. (`#3383 `_) + - Fix stack trace for ``asyncio.TimeoutError`` which was not logged, when it is caught + in the handler. (`#3414 `_) Improved Documentation ---------------------- - - Document behavior when cchardet detects encodings that are unknown to Python. - (`#2732 `_) - - Add diagrams for tracing request life style. (`#2748 `_) - - Drop removed functionality for passing ``StreamReader`` as data at client - side. (`#2793 `_) + - Improve documentation of ``Application.make_handler`` parameters. (`#3152 `_) + - Fix BaseRequest.raw_headers doc. (`#3215 `_) + - Fix typo in TypeError exception reason in ``web.Application._handle`` (`#3229 `_) + - Make server access log format placeholder %b documentation reflect + behavior and docstring. (`#3307 `_) + + + Deprecations and Removals + ------------------------- + + - Deprecate modification of ``session.requote_redirect_url`` (`#2278 `_) + - Deprecate ``stream.unread_data()`` (`#3260 `_) + - Deprecated use of boolean in ``resp.enable_compression()`` (`#3318 `_) + - Encourage creation of aiohttp public objects inside a coroutine (`#3331 `_) + - Drop dead ``Connection.detach()`` and ``Connection.writer``. Both methods were broken + for more than 2 years. (`#3358 `_) + - Deprecate ``app.loop``, ``request.loop``, ``client.loop`` and ``connector.loop`` properties. (`#3374 `_) + - Deprecate explicit debug argument. Use asyncio debug mode instead. (`#3381 `_) + - Deprecate body parameter in HTTPException (and derived classes) constructor. (`#3385 `_) + - Deprecate bare connector close, use ``async with connector:`` and ``await connector.close()`` instead. (`#3417 `_) + - Deprecate obsolete ``read_timeout`` and ``conn_timeout`` in ``ClientSession`` constructor. (`#3438 `_) + + + Misc + ---- + + - #3341, #3351 Platform: UNKNOWN Classifier: License :: OSI Approved :: Apache Software License Classifier: Intended Audience :: Developers @@ -321,6 +326,7 @@ Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 Classifier: Development Status :: 5 - Production/Stable Classifier: Operating System :: POSIX Classifier: Operating System :: MacOS :: MacOS X @@ -328,3 +334,4 @@ Classifier: Topic :: Internet :: WWW/HTTP Classifier: Framework :: AsyncIO Requires-Python: >=3.5.3 +Provides-Extra: speedups diff -Nru python-aiohttp-3.1.3/aiohttp.egg-info/requires.txt python-aiohttp-3.5.1/aiohttp.egg-info/requires.txt --- python-aiohttp-3.1.3/aiohttp.egg-info/requires.txt 2018-04-13 10:03:22.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp.egg-info/requires.txt 2018-12-24 20:59:57.000000000 +0000 @@ -1,6 +1,14 @@ attrs>=17.3.0 chardet<4.0,>=2.0 multidict<5.0,>=4.0 -async_timeout<3.0,>=1.2 +async_timeout<4.0,>=3.0 yarl<2.0,>=1.0 + +[:python_version < "3.7"] idna-ssl>=1.0 +typing_extensions>=3.6.5 + +[speedups] +aiodns +brotlipy +cchardet diff -Nru python-aiohttp-3.1.3/aiohttp.egg-info/SOURCES.txt python-aiohttp-3.5.1/aiohttp.egg-info/SOURCES.txt --- python-aiohttp-3.1.3/aiohttp.egg-info/SOURCES.txt 2018-04-13 10:03:22.000000000 +0000 +++ python-aiohttp-3.5.1/aiohttp.egg-info/SOURCES.txt 2018-12-24 20:59:57.000000000 +0000 @@ -1,7 +1,9 @@ .appveyor.yml .cherry_picker.toml +.editorconfig .gitattributes .gitignore +.gitmodules .pyup.yml .readthedocs.yml .travis.yml @@ -16,21 +18,34 @@ README.rst codecov.yml pyproject.toml +pytest.ci.ini +pytest.ini setup.cfg setup.py tox.ini +.github/CODEOWNERS .github/ISSUE_TEMPLATE.md .github/PULL_REQUEST_TEMPLATE.md CHANGES/.gitignore aiohttp/__init__.py aiohttp/_cparser.pxd +aiohttp/_find_header.c +aiohttp/_find_header.h +aiohttp/_find_header.pxd aiohttp/_frozenlist.c aiohttp/_frozenlist.pyx +aiohttp/_headers.pxi +aiohttp/_helpers.c +aiohttp/_helpers.pyi +aiohttp/_helpers.pyx aiohttp/_http_parser.c aiohttp/_http_parser.pyx +aiohttp/_http_writer.c +aiohttp/_http_writer.pyx aiohttp/_websocket.c aiohttp/_websocket.pyx aiohttp/abc.py +aiohttp/base_protocol.py aiohttp/client.py aiohttp/client_exceptions.py aiohttp/client_proto.py @@ -40,6 +55,7 @@ aiohttp/cookiejar.py aiohttp/formdata.py aiohttp/frozenlist.py +aiohttp/frozenlist.pyi aiohttp/hdrs.py aiohttp/helpers.py aiohttp/http.py @@ -52,21 +68,26 @@ aiohttp/multipart.py aiohttp/payload.py aiohttp/payload_streamer.py +aiohttp/py.typed aiohttp/pytest_plugin.py aiohttp/resolver.py aiohttp/signals.py +aiohttp/signals.pyi aiohttp/streams.py aiohttp/tcp_helpers.py aiohttp/test_utils.py aiohttp/tracing.py +aiohttp/typedefs.py aiohttp/web.py aiohttp/web_app.py aiohttp/web_exceptions.py aiohttp/web_fileresponse.py +aiohttp/web_log.py aiohttp/web_middlewares.py aiohttp/web_protocol.py aiohttp/web_request.py aiohttp/web_response.py +aiohttp/web_routedef.py aiohttp/web_runner.py aiohttp/web_server.py aiohttp/web_urldispatcher.py @@ -77,39 +98,6 @@ aiohttp.egg-info/dependency_links.txt aiohttp.egg-info/requires.txt aiohttp.egg-info/top_level.txt -demos/README.rst -demos/chat/setup.py -demos/chat/aiohttpdemo_chat/__init__.py -demos/chat/aiohttpdemo_chat/main.py -demos/chat/aiohttpdemo_chat/views.py -demos/chat/aiohttpdemo_chat/templates/index.html -demos/polls/Makefile -demos/polls/README.rst -demos/polls/requirements.txt -demos/polls/setup.py -demos/polls/tox.ini -demos/polls/aiohttpdemo_polls/__init__.py -demos/polls/aiohttpdemo_polls/__main__.py -demos/polls/aiohttpdemo_polls/db.py -demos/polls/aiohttpdemo_polls/main.py -demos/polls/aiohttpdemo_polls/middlewares.py -demos/polls/aiohttpdemo_polls/routes.py -demos/polls/aiohttpdemo_polls/utils.py -demos/polls/aiohttpdemo_polls/views.py -demos/polls/aiohttpdemo_polls/static/style.css -demos/polls/aiohttpdemo_polls/templates/404.html -demos/polls/aiohttpdemo_polls/templates/500.html -demos/polls/aiohttpdemo_polls/templates/base.html -demos/polls/aiohttpdemo_polls/templates/detail.html -demos/polls/aiohttpdemo_polls/templates/index.html -demos/polls/aiohttpdemo_polls/templates/results.html -demos/polls/config/polls.yaml -demos/polls/images/example.png -demos/polls/sql/create_tables.sql -demos/polls/sql/install.sh -demos/polls/sql/sample_data.sql -demos/polls/tests/conftest.py -demos/polls/tests/test_integration.py docs/Makefile docs/abc.rst docs/aiohttp-icon.svg @@ -136,15 +124,16 @@ docs/multipart.rst docs/multipart_reference.rst docs/new_router.rst +docs/old-logo.png docs/old-logo.svg docs/powered_by.rst docs/signals.rst docs/spelling_wordlist.txt docs/streams.rst +docs/structures.rst docs/testing.rst docs/third_party.rst docs/tracing_reference.rst -docs/tutorial.rst docs/utilities.rst docs/web.rst docs/web_advanced.rst @@ -166,6 +155,7 @@ examples/server.crt examples/server.csr examples/server.key +examples/server_simple.py examples/static_files.py examples/web_classview.py examples/web_cookies.py @@ -180,9 +170,12 @@ examples/legacy/tcp_protocol_parser.py requirements/ci-wheel.txt requirements/ci.txt +requirements/cython.txt requirements/dev.txt requirements/doc-spelling.txt requirements/doc.txt +requirements/flake.txt +requirements/towncrier.txt requirements/wheel.txt tests/aiohttp.jpg tests/aiohttp.png @@ -192,6 +185,7 @@ tests/sample.crt tests/sample.crt.der tests/sample.key +tests/test_base_protocol.py tests/test_classbasedview.py tests/test_client_connection.py tests/test_client_exceptions.py @@ -233,6 +227,7 @@ tests/test_web_cli.py tests/test_web_exceptions.py tests/test_web_functional.py +tests/test_web_log.py tests/test_web_middleware.py tests/test_web_protocol.py tests/test_web_request.py @@ -258,8 +253,10 @@ tools/check_changes.py tools/drop_merged_branches.sh tools/fix_changelog.py +tools/gen.py tools/run_docker.sh vendor/http-parser/http_parser.c +vendor/http-parser/.git vendor/http-parser/.gitignore vendor/http-parser/.mailmap vendor/http-parser/.travis.yml diff -Nru python-aiohttp-3.1.3/.appveyor.yml python-aiohttp-3.5.1/.appveyor.yml --- python-aiohttp-3.1.3/.appveyor.yml 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/.appveyor.yml 2018-12-24 20:58:53.000000000 +0000 @@ -1,23 +1,30 @@ environment: PYPI_PASSWD: - secure: u+K6dKi7+CXXVFEUG4V7zUyV3w7Ntg0Ork/RGVV0eSQ= + secure: HrwOVde4wZoYHJf9bZ5AsQ== matrix: - PYTHON: "C:\\Python35" - PYTHON: "C:\\Python35-x64" - PYTHON: "C:\\Python36" - PYTHON: "C:\\Python36-x64" + - PYTHON: "C:\\Python37" + - PYTHON: "C:\\Python37-x64" install: - - "tools/build.cmd %PYTHON%\\python.exe -m pip install -U wheel setuptools" + # Ensure the Git Submoduldes have been pulled down too + - git submodule update --init --recursive + + - "tools/build.cmd %PYTHON%\\python.exe -m pip install -U pip wheel setuptools" + - "tools/build.cmd %PYTHON%\\python.exe -m pip install -r requirements/cython.txt" - "tools/build.cmd %PYTHON%\\python.exe -m pip install -r requirements/ci.txt" -build: false +build_script: + - "tools/build.cmd %PYTHON%\\python.exe -m setup sdist bdist_wheel" test_script: - - "tools/build.cmd %PYTHON%\\python.exe setup.py test" + - "tools/build.cmd %PYTHON%\\python.exe -m pytest -c pytest.ci.ini --cov-report xml" after_test: - - "tools/build.cmd %PYTHON%\\python.exe setup.py sdist bdist_wheel" + - "tools/build.cmd %PYTHON%\\python.exe -m codecov -f coverage.xml -X gcov" artifacts: - path: dist\* @@ -25,7 +32,7 @@ deploy_script: - ps: >- if($env:appveyor_repo_tag -eq 'True') { - Invoke-Expression "$env:PYTHON\\python.exe -m twine upload dist/* --username andrew.svetlov --password $env:PYPI_PASSWD" + Invoke-Expression "$env:PYTHON\\python.exe -m twine upload dist/* --username aio-libs-bot --password $env:PYPI_PASSWD --skip-existing" } #notifications: diff -Nru python-aiohttp-3.1.3/CHANGES.rst python-aiohttp-3.5.1/CHANGES.rst --- python-aiohttp-3.1.3/CHANGES.rst 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/CHANGES.rst 2018-12-24 20:58:54.000000000 +0000 @@ -14,109 +14,92 @@ .. towncrier release notes start -3.1.3 (2018-04-12) -================== +3.5.1 (2018-12-24) +==================== -- Fix cancellation broadcast during DNS resolve (`#2910 `_) +- Fix a regression about ``ClientSession._requote_redirect_url`` modification in debug + mode. +3.5.0 (2018-12-22) +==================== -3.1.2 (2018-04-05) -================== - -- Make ``LineTooLong`` exception more detailed about actual data size (`#2863 `_) -- Call ``on_chunk_sent`` when write_eof takes as a param the last chunk (`#2909 `_) - - -3.1.1 (2018-03-27) -================== - -- Support *asynchronous iterators* (and *asynchronous generators* as - well) in both client and server API as request / response BODY - payloads. (`#2802 `_) - - -3.1.0 (2018-03-21) -================== - -Welcome to aiohttp 3.1 release. - -This is an *incremental* release, fully backward compatible with *aiohttp 3.0*. - -But we have added several new features. - -The most visible one is ``app.add_routes()`` (an alias for existing -``app.router.add_routes()``. The addition is very important because -all *aiohttp* docs now uses ``app.add_routes()`` call in code -snippets. All your existing code still do register routes / resource -without any warning but you've got the idea for a favorite way: noisy -``app.router.add_get()`` is replaced by ``app.add_routes()``. - -The library does not make a preference between decorators:: - - routes = web.RouteTableDef() - - @routes.get('/') - async def hello(request): - return web.Response(text="Hello, world") - - app.add_routes(routes) - -and route tables as a list:: - - async def hello(request): - return web.Response(text="Hello, world") - - app.add_routes([web.get('/', hello)]) +Features +-------- -Both ways are equal, user may decide basing on own code taste. +- The library type annotations are checked in strict mode now. +- Add support for setting cookies for individual request (`#2387 `_) +- Application.add_domain implementation (`#2809 `_) +- The default ``app`` in the request returned by ``test_utils.make_mocked_request`` + can now have objects assigned to it and retrieved using the ``[]`` operator. (`#3174 `_) +- Make ``request.url`` accessible when transport is closed. (`#3177 `_) +- Add ``zlib_executor_size`` argument to ``Response`` constructor to allow compression to run in a background executor to avoid blocking the main thread and potentially triggering health check failures. (`#3205 `_) +- Enable users to set `ClientTimeout` in `aiohttp.request` (`#3213 `_) +- Don't raise a warning if ``NETRC`` environment variable is not set and ``~/.netrc`` file + doesn't exist. (`#3267 `_) +- Add default logging handler to web.run_app -Also we have a lot of minor features, bug fixes and documentation -updates, see below. + If the `Application.debug` flag is set and the default logger `aiohttp.access` is used, access logs will now be output using a `stderr` `StreamHandler` if no handlers are attached. Furthermore, if the default logger has no log level set, the log level will be set to `DEBUG`. (`#3324 `_) +- Add method argument to ``session.ws_connect()``. -Features --------- + Sometimes server API requires a different HTTP method for WebSocket connection establishment. -- Relax JSON content-type checking in the ``ClientResponse.json()`` to allow - "application/xxx+json" instead of strict "application/json". (`#2206 `_) -- Bump C HTTP parser to version 2.8 (`#2730 `_) -- Accept a coroutine as an application factory in ``web.run_app`` and gunicorn - worker. (`#2739 `_) -- Implement application cleanup context (``app.cleanup_ctx`` property). (`#2747 `_) -- Make ``writer.write_headers`` a coroutine. (`#2762 `_) -- Add tracking signals for getting request/response bodies. (`#2767 `_) -- Deprecate ClientResponseError.code in favor of .status to keep similarity - with response classes. (`#2781 `_) -- Implement ``app.add_routes()`` method. (`#2787 `_) -- Implement ``web.static()`` and ``RouteTableDef.static()`` API. (`#2795 `_) -- Install a test event loop as default by ``asyncio.set_event_loop()``. The - change affects aiohttp test utils but backward compatibility is not broken - for 99.99% of use cases. (`#2804 `_) -- Refactor ``ClientResponse`` constructor: make logically required constructor - arguments mandatory, drop ``_post_init()`` method. (`#2820 `_) -- Use ``app.add_routes()`` in server docs everywhere (`#2830 `_) -- Websockets refactoring, all websocket writer methods are converted into - coroutines. (`#2836 `_) -- Provide ``Content-Range`` header for ``Range`` requests (`#2844 `_) + For example, ``Docker exec`` needs POST. (`#3378 `_) +- Create a task per request handling. (`#3406 `_) Bugfixes -------- -- Fix websocket client return EofStream. (`#2784 `_) -- Fix websocket demo. (`#2789 `_) -- Property ``BaseRequest.http_range`` now returns a python-like slice when - requesting the tail of the range. It's now indicated by a negative value in - ``range.start`` rather then in ``range.stop`` (`#2805 `_) -- Close a connection if an unexpected exception occurs while sending a request - (`#2827 `_) -- Fix firing DNS tracing events. (`#2841 `_) +- Enable passing `access_log_class` via `handler_args` (`#3158 `_) +- Return empty bytes with end-of-chunk marker in empty stream reader. (`#3186 `_) +- Accept ``CIMultiDictProxy`` instances for ``headers`` argument in ``web.Response`` + constructor. (`#3207 `_) +- Don't uppercase HTTP method in parser (`#3233 `_) +- Make method match regexp RFC-7230 compliant (`#3235 `_) +- Add ``app.pre_frozen`` state to properly handle startup signals in sub-applications. (`#3237 `_) +- Enhanced parsing and validation of helpers.BasicAuth.decode. (`#3239 `_) +- Change imports from collections module in preparation for 3.8. (`#3258 `_) +- Ensure Host header is added first to ClientRequest to better replicate browser (`#3265 `_) +- Fix forward compatibility with Python 3.8: importing ABCs directly from the collections module will not be supported anymore. (`#3273 `_) +- Keep the query string by `normalize_path_middleware`. (`#3278 `_) +- Fix missing parameter ``raise_for_status`` for aiohttp.request() (`#3290 `_) +- Bracket IPv6 addresses in the HOST header (`#3304 `_) +- Fix default message for server ping and pong frames. (`#3308 `_) +- Fix tests/test_connector.py typo and tests/autobahn/server.py duplicate loop def. (`#3337 `_) +- Fix false-negative indicator end_of_HTTP_chunk in StreamReader.readchunk function (`#3361 `_) +- Release HTTP response before raising status exception (`#3364 `_) +- Fix task cancellation when ``sendfile()`` syscall is used by static file handling. (`#3383 `_) +- Fix stack trace for ``asyncio.TimeoutError`` which was not logged, when it is caught + in the handler. (`#3414 `_) Improved Documentation ---------------------- -- Document behavior when cchardet detects encodings that are unknown to Python. - (`#2732 `_) -- Add diagrams for tracing request life style. (`#2748 `_) -- Drop removed functionality for passing ``StreamReader`` as data at client - side. (`#2793 `_) +- Improve documentation of ``Application.make_handler`` parameters. (`#3152 `_) +- Fix BaseRequest.raw_headers doc. (`#3215 `_) +- Fix typo in TypeError exception reason in ``web.Application._handle`` (`#3229 `_) +- Make server access log format placeholder %b documentation reflect + behavior and docstring. (`#3307 `_) + + +Deprecations and Removals +------------------------- + +- Deprecate modification of ``session.requote_redirect_url`` (`#2278 `_) +- Deprecate ``stream.unread_data()`` (`#3260 `_) +- Deprecated use of boolean in ``resp.enable_compression()`` (`#3318 `_) +- Encourage creation of aiohttp public objects inside a coroutine (`#3331 `_) +- Drop dead ``Connection.detach()`` and ``Connection.writer``. Both methods were broken + for more than 2 years. (`#3358 `_) +- Deprecate ``app.loop``, ``request.loop``, ``client.loop`` and ``connector.loop`` properties. (`#3374 `_) +- Deprecate explicit debug argument. Use asyncio debug mode instead. (`#3381 `_) +- Deprecate body parameter in HTTPException (and derived classes) constructor. (`#3385 `_) +- Deprecate bare connector close, use ``async with connector:`` and ``await connector.close()`` instead. (`#3417 `_) +- Deprecate obsolete ``read_timeout`` and ``conn_timeout`` in ``ClientSession`` constructor. (`#3438 `_) + + +Misc +---- + +- #3341, #3351 diff -Nru python-aiohttp-3.1.3/.cherry_picker.toml python-aiohttp-3.5.1/.cherry_picker.toml --- python-aiohttp-3.1.3/.cherry_picker.toml 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/.cherry_picker.toml 2018-12-24 20:58:53.000000000 +0000 @@ -1,3 +1,4 @@ team = "aio-libs" repo = "aiohttp" check_sha = "f382b5ffc445e45a110734f5396728da7914aeb6" +fix_commit_msg = false diff -Nru python-aiohttp-3.1.3/codecov.yml python-aiohttp-3.5.1/codecov.yml --- python-aiohttp-3.1.3/codecov.yml 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/codecov.yml 2018-12-24 20:58:54.000000000 +0000 @@ -3,3 +3,33 @@ status: project: no + +flags: + library: + paths: + - aiohttp/ + configs: + paths: + - requirements/ + - ".git*" + - "*.toml" + - "*.yml" + changelog: + paths: + - CHANGES/ + - CHANGES.rst + docs: + paths: + - docs/ + - "*.md" + - "*.rst" + - "*.txt" + tests: + paths: + - tests/ + tools: + paths: + - tools/ + third-party: + paths: + - vendor/ diff -Nru python-aiohttp-3.1.3/CONTRIBUTING.rst python-aiohttp-3.5.1/CONTRIBUTING.rst --- python-aiohttp-3.1.3/CONTRIBUTING.rst 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/CONTRIBUTING.rst 2018-12-24 20:58:54.000000000 +0000 @@ -12,222 +12,22 @@ Workflow is pretty straightforward: - 1. Clone the GitHub_ repo + 1. Clone the GitHub_ repo using ``--recurse-submodules`` argument 2. Make a change 3. Make sure all tests passed - 4. Add a file into ``CHANGES`` folder (`Changelog update`_). + 4. Add a file into ``CHANGES`` folder. 5. Commit changes to own aiohttp clone 6. Make pull request from github page for your clone against master branch -Preconditions for running aiohttp test suite --------------------------------------------- - -We expect you to use a python virtual environment to run our tests. - -There are several ways to make a virtual environment. - -If you like to use *virtualenv* please run: - -.. code-block:: shell - - $ cd aiohttp - $ virtualenv --python=`which python3` venv - $ . venv/bin/activate - -For standard python *venv*: - -.. code-block:: shell - - $ cd aiohttp - $ python3 -m venv venv - $ . venv/bin/activate - -For *virtualenvwrapper*: - -.. code-block:: shell - - $ cd aiohttp - $ mkvirtualenv --python=`which python3` aiohttp - -There are other tools like *pyvenv* but you know the rule of thumb -now: create a python3 virtual environment and activate it. - -After that please install libraries required for development: - -.. code-block:: shell - - $ pip install -r requirements/dev.txt - -.. note:: - If you plan to use ``pdb`` or ``ipdb`` within the test suite, execute: - -.. code-block:: shell - - $ py.test tests -s - - command to run the tests with disabled output capturing. - -Congratulations, you are ready to run the test suite! - - -Run aiohttp test suite ----------------------- - -After all the preconditions are met you can run tests typing the next -command: - -.. code-block:: shell - - $ make test - -The command at first will run the *flake8* tool (sorry, we don't accept -pull requests with pep8 or pyflakes errors). - -On *flake8* success the tests will be run. - -Please take a look on the produced output. - -Any extra texts (print statements and so on) should be removed. - - -Tests coverage --------------- - -We are trying hard to have good test coverage; please don't make it worse. - -Use: - -.. code-block:: shell - - $ make cov - -to run test suite and collect coverage information. Once the command -has finished check your coverage at the file that appears in the last -line of the output: -``open file:///.../aiohttp/htmlcov/index.html`` - -Please go to the link and make sure that your code change is covered. - - -The project uses *codecov.io* for storing coverage results. Visit -https://codecov.io/gh/aio-libs/aiohttp for looking on coverage of -master branch, history, pull requests etc. - -The browser extension https://docs.codecov.io/docs/browser-extension -is highly recommended for analyzing the coverage just in *Files -Changed* tab on *GitHub Pull Request* review page. - -Documentation -------------- - -We encourage documentation improvements. - -Please before making a Pull Request about documentation changes run: - -.. code-block:: shell - - $ make doc - -Once it finishes it will output the index html page -``open file:///.../aiohttp/docs/_build/html/index.html``. - -Go to the link and make sure your doc changes looks good. - -Spell checking --------------- - -We use ``pyenchant`` and ``sphinxcontrib-spelling`` for running spell -checker for documentation: - -.. code-block:: shell - - $ make doc-spelling - -Unfortunately there are problems with running spell checker on MacOS X. - -To run spell checker on Linux box you should install it first: - -.. code-block:: shell - - $ sudo apt-get install enchant - $ pip install sphinxcontrib-spelling - -Changelog update ----------------- - -The ``CHANGES.rst`` file is managed using `towncrier -`_ tool and all non trivial -changes must be accompanied by a news entry. - -To add an entry to the news file, first you need to have created an -issue describing the change you want to make. A Pull Request itself -*may* function as such, but it is preferred to have a dedicated issue -(for example, in case the PR ends up rejected due to code quality -reasons). - -Once you have an issue or pull request, you take the number and you -create a file inside of the ``CHANGES/`` directory named after that -issue number with an extension of ``.removal``, ``.feature``, -``.bugfix``, or ``.doc``. Thus if your issue or PR number is ``1234`` and -this change is fixing a bug, then you would create a file -``CHANGES/1234.bugfix``. PRs can span multiple categories by creating -multiple files (for instance, if you added a feature and -deprecated/removed the old feature at the same time, you would create -``CHANGES/NNNN.feature`` and ``CHANGES/NNNN.removal``). Likewise if a PR touches -multiple issues/PRs you may create a file for each of them with the -exact same contents and *Towncrier* will deduplicate them. - -The contents of this file are *reStructuredText* formatted text that -will be used as the content of the news file entry. You do not need to -reference the issue or PR numbers here as *towncrier* will automatically -add a reference to all of the affected issues when rendering the news -file. - - - -The End -------- - -After finishing all steps make a GitHub_ Pull Request, thanks. - - -How to become an aiohttp committer ----------------------------------- - -Contribute! - -The easiest way is providing Pull Requests for issues in our bug -tracker. But if you have a great idea for the library improvement --- please make an issue and Pull Request. - - - -The rules for committers are simple: - -1. No wild commits! Everything should go through PRs. -2. Take a part in reviews. It's very important part of maintainer's activity. -3. Pickup issues created by others, especially if they are simple. -4. Keep test suite comprehensive. In practice it means leveling up - coverage. 97% is not bad but we wish to have 100% someday. Well, 99% - is good target too. -5. Don't hesitate to improve our docs. Documentation is very important - thing, it's the key for project success. The documentation should - not only cover our public API but help newbies to start using the - project and shed a light on non-obvious gotchas. - - - -After positive answer aiohttp committer creates an issue on github -with the proposal for nomination. If the proposal will collect only -positive votes and no strong objection -- you'll be a new member in -our team. + 7. Optionally make backport Pull Request(s) for landing a bug fix + into released aiohttp versions. +Please open https://docs.aiohttp.org/en/stable/contributing.html +documentation page for getting detailed information about all steps. .. _GitHub: https://github.com/aio-libs/aiohttp - -.. _ipdb: https://pypi.python.org/pypi/ipdb diff -Nru python-aiohttp-3.1.3/CONTRIBUTORS.txt python-aiohttp-3.5.1/CONTRIBUTORS.txt --- python-aiohttp-3.1.3/CONTRIBUTORS.txt 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/CONTRIBUTORS.txt 2018-12-24 20:58:54.000000000 +0000 @@ -1,6 +1,7 @@ -Contributors ------------- +- Contributors - +---------------- A. Jesse Jiryu Davis +Adam Cooper Adam Mills Adrián Chaves Alec Hanefeld @@ -30,6 +31,7 @@ Andrew Leech Andrew Lytvyn Andrew Svetlov +Andrew Zhou Andrii Soldatenko Antoine Pietri Anton Kasyanov @@ -52,21 +54,25 @@ Chris Moore Christopher Schmitt Claudiu Popa +Colin Dunklau Damien Nadé Dan Xu Daniel García Daniel Nelson Danny Song +David Bibb David Michael Brown Denilson Amorim Denis Matiychuk Dima Veselov Dimitar Dimitrov +Dmitriy Safonov Dmitry Doroshev +Dmitry Lukashin Dmitry Shamov Dmitry Trofimov +Dmytro Bohomiakov Dmytro Kuznetsov -Dmitriy Safonov Dustin J. Mitchell Eduard Iskandarov Eli Ribble @@ -85,22 +91,29 @@ Georges Dubus Greg Holt Gregory Haynes +Gus Goulart +Gustavo Carneiro Günther Jena +Hans Adema +Harmon Y. Hu Bo Hugo Herter Hynek Schlawack Igor Alexandrov Igor Davydenko +Igor Mozharovsky Igor Pavlov Ingmar Steen Jacob Champion Jaesung Lee Jake Davis +Jakob Ackermann Jakub Wilk Jashandeep Sohi Jeongkyu Shin Jeroen van der Heijden Jesus Cea +Jian Zeng Jinkyu Yi Joel Watts Jon Nabozny @@ -111,6 +124,7 @@ Jungkook Park Junjie Tao Justas Trimailovas +Justin Foo Justin Turner Arthur Kay Zheng Kimmo Parviainen-Jalanko @@ -118,11 +132,12 @@ Kirill Malovitsa Kyrylo Perevozchikov Lars P. Søndergaard -Loïc Lajeanne Louis-Philippe Huberdeau +Loïc Lajeanne Lu Gong Lubomir Gelo Ludovic Gasc +Luis Pedrosa Lukasz Marcin Dobrzanski Makc Belousow Manuel Miranda @@ -137,22 +152,29 @@ Michael Ihnatenko Mikhail Kashkin Mikhail Lukyanchenko +Mikhail Nacharov Misha Behersky +Mitchell Ferree Morgan Delahaye-Prat Moss Collum Mun Gwan-gyeong Nicolas Braem Nikolay Kim Nikolay Novik +Oisin Aylward Olaf Conradi Pahaz Blinov Panagiotis Kolokotronis Pankaj Pandey Pau Freixes Paul Colomiets +Paulius Šileikis Paulus Schoutsen Pavel Kamaev +Pavel Polyakov +Pawel Kowalski Pawel Miech +Pepe Osca Philipp A. Pieter van Beek Rafael Viotti @@ -162,9 +184,10 @@ Roman Podoliaka Samuel Colvin Sean Hunt -Sebastien Geffroy +Sebastian Acuna Sebastian Hanula Sebastian Hüther +Sebastien Geffroy SeongSoo Cho Sergey Ninua Sergey Skripnick @@ -183,14 +206,21 @@ Terence Honles Thanos Lefteris Thijs Vermeir +Thomas Forbes Thomas Grainger Tolga Tezel +Tomasz Trebski +Trinh Hoang Nhu +Vadim Suharnikov Vaibhav Sagar Vamsi Krishna Avula Vasiliy Faronov Vasyl Baran Victor Kovtun Vikas Kawadia +Viktor Danyliuk +Ville Skyttä +Vincent Maillol Vitalik Verhovodov Vitaly Haritonsky Vitaly Magerya @@ -200,16 +230,18 @@ Vladimir Zakharov Vladyslav Bondar W. Trevor King +Wei Lin +Weiwei Wang Will McGugan Willem de Groot +William Grzybowski Wilson Ong -Wei Lin -Weiwei Wang Yang Zhou Yannick Koechlin Yannick Péroux Ye Cao Yegor Roganov +Yifei Kong Young-Ho Cha Yuriy Shatrov Yury Selivanov diff -Nru python-aiohttp-3.1.3/debian/changelog python-aiohttp-3.5.1/debian/changelog --- python-aiohttp-3.1.3/debian/changelog 2018-11-03 19:41:43.000000000 +0000 +++ python-aiohttp-3.5.1/debian/changelog 2018-12-31 17:15:56.000000000 +0000 @@ -1,8 +1,28 @@ -python-aiohttp (3.1.3-1build1) disco; urgency=medium +python-aiohttp (3.5.1-1) unstable; urgency=medium - * No-change rebuild to build without python3.6 support. + * New upstream release + * Remove idna_ssl patch - no longer needed in Python >= 3.7 + * Standards-Version bumped to 4.3.0 (no changes needed) - -- Matthias Klose Sat, 03 Nov 2018 19:41:43 +0000 + -- Piotr Ożarowski Mon, 31 Dec 2018 18:15:56 +0100 + +python-aiohttp (3.4.4-1~exp1) experimental; urgency=medium + + * Team upload + * New upstream release (Closes: #901010) + * debian/control: + - New standards version 4.2.1 - no changes + - Recommends libjs-jquery + * debian/gbp.conf: Enable pristine-tar build + * debian/patches: + - Refresh patches + - debian/patches/0002-Use-local-install-of-jquery.patch + (fixes lintian) + * debian/rules: + - Do not delete aiohttp/_*.c in override_dh_auto_clean + - Delete _find_header.h from binary packages + + -- Ruben Undheim Fri, 21 Dec 2018 18:32:14 +0000 python-aiohttp (3.1.3-1) unstable; urgency=medium diff -Nru python-aiohttp-3.1.3/debian/control python-aiohttp-3.5.1/debian/control --- python-aiohttp-3.1.3/debian/control 2018-08-14 12:51:41.000000000 +0000 +++ python-aiohttp-3.5.1/debian/control 2018-12-31 17:15:56.000000000 +0000 @@ -20,7 +20,7 @@ python3-pytest-mock, python3-chardet, python3-gunicorn -Standards-Version: 4.2.0 +Standards-Version: 4.3.0 Homepage: https://aiohttp.readthedocs.org Vcs-Git: https://salsa.debian.org/python-team/modules/python-aiohttp.git Vcs-Browser: https://salsa.debian.org/python-team/modules/python-aiohttp @@ -30,6 +30,7 @@ Package: python3-aiohttp Architecture: any Depends: python3-yarl (>= 1.0), ${misc:Depends}, ${python3:Depends}, ${shlibs:Depends}, +Recommends: libjs-jquery Description: http client/server for asyncio HTTP Client for asyncio (PEP 3156 - Asynchronous I/O Support). . diff -Nru python-aiohttp-3.1.3/debian/gbp.conf python-aiohttp-3.5.1/debian/gbp.conf --- python-aiohttp-3.1.3/debian/gbp.conf 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/debian/gbp.conf 2018-12-31 17:04:47.000000000 +0000 @@ -0,0 +1,2 @@ +[DEFAULT] +pristine-tar = True diff -Nru python-aiohttp-3.1.3/debian/idna_ssl.py python-aiohttp-3.5.1/debian/idna_ssl.py --- python-aiohttp-3.1.3/debian/idna_ssl.py 2018-04-16 10:23:31.000000000 +0000 +++ python-aiohttp-3.5.1/debian/idna_ssl.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,31 +0,0 @@ -import ssl - -import idna - -__version__ = '1.0.0' - -real_match_hostname = ssl.match_hostname - - -def patched_match_hostname(cert, hostname): - try: - hostname = idna.encode(hostname, uts46=True).decode('ascii') - except UnicodeError: - hostname = hostname.encode('idna').decode('ascii') - - return real_match_hostname(cert, hostname) - - -def patch_match_hostname(): - if hasattr(ssl.match_hostname, 'patched'): - return - - ssl.match_hostname = patched_match_hostname - ssl.match_hostname.patched = True - - -def reset_match_hostname(): - if not hasattr(ssl.match_hostname, 'patched'): - return - - ssl.match_hostname = real_match_hostname diff -Nru python-aiohttp-3.1.3/debian/patches/0001-bundle-idna_ssl.patch python-aiohttp-3.5.1/debian/patches/0001-bundle-idna_ssl.patch --- python-aiohttp-3.1.3/debian/patches/0001-bundle-idna_ssl.patch 2018-04-16 10:23:31.000000000 +0000 +++ python-aiohttp-3.5.1/debian/patches/0001-bundle-idna_ssl.patch 1970-01-01 00:00:00.000000000 +0000 @@ -1,42 +0,0 @@ -From 3de99c20ba2eea70259b34f6c4cb4b3b7704834e Mon Sep 17 00:00:00 2001 -From: =?UTF-8?q?Piotr=20O=C5=BCarowski?= -Date: Wed, 14 Feb 2018 13:55:21 +0100 -Subject: bundle idna_ssl - -yeah, usually we do that the other way around ;) - -this is just a temporary fix and hopefully will not be released with -Debian stable ---- - aiohttp/helpers.py | 2 +- - setup.py | 4 ++-- - 2 files changed, 3 insertions(+), 3 deletions(-) - -diff --git a/aiohttp/helpers.py b/aiohttp/helpers.py -index ff43b78..954faff 100644 ---- a/aiohttp/helpers.py -+++ b/aiohttp/helpers.py -@@ -36,7 +36,7 @@ PY_36 = sys.version_info >= (3, 6) - PY_37 = sys.version_info >= (3, 7) - - if not PY_37: -- import idna_ssl -+ from aiohttp import idna_ssl - idna_ssl.patch_match_hostname() - - -diff --git a/setup.py b/setup.py -index 0a5142d..8874f19 100644 ---- a/setup.py -+++ b/setup.py -@@ -73,8 +73,8 @@ install_requires = ['attrs>=17.3.0', 'chardet>=2.0,<4.0', - 'async_timeout>=1.2,<3.0', - 'yarl>=1.0,<2.0'] - --if sys.version_info < (3, 7): -- install_requires.append('idna-ssl>=1.0') -+#if sys.version_info < (3, 7): -+# install_requires.append('idna-ssl>=1.0') - - - def read(f): diff -Nru python-aiohttp-3.1.3/debian/patches/0002-Use-local-install-of-jquery.patch python-aiohttp-3.5.1/debian/patches/0002-Use-local-install-of-jquery.patch --- python-aiohttp-3.1.3/debian/patches/0002-Use-local-install-of-jquery.patch 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/debian/patches/0002-Use-local-install-of-jquery.patch 2018-12-31 17:14:53.000000000 +0000 @@ -0,0 +1,21 @@ +From: Ruben Undheim +Date: Fri, 21 Dec 2018 10:58:35 +0000 +Subject: Use local install of jquery + +--- + examples/websocket.html | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/examples/websocket.html b/examples/websocket.html +index 2ba9ff3..279be7d 100644 +--- a/examples/websocket.html ++++ b/examples/websocket.html +@@ -2,7 +2,7 @@ + + + +- + - - - -

Chat!

-
-  | Status: - UNKNOWN - disconnected -
-
-
-
- - -
- - diff -Nru python-aiohttp-3.1.3/demos/chat/aiohttpdemo_chat/views.py python-aiohttp-3.5.1/demos/chat/aiohttpdemo_chat/views.py --- python-aiohttp-3.1.3/demos/chat/aiohttpdemo_chat/views.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/chat/aiohttpdemo_chat/views.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,51 +0,0 @@ -import json -import logging -import random -import string - -import aiohttp_jinja2 -from aiohttp import web - - -log = logging.getLogger(__name__) - - -async def index(request): - resp = web.WebSocketResponse() - is_ws = resp.can_prepare(request) - if not is_ws: - return aiohttp_jinja2.render_template('index.html', request, {}) - - await resp.prepare(request) - name = (random.choice(string.ascii_uppercase) + - ''.join(random.sample(string.ascii_lowercase*10, 10))) - log.info('%s joined.', name) - await resp.send_str(json.dumps({'action': 'connect', - 'name': name})) - for ws in request.app['sockets'].values(): - await ws.send_str(json.dumps({'action': 'join', - 'name': name})) - request.app['sockets'][name] = resp - - while True: - msg = await resp.receive() - - if msg.type == web.MsgType.text: - for ws in request.app['sockets'].values(): - if ws is not resp: - await ws.send_str(json.dumps({'action': 'sent', - 'name': name, - 'text': msg.data})) - else: - break - - del request.app['sockets'][name] - log.info('%s disconnected.', name) - for ws in request.app['sockets'].values(): - await ws.send_str(json.dumps({'action': 'disconnect', - 'name': name})) - return resp - - -def setup(app): - app.router.add_get('/', index) diff -Nru python-aiohttp-3.1.3/demos/chat/setup.py python-aiohttp-3.5.1/demos/chat/setup.py --- python-aiohttp-3.1.3/demos/chat/setup.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/chat/setup.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,32 +0,0 @@ -import os -import re - -from setuptools import find_packages, setup - - -def read_version(): - regexp = re.compile(r"^__version__\W*=\W*'([\d.abrc]+)'") - init_py = os.path.join(os.path.dirname(__file__), - 'aiohttpdemo_chat', '__init__.py') - with open(init_py) as f: - for line in f: - match = regexp.match(line) - if match is not None: - return match.group(1) - else: - msg = 'Cannot find version in aiohttpdemo_chat/__init__.py' - raise RuntimeError(msg) - - -install_requires = ['aiohttp', - 'aiohttp_jinja2'] - - -setup(name='aiohttpdemo_chat', - version=read_version(), - description='Chat example from aiohttp', - platforms=['POSIX'], - packages=find_packages(), - include_package_data=True, - install_requires=install_requires, - zip_safe=False) diff -Nru python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/db.py python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/db.py --- python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/db.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/db.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,83 +0,0 @@ -import aiopg.sa -import sqlalchemy as sa - - -__all__ = ['question', 'choice'] - -meta = sa.MetaData() - - -question = sa.Table( - 'question', meta, - sa.Column('id', sa.Integer, nullable=False), - sa.Column('question_text', sa.String(200), nullable=False), - sa.Column('pub_date', sa.Date, nullable=False), - - # Indexes # - sa.PrimaryKeyConstraint('id', name='question_id_pkey')) - -choice = sa.Table( - 'choice', meta, - sa.Column('id', sa.Integer, nullable=False), - sa.Column('question_id', sa.Integer, nullable=False), - sa.Column('choice_text', sa.String(200), nullable=False), - sa.Column('votes', sa.Integer, server_default="0", nullable=False), - - # Indexes # - sa.PrimaryKeyConstraint('id', name='choice_id_pkey'), - sa.ForeignKeyConstraint(['question_id'], [question.c.id], - name='choice_question_id_fkey', - ondelete='CASCADE'), -) - - -class RecordNotFound(Exception): - """Requested record in database was not found""" - - -async def init_pg(app): - conf = app['config']['postgres'] - engine = await aiopg.sa.create_engine( - database=conf['database'], - user=conf['user'], - password=conf['password'], - host=conf['host'], - port=conf['port'], - minsize=conf['minsize'], - maxsize=conf['maxsize'], - loop=app.loop) - app['db'] = engine - - -async def close_pg(app): - app['db'].close() - await app['db'].wait_closed() - - -async def get_question(conn, question_id): - result = await conn.execute( - question.select() - .where(question.c.id == question_id)) - question_record = await result.first() - if not question_record: - msg = "Question with id: {} does not exists" - raise RecordNotFound(msg.format(question_id)) - result = await conn.execute( - choice.select() - .where(choice.c.question_id == question_id) - .order_by(choice.c.id)) - choice_recoreds = await result.fetchall() - return question_record, choice_recoreds - - -async def vote(conn, question_id, choice_id): - result = await conn.execute( - choice.update() - .returning(*choice.c) - .where(choice.c.question_id == question_id) - .where(choice.c.id == choice_id) - .values(votes=choice.c.votes+1)) - record = await result.fetchone() - if not record: - msg = "Question with id: {} or choice id: {} does not exists" - raise RecordNotFound(msg.format(question_id, choice_id)) diff -Nru python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/__init__.py python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/__init__.py --- python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/__init__.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/__init__.py 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -__version__ = '0.0.1' diff -Nru python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/__main__.py python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/__main__.py --- python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/__main__.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/__main__.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,6 +0,0 @@ -import sys - -from aiohttpdemo_polls.main import main - - -main(sys.argv[1:]) diff -Nru python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/main.py python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/main.py --- python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/main.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/main.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,62 +0,0 @@ -import argparse -import asyncio -import logging -import sys - -import jinja2 - -import aiohttp_jinja2 -from aiohttp import web -from aiohttpdemo_polls.db import close_pg, init_pg -from aiohttpdemo_polls.middlewares import setup_middlewares -from aiohttpdemo_polls.routes import setup_routes -from aiohttpdemo_polls.utils import TRAFARET -from trafaret_config import commandline - - -def init(loop, argv): - ap = argparse.ArgumentParser() - commandline.standard_argparse_options(ap, - default_config='./config/polls.yaml') - # - # define your command-line arguments here - # - options = ap.parse_args(argv) - - config = commandline.config_from_options(options, TRAFARET) - - # setup application and extensions - app = web.Application(loop=loop) - - # load config from yaml file in current dir - app['config'] = config - - # setup Jinja2 template renderer - aiohttp_jinja2.setup( - app, loader=jinja2.PackageLoader('aiohttpdemo_polls', 'templates')) - - # create connection to the database - app.on_startup.append(init_pg) - # shutdown db connection on exit - app.on_cleanup.append(close_pg) - # setup views and routes - setup_routes(app) - setup_middlewares(app) - - return app - - -def main(argv): - # init logging - logging.basicConfig(level=logging.DEBUG) - - loop = asyncio.get_event_loop() - - app = init(loop, argv) - web.run_app(app, - host=app['config']['host'], - port=app['config']['port']) - - -if __name__ == '__main__': - main(sys.argv[1:]) diff -Nru python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/middlewares.py python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/middlewares.py --- python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/middlewares.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/middlewares.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,41 +0,0 @@ -import aiohttp_jinja2 -from aiohttp import web - - -async def handle_404(request, response): - response = aiohttp_jinja2.render_template('404.html', - request, - {}) - return response - - -async def handle_500(request, response): - response = aiohttp_jinja2.render_template('500.html', - request, - {}) - return response - - -def error_pages(overrides): - @web.middleware - async def middleware(request, handler): - try: - response = await handler(request) - override = overrides.get(response.status) - if override is None: - return response - else: - return await override(request, response) - except web.HTTPException as ex: - override = overrides.get(ex.status) - if override is None: - raise - else: - return await override(request, ex) - return middleware - - -def setup_middlewares(app): - error_middleware = error_pages({404: handle_404, - 500: handle_500}) - app.middlewares.append(error_middleware) diff -Nru python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/routes.py python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/routes.py --- python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/routes.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/routes.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,21 +0,0 @@ -import pathlib - -from .views import index, poll, results, vote - - -PROJECT_ROOT = pathlib.Path(__file__).parent - - -def setup_routes(app): - app.router.add_get('/', index) - app.router.add_get('/poll/{question_id}', poll, name='poll') - app.router.add_get('/poll/{question_id}/results', - results, name='results') - app.router.add_post('/poll/{question_id}/vote', vote, name='vote') - setup_static_routes(app) - - -def setup_static_routes(app): - app.router.add_static('/static/', - path=PROJECT_ROOT / 'static', - name='static') diff -Nru python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/static/style.css python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/static/style.css --- python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/static/style.css 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/static/style.css 1970-01-01 00:00:00.000000000 +0000 @@ -1,7 +0,0 @@ -li a { - color: green; -} - -body { - background: white url("images/background.gif") no-repeat right bottom; -} diff -Nru python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/templates/404.html python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/templates/404.html --- python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/templates/404.html 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/templates/404.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -{% extends "base.html" %} - -{% set title = "Page Not Found" %} diff -Nru python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/templates/500.html python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/templates/500.html --- python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/templates/500.html 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/templates/500.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -{% extends "base.html" %} - -{% set title = "Internal Server Error" %} diff -Nru python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/templates/base.html python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/templates/base.html --- python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/templates/base.html 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/templates/base.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ - - - - {% block head %} - - {{title}} - {% endblock %} - - -

{{title}}

-
- {% block content %} - {% endblock %} -
- - diff -Nru python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/templates/detail.html python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/templates/detail.html --- python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/templates/detail.html 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/templates/detail.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,15 +0,0 @@ -{% extends "base.html" %} - -{% set title = question.question_text %} - -{% block content %} -{% if error_message %}

{{ error_message }}

{% endif %} - -
-{% for choice in choices %} - -
-{% endfor %} - -
-{% endblock %} diff -Nru python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/templates/index.html python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/templates/index.html --- python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/templates/index.html 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/templates/index.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,15 +0,0 @@ -{% extends "base.html" %} - -{% set title = "Main" %} - -{% block content %} -{% if questions %} - -{% else %} -

No polls are available.

-{% endif %} -{% endblock %} diff -Nru python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/templates/results.html python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/templates/results.html --- python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/templates/results.html 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/templates/results.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,13 +0,0 @@ -{% extends "base.html" %} - -{% set title = question.question_text %} - -{% block content %} -
    -{% for choice in choices %} -
  • {{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes }}
  • -{% endfor %} -
- -Vote again? -{% endblock %} diff -Nru python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/utils.py python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/utils.py --- python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/utils.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/utils.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -import trafaret as T - - -TRAFARET = T.Dict({ - T.Key('postgres'): - T.Dict({ - 'database': T.String(), - 'user': T.String(), - 'password': T.String(), - 'host': T.String(), - 'port': T.Int(), - 'minsize': T.Int(), - 'maxsize': T.Int(), - }), - T.Key('host'): T.IP, - T.Key('port'): T.Int(), -}) diff -Nru python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/views.py python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/views.py --- python-aiohttp-3.1.3/demos/polls/aiohttpdemo_polls/views.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/aiohttpdemo_polls/views.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,63 +0,0 @@ -import aiohttp_jinja2 -from aiohttp import web - -from . import db - - -@aiohttp_jinja2.template('index.html') -async def index(request): - async with request.app['db'].acquire() as conn: - cursor = await conn.execute(db.question.select()) - records = await cursor.fetchall() - questions = [dict(q) for q in records] - return {'questions': questions} - - -@aiohttp_jinja2.template('detail.html') -async def poll(request): - async with request.app['db'].acquire() as conn: - question_id = request.match_info['question_id'] - try: - question, choices = await db.get_question(conn, - question_id) - except db.RecordNotFound as e: - raise web.HTTPNotFound(text=str(e)) - return { - 'question': question, - 'choices': choices - } - - -@aiohttp_jinja2.template('results.html') -async def results(request): - async with request.app['db'].acquire() as conn: - question_id = request.match_info['question_id'] - - try: - question, choices = await db.get_question(conn, - question_id) - except db.RecordNotFound as e: - raise web.HTTPNotFound(text=str(e)) - - return { - 'question': question, - 'choices': choices - } - - -async def vote(request): - async with request.app['db'].acquire() as conn: - question_id = int(request.match_info['question_id']) - data = await request.post() - try: - choice_id = int(data['choice']) - except (KeyError, TypeError, ValueError) as e: - raise web.HTTPBadRequest( - text='You have not specified choice value') from e - try: - await db.vote(conn, question_id, choice_id) - except db.RecordNotFound as e: - raise web.HTTPNotFound(text=str(e)) - router = request.app.router - url = router['results'].url(parts={'question_id': question_id}) - return web.HTTPFound(location=url) diff -Nru python-aiohttp-3.1.3/demos/polls/config/polls.yaml python-aiohttp-3.5.1/demos/polls/config/polls.yaml --- python-aiohttp-3.1.3/demos/polls/config/polls.yaml 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/config/polls.yaml 1970-01-01 00:00:00.000000000 +0000 @@ -1,11 +0,0 @@ -postgres: - database: aiohttpdemo_polls - user: aiohttpdemo_user - password: aiohttpdemo_user - host: localhost - port: 5432 - minsize: 1 - maxsize: 5 - -host: 127.0.0.1 -port: 8080 Binary files /tmp/tmpYRAZo5/bce_IiBcz8/python-aiohttp-3.1.3/demos/polls/images/example.png and /tmp/tmpYRAZo5/6pNZuTByL6/python-aiohttp-3.5.1/demos/polls/images/example.png differ diff -Nru python-aiohttp-3.1.3/demos/polls/Makefile python-aiohttp-3.5.1/demos/polls/Makefile --- python-aiohttp-3.1.3/demos/polls/Makefile 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/Makefile 1970-01-01 00:00:00.000000000 +0000 @@ -1,28 +0,0 @@ -# Some simple testing tasks (sorry, UNIX only). - -FLAGS= - - -flake: - pyflakes aiohttpdemo_polls - pep8 aiohttpdemo_polls setup.py - -test: - pytest tests - -clean: - rm -rf `find . -name __pycache__` - rm -f `find . -type f -name '*.py[co]' ` - rm -f `find . -type f -name '*~' ` - rm -f `find . -type f -name '.*~' ` - rm -f `find . -type f -name '@*' ` - rm -f `find . -type f -name '#*#' ` - rm -f `find . -type f -name '*.orig' ` - rm -f `find . -type f -name '*.rej' ` - rm -f .coverage - rm -rf coverage - rm -rf build - rm -rf htmlcov - rm -rf dist - -.PHONY: flake clean test diff -Nru python-aiohttp-3.1.3/demos/polls/README.rst python-aiohttp-3.5.1/demos/polls/README.rst --- python-aiohttp-3.1.3/demos/polls/README.rst 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/README.rst 1970-01-01 00:00:00.000000000 +0000 @@ -1,48 +0,0 @@ -Polls (demo for aiohttp) -======================== - -Example of polls project using aiohttp_, aiopg_ and aiohttp_jinja2_, -similar to django one. - -Installation -============ - -Install the app:: - - $ cd demos/polls - $ pip install -e . - -Create database for your project:: - - bash sql/install.sh - -Run application:: - - $ python -m aiohttpdemo_polls - - -Open browser:: - - http://localhost:8080/ - -.. image:: https://raw.githubusercontent.com/andriisoldatenko/aiohttp_polls/master/images/example.png - :align: center - - -Run integration tests:: - - pip install tox - tox - - -Requirements -============ -* aiohttp_ -* aiopg_ -* aiohttp_jinja2_ - - -.. _Python: https://www.python.org -.. _aiohttp: https://github.com/aio-libs/aiohttp -.. _aiopg: https://github.com/aio-libs/aiopg -.. _aiohttp_jinja2: https://github.com/aio-libs/aiohttp_jinja2 diff -Nru python-aiohttp-3.1.3/demos/polls/requirements.txt python-aiohttp-3.5.1/demos/polls/requirements.txt --- python-aiohttp-3.1.3/demos/polls/requirements.txt 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/requirements.txt 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ --e . -docker-py==1.10.6 -pytest-aiohttp==0.3.0 -trafaret_config==1.0.1 diff -Nru python-aiohttp-3.1.3/demos/polls/setup.py python-aiohttp-3.5.1/demos/polls/setup.py --- python-aiohttp-3.1.3/demos/polls/setup.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/setup.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,37 +0,0 @@ -import os -import re - -from setuptools import find_packages, setup - - -def read_version(): - regexp = re.compile(r"^__version__\W*=\W*'([\d.abrc]+)'") - init_py = os.path.join(os.path.dirname(__file__), - 'aiohttpdemo_polls', '__init__.py') - with open(init_py) as f: - for line in f: - match = regexp.match(line) - if match is not None: - return match.group(1) - else: - msg = 'Cannot find version in aiohttpdemo_polls/__init__.py' - raise RuntimeError(msg) - - -install_requires = ['aiohttp', - 'aiopg[sa]', - 'aiohttp-jinja2', - 'trafaret-config'] - - -setup(name='aiohttpdemo-polls', - version=read_version(), - description='Polls project example from aiohttp', - platforms=['POSIX'], - packages=find_packages(), - package_data={ - '': ['templates/*.html', 'static/*.*'] - }, - include_package_data=True, - install_requires=install_requires, - zip_safe=False) diff -Nru python-aiohttp-3.1.3/demos/polls/sql/create_tables.sql python-aiohttp-3.5.1/demos/polls/sql/create_tables.sql --- python-aiohttp-3.1.3/demos/polls/sql/create_tables.sql 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/sql/create_tables.sql 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -SET ROLE 'aiohttpdemo_user'; - -BEGIN; --- --- Create model Choice --- -CREATE TABLE "choice" ("id" serial NOT NULL PRIMARY KEY, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL); --- --- Create model Question --- -CREATE TABLE "question" ("id" serial NOT NULL PRIMARY KEY, "question_text" varchar(200) NOT NULL, "pub_date" timestamp with time zone NOT NULL); --- --- Add field question to choice --- -ALTER TABLE "choice" ADD COLUMN "question_id" integer NOT NULL; -ALTER TABLE "choice" ALTER COLUMN "question_id" DROP DEFAULT; -CREATE INDEX "choice_7aa0f6ee" ON "choice" ("question_id"); -ALTER TABLE "choice" ADD CONSTRAINT "choice_question_id_c5b4b260_fk_question_id" FOREIGN KEY ("question_id") REFERENCES "question" ("id") DEFERRABLE INITIALLY DEFERRED; - -COMMIT; diff -Nru python-aiohttp-3.1.3/demos/polls/sql/install.sh python-aiohttp-3.5.1/demos/polls/sql/install.sh --- python-aiohttp-3.1.3/demos/polls/sql/install.sh 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/sql/install.sh 1970-01-01 00:00:00.000000000 +0000 @@ -1,15 +0,0 @@ -# determine os -unameOut="$(uname -s)" -case "${unameOut}" in - Darwin*) pg_cmd="psql -U postgres";; - *) pg_cmd="sudo -u postgres psql" -esac - -${pg_cmd} -c "DROP DATABASE IF EXISTS aiohttpdemo_polls" -${pg_cmd} -c "DROP ROLE IF EXISTS aiohttpdemo_user" -${pg_cmd} -c "CREATE USER aiohttpdemo_user WITH PASSWORD 'aiohttpdemo_user';" -${pg_cmd} -c "CREATE DATABASE aiohttpdemo_polls ENCODING 'UTF8';" -${pg_cmd} -c "GRANT ALL PRIVILEGES ON DATABASE aiohttpdemo_polls TO aiohttpdemo_user;" - -cat sql/create_tables.sql | ${pg_cmd} -d aiohttpdemo_polls -a -cat sql/sample_data.sql | ${pg_cmd} -d aiohttpdemo_polls -a diff -Nru python-aiohttp-3.1.3/demos/polls/sql/sample_data.sql python-aiohttp-3.5.1/demos/polls/sql/sample_data.sql --- python-aiohttp-3.1.3/demos/polls/sql/sample_data.sql 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/sql/sample_data.sql 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -SET ROLE 'aiohttpdemo_user'; - -INSERT INTO question (id, question_text, pub_date) VALUES (1, 'What''s new?', '2015-12-15 17:17:49.629+02'); - - --- --- Name: question_id_seq; Type: SEQUENCE SET; Schema: public; Owner: polls --- - -SELECT pg_catalog.setval('question_id_seq', 1, true); - - -INSERT INTO choice (id, choice_text, votes, question_id) VALUES (1, 'Not much', 0, 1); -INSERT INTO choice (id, choice_text, votes, question_id) VALUES (2, 'The sky', 0, 1); -INSERT INTO choice (id, choice_text, votes, question_id) VALUES (3, 'Just hacking again', 0, 1); - - --- --- Name: choice_id_seq; Type: SEQUENCE SET; Schema: public; Owner: polls --- - -SELECT pg_catalog.setval('choice_id_seq', 3, true); diff -Nru python-aiohttp-3.1.3/demos/polls/tests/conftest.py python-aiohttp-3.5.1/demos/polls/tests/conftest.py --- python-aiohttp-3.1.3/demos/polls/tests/conftest.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/tests/conftest.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,30 +0,0 @@ -import pathlib -import subprocess - -import pytest - -from aiohttpdemo_polls.main import init - - -BASE_DIR = pathlib.Path(__file__).parent.parent - - -@pytest.fixture -def config_path(): - path = BASE_DIR / 'config' / 'polls.yaml' - return path.as_posix() - - -@pytest.fixture -def cli(loop, test_client, config_path): - app = init(loop, ['-c', config_path]) - return loop.run_until_complete(test_client(app)) - - -@pytest.fixture -def app_db(): - subprocess.call( - [(BASE_DIR / 'sql' / 'install.sh').as_posix()], - shell=True, - cwd=BASE_DIR.as_posix() - ) diff -Nru python-aiohttp-3.1.3/demos/polls/tests/test_integration.py python-aiohttp-3.5.1/demos/polls/tests/test_integration.py --- python-aiohttp-3.1.3/demos/polls/tests/test_integration.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/tests/test_integration.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -""" -Integration tests. They need a running database. - -Beware, they destroy your db using sudo. -""" - - -async def test_index(cli, app_db): - response = await cli.get('/poll/1') - assert response.status == 200 - assert 'What\'s new?' in await response.text() - - -async def test_results(cli, app_db): - response = await cli.get('/poll/1/results') - assert response.status == 200 - assert 'Just hacking again' in await response.text() diff -Nru python-aiohttp-3.1.3/demos/polls/tox.ini python-aiohttp-3.5.1/demos/polls/tox.ini --- python-aiohttp-3.1.3/demos/polls/tox.ini 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/demos/polls/tox.ini 1970-01-01 00:00:00.000000000 +0000 @@ -1,9 +0,0 @@ -[tox] -envlist = py35 - -[testenv] -deps = - pytest - pytest-aiohttp -usedevelop = True -commands=py.test tests -s diff -Nru python-aiohttp-3.1.3/demos/README.rst python-aiohttp-3.5.1/demos/README.rst --- python-aiohttp-3.1.3/demos/README.rst 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/demos/README.rst 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -aiohttp demos -============= diff -Nru python-aiohttp-3.1.3/docs/built_with.rst python-aiohttp-3.5.1/docs/built_with.rst --- python-aiohttp-3.1.3/docs/built_with.rst 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/built_with.rst 2018-12-24 20:58:54.000000000 +0000 @@ -22,3 +22,4 @@ * `Arsenic `_ Async WebDriver. * `Home Assistant `_ Home Automation Platform. * `Backend.AI `_ Code execution API service. +* `doh-proxy `_ DNS Over HTTPS Proxy. diff -Nru python-aiohttp-3.1.3/docs/client_advanced.rst python-aiohttp-3.5.1/docs/client_advanced.rst --- python-aiohttp-3.1.3/docs/client_advanced.rst 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/client_advanced.rst 2018-12-24 20:58:54.000000000 +0000 @@ -52,9 +52,9 @@ await session.post(url, json={'example': 'text'}) -The same for *text/plain*:: +For *text/plain* :: - await session.post(url, text='Привет, Мир!') + await session.post(url, data='Привет, Мир!') Custom Cookies -------------- diff -Nru python-aiohttp-3.1.3/docs/client_quickstart.rst python-aiohttp-3.5.1/docs/client_quickstart.rst --- python-aiohttp-3.1.3/docs/client_quickstart.rst 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/client_quickstart.rst 2018-12-24 20:58:54.000000000 +0000 @@ -61,6 +61,15 @@ A session contains a connection pool inside. Connection reusage and keep-alives (both are on by default) may speed up total performance. +A session context manager usage is not mandatory +but ``await session.close()`` method +should be called in this case, e.g.:: + + session = aiohttp.ClientSession() + async with session.get('...'): + # ... + await session.close() + Passing Parameters In URLs ========================== @@ -91,7 +100,7 @@ params = [('key', 'value1'), ('key', 'value2')] async with session.get('http://httpbin.org/get', params=params) as r: - expect == 'http://httpbin.org/get?key=value2&key=value1' + expect = 'http://httpbin.org/get?key=value2&key=value1' assert str(r.url) == expect You can also pass :class:`str` content as param, but beware -- content @@ -108,7 +117,7 @@ Canonization encodes *host* part by :term:`IDNA` codec and applies :term:`requoting` to *path* and *query* parts. - For example ``URL('http://example.com/путь%30?a=%31')`` is converted to + For example ``URL('http://example.com/путь/%30?a=%31')`` is converted to ``URL('http://example.com/%D0%BF%D1%83%D1%82%D1%8C/0?a=1')``. Sometimes canonization is not desirable if server accepts exact @@ -126,7 +135,7 @@ Response Content and Status Code ================================ -We can read the content of the server's response and it's status +We can read the content of the server's response and its status code. Consider the GitHub time-line again:: async with session.get('https://api.github.com/events') as resp: @@ -275,7 +284,7 @@ To send text with appropriate content-type just use ``text`` attribute :: - async with session.post(url, text='Тест') as resp: + async with session.post(url, data='Тест') as resp: ... POST a Multipart-Encoded File @@ -368,9 +377,7 @@ object you can communicate with websocket server using response's methods:: - session = aiohttp.ClientSession() async with session.ws_connect('http://example.org/ws') as ws: - async for msg in ws: if msg.type == aiohttp.WSMsgType.TEXT: if msg.data == 'close cmd': @@ -378,8 +385,6 @@ break else: await ws.send_str(msg.data + '/answer') - elif msg.type == aiohttp.WSMsgType.CLOSED: - break elif msg.type == aiohttp.WSMsgType.ERROR: break @@ -390,31 +395,55 @@ ``await ws.send_str('data')`` for example). +.. _aiohttp-client-timeouts: Timeouts ======== -By default all IO operations have 5min timeout. The timeout may be -overridden by passing ``timeout`` parameter into -:meth:`ClientSession.get` and family:: +Timeout settings a stored in :class:`ClientTimeout` data structure. + +By default *aiohttp* uses a *total* 5min timeout, it means that the +whole operation should finish in 5 minutes. - async with session.get('https://github.com', timeout=60) as r: +The value could be overridden by *timeout* parameter for the session:: + + timeout = aiohttp.ClientTimeout(total=60) + async with aiohttp.ClientSession(timeout=timeout) as session: ... -``None`` or ``0`` disables timeout check. +Timeout could be overridden for a request like :meth:`ClientSession.get`:: -The example wraps a client call in :func:`async_timeout.timeout` context -manager, adding timeout for both connecting and response body -reading procedures:: + async with session.get(url, timeout=timeout) as resp: + ... - import async_timeout +Supported :class:`ClientTimeout` fields are: - with async_timeout.timeout(0.001): - async with session.get('https://github.com') as r: - await r.text() + ``total`` + The whole operation time including connection + establishment, request sending and response reading. -.. note:: + ``connect`` + + The time + consists connection establishment for a new connection or + waiting for a free connection from a pool if pool connection + limits are exceeded. + + ``sock_connect`` + + A timeout for connecting to a peer for a new connection, not + given from a pool. + + ``sock_read`` + + The maximum allowed timeout for period between reading a new + data portion from a peer. + +All fields are floats, ``None`` or ``0`` disables a particular timeout check, see the +:class:`ClientTimeout` reference for defaults and additional details. + +Thus the default timeout is:: - Timeout is cumulative time, it includes all operations like sending request, - redirects, response parsing, consuming response, etc. + aiohttp.ClientTimeout(total=5*60, connect=None, + sock_connect=None, sock_read=None) diff -Nru python-aiohttp-3.1.3/docs/client_reference.rst python-aiohttp-3.5.1/docs/client_reference.rst --- python-aiohttp-3.1.3/docs/client_reference.rst 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/client_reference.rst 2018-12-24 20:58:54.000000000 +0000 @@ -45,9 +45,13 @@ version=aiohttp.HttpVersion11, \ cookie_jar=None, read_timeout=None, \ conn_timeout=None, \ + timeout=sentinel, \ raise_for_status=False, \ connector_owner=True, \ - auto_decompress=True, proxies=None) + auto_decompress=True, \ + requote_redirect_url=False, \ + trust_env=False, \ + trace_configs=None) The class for creating client sessions and making requests. @@ -113,16 +117,39 @@ Automatically call :meth:`ClientResponse.raise_for_status()` for each response, ``False`` by default. - .. versionadded:: 2.0 + This parameter can be overridden when you making a request, e.g.:: + + client_session = aiohttp.ClientSession(raise_for_status=True) + resp = await client_session.get(url, raise_for_status=False) + async with resp: + assert resp.status == 200 + + Set the parameter to ``True`` if you need ``raise_for_status`` + for most of cases but override ``raise_for_status`` for those + requests where you need to handle responses with status 400 or + higher. + + :param timeout: a :class:`ClientTimeout` settings structure, 5min + total timeout by default. + + .. versionadded:: 3.3 :param float read_timeout: Request operations timeout. ``read_timeout`` is cumulative for all request operations (request, redirects, responses, data consuming). By default, the read timeout is 5*60 seconds. Use ``None`` or ``0`` to disable timeout checks. + .. deprecated:: 3.3 + + Use ``timeout`` parameter instead. + :param float conn_timeout: timeout for connection establishing (optional). Values ``0`` or ``None`` mean no timeout. + .. deprecated:: 3.3 + + Use ``timeout`` parameter instead. + :param bool connector_owner: Close connector instance on session closing. @@ -131,18 +158,16 @@ connection pool between sessions without sharing session state: cookies etc. - .. versionadded:: 2.1 - - :param bool auto_decompress: Automatically decompress response body + :param bool auto_decompress: Automatically decompress response body, + ``True`` by default .. versionadded:: 2.3 :param bool trust_env: Get proxies information from *HTTP_PROXY* / - *HTTPS_PROXY* environment variables if the - parameter is ``True`` (``False`` by default). + *HTTPS_PROXY* environment variables if the parameter is ``True`` + (``False`` by default). - Get proxy credentials from ``~/.netrc`` file if - present. + Get proxy credentials from ``~/.netrc`` file if present. .. seealso:: @@ -154,6 +179,17 @@ Added support for ``~/.netrc`` file. + :param bool requote_redirect_url: Apply *URL requoting* for redirection URLs if + automatic redirection is enabled (``True`` by + default). + + .. versionadded:: 3.5 + + :param trace_configs: A list of :class:`TraceConfig` instances used for client + tracing. ``None`` (default) is used for request tracing + disabling. See :ref:`aiohttp-client-tracing-reference` for + more information. + .. attribute:: closed ``True`` if the session has been closed, ``False`` otherwise. @@ -185,19 +221,25 @@ .. note:: This parameter affects all subsequent requests. + .. deprecated:: 3.5 + + The attribute modification is deprecated. + .. attribute:: loop A loop instance used for session creation. A read-only property. + .. deprecated:: 3.5 + .. comethod:: request(method, url, *, params=None, data=None, json=None,\ - headers=None, skip_auto_headers=None, \ + cookies=None, headers=None, skip_auto_headers=None, \ auth=None, allow_redirects=True,\ max_redirects=10,\ - compress=None, chunked=None, expect100=False,\ + compress=None, chunked=None, expect100=False, raise_for_status=None,\ read_until_eof=True, proxy=None, proxy_auth=None,\ - timeout=5*60, ssl=None, \ + timeout=sentinel, ssl=None, \ verify_ssl=None, fingerprint=None, \ ssl_context=None, proxy_headers=None) :async-with: @@ -231,6 +273,14 @@ (optional). *json* and *data* parameters could not be used at the same time. + :param dict cookies: HTTP Cookies to send with + the request (optional) + + Global session cookies and the explicitly set cookies will be merged + when sending the request. + + .. versionadded:: 3.5 + :param dict headers: HTTP Headers to send with the request (optional) @@ -251,6 +301,9 @@ :param bool allow_redirects: If set to ``False``, do not follow redirects. ``True`` by default (optional). + :param int max_redirects: Maximum number of redirects to follow. + ``10`` by default. + :param bool compress: Set to ``True`` if request has to be compressed with deflate encoding. If `compress` can not be combined with a *Content-Encoding* and *Content-Length* headers. @@ -266,6 +319,13 @@ :param bool expect100: Expect 100-continue response from server. ``False`` by default (optional). + :param bool raise_for_status: Automatically call :meth:`ClientResponse.raise_for_status()` for + response if set to ``True``. + If set to ``None`` value from ``ClientSession`` will be used. + ``None`` by default (optional). + + .. versionadded:: 3.4 + :param bool read_until_eof: Read response until EOF if response does not have Content-Length header. ``True`` by default (optional). @@ -275,8 +335,15 @@ :param aiohttp.BasicAuth proxy_auth: an object that represents proxy HTTP Basic Authorization (optional) - :param int timeout: override the session's timeout - (``read_timeout``) for IO operations. + :param int timeout: override the session's timeout. + + .. versionchanged:: 3.3 + + The parameter is :class:`ClientTimeout` instance, + :class:`float` is still supported for sake of backward + compatibility. + + If :class:`float` is passed it is a *total* timeout. :param ssl: SSL validation mode. ``None`` for default SSL check (:func:`ssl.create_default_context` is used), @@ -467,17 +534,19 @@ :return ClientResponse: a :class:`client response ` object. - .. comethod:: ws_connect(url, *, protocols=(), timeout=10.0,\ + .. comethod:: ws_connect(url, *, method='GET', \ + protocols=(), timeout=10.0,\ receive_timeout=None,\ auth=None,\ autoclose=True,\ autoping=True,\ heartbeat=None,\ origin=None, \ + headers=None, \ proxy=None, proxy_auth=None, ssl=None, \ verify_ssl=None, fingerprint=None, \ ssl_context=None, proxy_headers=None, \ - compress=0) + compress=0, max_msg_size=4194304) :async-with: :coroutine: @@ -500,18 +569,22 @@ :param bool autoclose: Automatically close websocket connection on close message from server. If *autoclose* is False - them close procedure has to be handled manually + then close procedure has to be handled manually. + ``True`` by default :param bool autoping: automatically send *pong* on *ping* - message from server + message from server. ``True`` by default :param float heartbeat: Send *ping* message every *heartbeat* seconds and wait *pong* response, if *pong* response is not received then close connection. The timer is reset on any data - reception. + reception.(optional) + + :param str origin: Origin header to send to server(optional) - :param str origin: Origin header to send to server + :param dict headers: HTTP Headers to send with + the request (optional) :param str proxy: Proxy URL, :class:`str` or :class:`~yarl.URL` (optional) @@ -561,21 +634,32 @@ .. versionadded:: 2.3 + .. deprecated:: 3.0 + + Use ``ssl=ssl_context`` + :param dict proxy_headers: HTTP headers to send to the proxy if the parameter proxy has been provided. .. versionadded:: 2.3 - .. deprecated:: 3.0 - - Use ``ssl=ssl_context`` - :param int compress: Enable Per-Message Compress Extension support. 0 for disable, 9 to 15 for window bit support. Default value is 0. .. versionadded:: 2.3 + :param int max_msg_size: maximum size of read websocket message, + 4 MB by default. To disable the size + limit use ``0``. + + .. versionadded:: 3.3 + + :param str method: HTTP method to establish WebSocket connection, + ``'GET'`` by default. + + .. versionadded:: 3.5 + .. comethod:: close() @@ -608,9 +692,9 @@ allow_redirects=True, max_redirects=10, \ encoding='utf-8', \ version=HttpVersion(major=1, minor=1), \ - compress=None, chunked=None, expect100=False, \ + compress=None, chunked=None, expect100=False, raise_for_status=False, \ connector=None, loop=None,\ - read_until_eof=True) + read_until_eof=True, timeout=sentinel) :async-with: @@ -653,6 +737,15 @@ :param bool expect100: Expect 100-continue response from server. ``False`` by default (optional). + :param bool raise_for_status: Automatically call + :meth:`ClientResponse.raise_for_status()` + for response if set to ``True``. If + set to ``None`` value from + ``ClientSession`` will be used. + ``None`` by default (optional). + + .. versionadded:: 3.4 + :param aiohttp.connector.BaseConnector connector: BaseConnector sub-class instance to support connection pooling. @@ -660,6 +753,9 @@ does not have Content-Length header. ``True`` by default (optional). + :param timeout: a :class:`ClientTimeout` settings structure, 5min + total timeout by default. + :param loop: :ref:`event loop` used for processing HTTP requests. If param is ``None``, :func:`asyncio.get_event_loop` @@ -765,12 +861,10 @@ Read-only property. - .. method:: close() + .. comethod:: close() Close all opened connections. - .. versionadded:: 2.0 - .. comethod:: connect(request) Get a free connection from pool or create new one if connection @@ -859,8 +953,6 @@ this option to keep the DNS cache updated refreshing each entry after N seconds. - .. versionadded:: 2.0.8 - :param int limit: total number simultaneous connections. If *limit* is ``None`` the connector has no limit (default: 100). @@ -988,6 +1080,8 @@ Event loop used for connection + .. deprecated:: 3.5 + .. attribute:: transport Connection transport @@ -1004,13 +1098,6 @@ later if timeout (30 seconds by default) for connection was not expired. - .. method:: detach() - - Detach underlying socket from connection. - - Underlying socket is not closed, next :meth:`close` or - :meth:`release` calls don't return socket to free pool. - Response object --------------- @@ -1051,6 +1138,12 @@ URL of request (:class:`~yarl.URL`). + .. attribute:: real_url + + Unmodified URL of request with URL fragment unstripped (:class:`~yarl.URL`). + + .. versionadded:: 3.2 + .. attribute:: connection :class:`Connection` used for handling response. @@ -1083,6 +1176,16 @@ Unmodified HTTP headers of response as unconverted bytes, a sequence of ``(key, value)`` pairs. + .. attribute:: links + + Link HTTP header parsed into a :class:`~multidict.MultiDictProxy`. + + For each link, key is link param `rel` when it exists, or link url as + :class:`str` otherwise, and value is :class:`~multidict.MultiDictProxy` + of link params and url at key `url` as :class:`~yarl.URL` instance. + + .. versionadded:: 3.2 + .. attribute:: content_type Read-only property with *content* part of *Content-Type* header. @@ -1425,12 +1528,55 @@ --------- +ClientTimeout +^^^^^^^^^^^^^ + +.. class:: ClientTimeout(*, total=None, connect=None, \ + sock_connect, sock_read=None) + + A data class for client timeout settings. + + See :ref:`aiohttp-client-timeouts` for usage examples. + + .. attribute:: total + + Total timeout for the whole request. + + :class:`float`, ``None`` by default. + + .. attribute:: connect + + Total timeout for acquiring a connection from pool. The time + consists connection establishment for a new connection or + waiting for a free connection from a pool if pool connection + limits are exceeded. + + For pure socket connection establishment time use + :attr:`sock_connect`. + + :class:`float`, ``None`` by default. + + .. attribute:: sock_connect + + A timeout for connecting to a peer for a new connection, not + given from a pool. See also :attr:`connect`. + + :class:`float`, ``None`` by default. + + .. attribute:: sock_read + + A timeout for reading a portion of data from a peer. + + :class:`float`, ``None`` by default. + + .. versionadded:: 3.3 + RequestInfo ^^^^^^^^^^^ .. class:: RequestInfo() - A namedtuple with request URL and headers from :class:`ClientRequest` + A data class with request URL and headers from :class:`ClientRequest` object, available as :attr:`ClientResponse.request_info` attribute. .. attribute:: url @@ -1445,6 +1591,12 @@ HTTP headers for request, :class:`multidict.CIMultiDict` instance. + .. attribute:: real_url + + Requested *url* with URL fragment unstripped, :class:`yarl.URL` instance. + + .. versionadded:: 3.2 + BasicAuth ^^^^^^^^^ @@ -1707,20 +1859,25 @@ Derived from :exc:`ClientResponseError` -.. class:: WSServerHandshakeError +.. class:: ContentTypeError - Web socket server response error. + Invalid content type. Derived from :exc:`ClientResponseError` + .. versionadded:: 2.3 -.. class:: ContentTypeError - Invalid content type. +.. class:: TooManyRedirects + + Client was redirected too many times. + + Maximum number of redirects can be configured by using + parameter ``max_redirects`` in :meth:`request`. Derived from :exc:`ClientResponseError` - .. versionadded:: 2.3 + .. versionadded:: 3.2 Connection errors ^^^^^^^^^^^^^^^^^ diff -Nru python-aiohttp-3.1.3/docs/conf.py python-aiohttp-3.5.1/docs/conf.py --- python-aiohttp-3.1.3/docs/conf.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/conf.py 2018-12-24 20:58:54.000000000 +0000 @@ -13,7 +13,7 @@ # All configuration values have a default; values that are commented out # serve to show the default. -import codecs +import io import os import re import sys @@ -21,7 +21,7 @@ _docs_path = os.path.dirname(__file__) _version_path = os.path.abspath(os.path.join(_docs_path, '..', 'aiohttp', '__init__.py')) -with codecs.open(_version_path, 'r', 'latin1') as fp: +with io.open(_version_path, 'r', encoding='latin1') as fp: try: _version_info = re.search(r"^__version__ = '" r"(?P\d+)" @@ -33,13 +33,6 @@ raise RuntimeError('Unable to determine version.') -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath('..')) -sys.path.insert(0, os.path.abspath('.')) - - # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. @@ -49,11 +42,9 @@ # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ - 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', 'sphinxcontrib.asyncio', - 'sphinxcontrib.asyncio', 'sphinxcontrib.blockdiag', ] @@ -76,7 +67,10 @@ 'aiohttpremotes': ('https://aiohttp-remotes.readthedocs.io/en/stable/', None), 'aiohttpsession': - ('https://aiohttp-session.readthedocs.io/en/stable/', None)} + ('https://aiohttp-session.readthedocs.io/en/stable/', None), + 'aiohttpdemos': + ('https://aiohttp-demos.readthedocs.io/en/latest/', None), +} # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] @@ -163,8 +157,8 @@ 'github_button': True, 'github_type': 'star', 'github_banner': True, - 'badges': [{'image': 'https://secure.travis-ci.org/aio-libs/aiohttp.svg?branch=master', - 'target': 'https://travis-ci.org/aio-libs/aiohttp', + 'badges': [{'image': 'https://travis-ci.com/aio-libs/aiohttp.svg?branch=master', + 'target': 'https://travis-ci.com/aio-libs/aiohttp', 'height': '20', 'alt': 'Travis CI status'}, {'image': 'https://codecov.io/github/aio-libs/aiohttp/coverage.svg?branch=master', diff -Nru python-aiohttp-3.1.3/docs/contributing.rst python-aiohttp-3.5.1/docs/contributing.rst --- python-aiohttp-3.1.3/docs/contributing.rst 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/contributing.rst 2018-12-24 20:58:54.000000000 +0000 @@ -1,3 +1,289 @@ .. _aiohttp-contributing: -.. include:: ../CONTRIBUTING.rst +Contributing +============ + +Instructions for contributors +----------------------------- + + +In order to make a clone of the GitHub_ repo: open the link and press the +"Fork" button on the upper-right menu of the web page. + +I hope everybody knows how to work with git and github nowadays :) + +Workflow is pretty straightforward: + + 1. Clone the GitHub_ repo using ``--recurse-submodules`` argument + + 2. Make a change + + 3. Make sure all tests passed + + 4. Add a file into ``CHANGES`` folder (`Changelog update`_). + + 5. Commit changes to own aiohttp clone + + 6. Make pull request from github page for your clone against master branch + + 7. Optionally make backport Pull Request(s) for landing a bug fix + into released aiohttp versions. + +.. note:: + + The project uses *Squash-and-Merge* strategy for *GitHub Merge* button. + + Basically it means that there is **no need to rebase** a Pull Request against + *master* branch. Just ``git merge`` *master* into your working copy (a fork) if + needed. The Pull Request is automatically squashed into the single commit + once the PR is accepted. + +Preconditions for running aiohttp test suite +-------------------------------------------- + +We expect you to use a python virtual environment to run our tests. + +There are several ways to make a virtual environment. + +If you like to use *virtualenv* please run: + +.. code-block:: shell + + $ cd aiohttp + $ virtualenv --python=`which python3` venv + $ . venv/bin/activate + +For standard python *venv*: + +.. code-block:: shell + + $ cd aiohttp + $ python3 -m venv venv + $ . venv/bin/activate + +For *virtualenvwrapper*: + +.. code-block:: shell + + $ cd aiohttp + $ mkvirtualenv --python=`which python3` aiohttp + +There are other tools like *pyvenv* but you know the rule of thumb +now: create a python3 virtual environment and activate it. + +After that please install libraries required for development: + +.. code-block:: shell + + $ pip install -r requirements/dev.txt + +.. note:: + + If you plan to use ``pdb`` or ``ipdb`` within the test suite, execute: + + .. code-block:: shell + + $ py.test tests -s + + command to run the tests with disabled output capturing. + +Congratulations, you are ready to run the test suite! + + +Run aiohttp test suite +---------------------- + +After all the preconditions are met you can run tests typing the next +command: + +.. code-block:: shell + + $ make test + +The command at first will run the *flake8* tool (sorry, we don't accept +pull requests with pep8 or pyflakes errors). + +On *flake8* success the tests will be run. + +Please take a look on the produced output. + +Any extra texts (print statements and so on) should be removed. + + +Tests coverage +-------------- + +We are trying hard to have good test coverage; please don't make it worse. + +Use: + +.. code-block:: shell + + $ make cov + +to run test suite and collect coverage information. Once the command +has finished check your coverage at the file that appears in the last +line of the output: +``open file:///.../aiohttp/htmlcov/index.html`` + +Please go to the link and make sure that your code change is covered. + + +The project uses *codecov.io* for storing coverage results. Visit +https://codecov.io/gh/aio-libs/aiohttp for looking on coverage of +master branch, history, pull requests etc. + +The browser extension https://docs.codecov.io/docs/browser-extension +is highly recommended for analyzing the coverage just in *Files +Changed* tab on *GitHub Pull Request* review page. + +Documentation +------------- + +We encourage documentation improvements. + +Please before making a Pull Request about documentation changes run: + +.. code-block:: shell + + $ make doc + +Once it finishes it will output the index html page +``open file:///.../aiohttp/docs/_build/html/index.html``. + +Go to the link and make sure your doc changes looks good. + +Spell checking +-------------- + +We use ``pyenchant`` and ``sphinxcontrib-spelling`` for running spell +checker for documentation: + +.. code-block:: shell + + $ make doc-spelling + +Unfortunately there are problems with running spell checker on MacOS X. + +To run spell checker on Linux box you should install it first: + +.. code-block:: shell + + $ sudo apt-get install enchant + $ pip install sphinxcontrib-spelling + +Changelog update +---------------- + +The ``CHANGES.rst`` file is managed using `towncrier +`_ tool and all non trivial +changes must be accompanied by a news entry. + +To add an entry to the news file, first you need to have created an +issue describing the change you want to make. A Pull Request itself +*may* function as such, but it is preferred to have a dedicated issue +(for example, in case the PR ends up rejected due to code quality +reasons). + +Once you have an issue or pull request, you take the number and you +create a file inside of the ``CHANGES/`` directory named after that +issue number with an extension of ``.removal``, ``.feature``, +``.bugfix``, or ``.doc``. Thus if your issue or PR number is ``1234`` and +this change is fixing a bug, then you would create a file +``CHANGES/1234.bugfix``. PRs can span multiple categories by creating +multiple files (for instance, if you added a feature and +deprecated/removed the old feature at the same time, you would create +``CHANGES/NNNN.feature`` and ``CHANGES/NNNN.removal``). Likewise if a PR touches +multiple issues/PRs you may create a file for each of them with the +exact same contents and *Towncrier* will deduplicate them. + +The contents of this file are *reStructuredText* formatted text that +will be used as the content of the news file entry. You do not need to +reference the issue or PR numbers here as *towncrier* will automatically +add a reference to all of the affected issues when rendering the news +file. + + + +Making a Pull Request +--------------------- + +After finishing all steps make a GitHub_ Pull Request with *master* base branch. + + +Backporting +----------- + +All Pull Requests are created against *master* git branch. + +If the Pull Request is not a new functionality but bug fixing +*backport* to maintenance branch would be desirable. + +*aiohttp* project committer may ask for making a *backport* of the PR +into maintained branch(es), in this case he or she adds a github label +like *needs backport to 3.1*. + +*Backporting* is performed *after* main PR merging into master. + Please do the following steps: + +1. Find *Pull Request's commit* for cherry-picking. + + *aiohttp* does *squashing* PRs on merging, so open your PR page on + github and scroll down to message like ``asvetlov merged commit + f7b8921 into master 9 days ago``. ``f7b8921`` is the required commit number. + +2. Run `cherry_picker + `_ + tool for making backport PR (the tool is already pre-installed from + ``./requirements/dev.txt``), e.g. ``cherry_picker f7b8921 3.1``. + +3. In case of conflicts fix them and continue cherry-picking by + ``cherry_picker --continue``. + + ``cherry_picker --abort`` stops the process. + + ``cherry_picker --status`` shows current cherry-picking status + (like ``git status``) + +4. After all conflicts are done the tool opens a New Pull Request page + in a browser with pre-filed information. Create a backport Pull + Request and wait for review/merging. + +5. *aiohttp* *committer* should remove *backport Git label* after + merging the backport. + +How to become an aiohttp committer +---------------------------------- + +Contribute! + +The easiest way is providing Pull Requests for issues in our bug +tracker. But if you have a great idea for the library improvement +-- please make an issue and Pull Request. + + + +The rules for committers are simple: + +1. No wild commits! Everything should go through PRs. +2. Take a part in reviews. It's very important part of maintainer's activity. +3. Pickup issues created by others, especially if they are simple. +4. Keep test suite comprehensive. In practice it means leveling up + coverage. 97% is not bad but we wish to have 100% someday. Well, 99% + is good target too. +5. Don't hesitate to improve our docs. Documentation is very important + thing, it's the key for project success. The documentation should + not only cover our public API but help newbies to start using the + project and shed a light on non-obvious gotchas. + + + +After positive answer aiohttp committer creates an issue on github +with the proposal for nomination. If the proposal will collect only +positive votes and no strong objection -- you'll be a new member in +our team. + + +.. _GitHub: https://github.com/aio-libs/aiohttp + +.. _ipdb: https://pypi.python.org/pypi/ipdb diff -Nru python-aiohttp-3.1.3/docs/deployment.rst python-aiohttp-3.5.1/docs/deployment.rst --- python-aiohttp-3.1.3/docs/deployment.rst 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/deployment.rst 2018-12-24 20:58:54.000000000 +0000 @@ -280,6 +280,8 @@ many worker processes to use for handling requests. (See the documentation for recommendations on `How Many Workers? `_) +* you may also want to use the *'--accesslog'* flag to enable the access + log to be populated. (See :ref:`logging ` for more information.) The custom worker subclass is defined in ``aiohttp.GunicornWebWorker``:: diff -Nru python-aiohttp-3.1.3/docs/external.rst python-aiohttp-3.5.1/docs/external.rst --- python-aiohttp-3.1.3/docs/external.rst 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/external.rst 2018-12-24 20:58:54.000000000 +0000 @@ -1,5 +1,5 @@ -Who use aiohttp? -================ +Who uses aiohttp? +================= The list of *aiohttp* users: both libraries, big projects and web sites. diff -Nru python-aiohttp-3.1.3/docs/faq.rst python-aiohttp-3.5.1/docs/faq.rst --- python-aiohttp-3.1.3/docs/faq.rst 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/faq.rst 2018-12-24 20:58:54.000000000 +0000 @@ -4,17 +4,18 @@ .. contents:: :local: -Are there any plans for @app.route decorator like in Flask? ------------------------------------------------------------ +Are there plans for an @app.route decorator like in Flask? +---------------------------------------------------------- -We have it already (*aiohttp>=2.3* required): +As of aiohttp 2.3, :class:`~aiohttp.web.RouteTableDef` provides an API +similar to Flask's ``@app.route``. See :ref:`aiohttp-web-alternative-routes-definition`. -The difference is: ``@app.route`` should have an ``app`` in module -global namespace, which makes *circular import hell* easy. +Unlike Flask's ``@app.route``, :class:`~aiohttp.web.RouteTableDef` +does not require an ``app`` in the module namespace (which often leads +to circular imports). -*aiohttp* provides a :class:`~aiohttp.web.RouteTableDef` decoupled - from an application instance:: +Instead, a :class:`~aiohttp.web.RouteTableDef` is decoupled from an application instance:: routes = web.RouteTableDef() @@ -30,36 +31,35 @@ app.router.add_routes(routes) -Has aiohttp the Flask Blueprint or Django App concept? ------------------------------------------------------- +Does aiohttp have a concept like Flask's "blueprint" or Django's "app"? +----------------------------------------------------------------------- -If you're planing to write big applications, maybe you must consider -use nested applications. They acts as a Flask Blueprint or like the -Django application concept. +If you're writing a large application, you may want to consider +using :ref:`nested applications `, which +are similar to Flask's "blueprints" or Django's "apps". -Using nested application you can add sub-applications to the main application. +See: :ref:`aiohttp-web-nested-applications`. -see: :ref:`aiohttp-web-nested-applications`. +How do I create a route that matches urls with a given prefix? +-------------------------------------------------------------- -How to create route that catches urls with given prefix? ---------------------------------------------------------- -Try something like:: +You can do something like the following: :: app.router.add_route('*', '/path/to/{tail:.+}', sink_handler) -Where first argument, star, means catch any possible method -(*GET, POST, OPTIONS*, etc), second matching ``url`` with desired prefix, -third -- handler. +The first argument, ``*``, matches any HTTP method +(*GET, POST, OPTIONS*, etc). The second argument matches URLS with the desired prefix. +The third argument is the handler function. -Where to put my database connection so handlers can access it? --------------------------------------------------------------- - -:class:`aiohttp.web.Application` object supports :class:`dict` -interface, and right place to store your database connections or any -other resource you want to share between handlers. Take a look on -following example:: +Where do I put my database connection so handlers can access it? +---------------------------------------------------------------- + +:class:`aiohttp.web.Application` object supports the :class:`dict` +interface and provides a place to store your database connections or any +other resource you want to share between handlers. +:: async def go(request): db = request.app['db'] @@ -77,71 +77,70 @@ return app -Why the minimal supported version is Python 3.5.3? --------------------------------------------------- +Why is Python 3.5.3 the lowest supported version? +------------------------------------------------- -Python 3.5.2 has fixed protocol for async iterators: ``__aiter()__`` is -not a coroutine but regular function. +Python 3.5.2 fixes the protocol for async iterators: ``__aiter__()`` is +not a coroutine but a regular function. -Python 3.5.3 is even more important: :func:`asyncio.get_event_loop` -returns the running loop instance if called from a coroutine -(previously was returning a *default* one, set by +Python 3.5.3 has a more important change: :func:`asyncio.get_event_loop` +returns the running loop instance if called from a coroutine. +Previously it returned a *default* loop, set by :func:`asyncio.set_event_loop`. -The change is very crucial, in Python < 3.5.3 -:func:`asyncio.get_event_loop` was not reliable, thus user *was -forced* to pass the event loop instance explicitly everywhere. - -Otherwise if a future object was created for using one event loop -(e.g. default) but a coroutine was run by other loop -- the coroutine -was never awaited, task was *hung*. +Previous to Python 3.5.3, +:func:`asyncio.get_event_loop` was not reliable, so users were +forced to explicitly pass the event loop instance everywhere. +If a future object were created for one event loop +(e.g. the default loop) but a coroutine was run by another loop, the coroutine +was never awaited. As a result, the task would hang. -Keep in mind that every ``await`` expression internally either passed -instantly or paused by waiting for a future. +Keep in mind that every internal ``await`` expression either passed +instantly or paused, waiting for a future. It's extremely important that all tasks (coroutine runners) and -futures are using the same event loop. +futures use the same event loop. -How a middleware may store a data for using by web-handler later? ------------------------------------------------------------------ +How can middleware store data for web handlers to use? +------------------------------------------------------ -:class:`aiohttp.web.Request` supports :class:`dict` interface as well -as :class:`aiohttp.web.Application`. +Both :class:`aiohttp.web.Request` and :class:`aiohttp.web.Application` +support the :class:`dict` interface. -Just put data inside *request*:: +Therefore, data may be stored inside a request object. :: async def handler(request): request['unique_key'] = data -See https://github.com/aio-libs/aiohttp_session code for inspiration, -``aiohttp_session.get_session(request)`` method uses ``SESSION_KEY`` -for saving request specific session info. +See https://github.com/aio-libs/aiohttp_session code for an example. +The ``aiohttp_session.get_session(request)`` method uses ``SESSION_KEY`` +for saving request-specific session information. -As of aiohttp 3.0 all response objects are *dict-like* structures as +As of aiohttp 3.0, all response objects are dict-like structures as well. .. _aiohttp_faq_parallel_event_sources: -How to receive an incoming events from different sources in parallel? ---------------------------------------------------------------------- +Can a handler receive incoming events from different sources in parallel? +------------------------------------------------------------------------- -For example we have two event sources: +Yes. - 1. WebSocket for event from end user +As an example, we may have two event sources: - 2. Redis PubSub from receiving events from other parts of app for - sending them to user via websocket. + 1. WebSocket for events from an end user -The most native way to perform it is creation of separate task for -pubsub handling. + 2. Redis PubSub for events from other parts of the application -Parallel :meth:`aiohttp.web.WebSocketResponse.receive` calls are forbidden, only -the single task should perform websocket reading. +The most native way to handle this is to create a separate task for +PubSub handling. -But other tasks may use the same websocket object for sending data to -peer:: +Parallel :meth:`aiohttp.web.WebSocketResponse.receive` calls are forbidden; +a single task should perform WebSocket reading. +However, other tasks may use the same WebSocket object for sending data to +peers. :: async def handler(request): @@ -172,18 +171,17 @@ .. _aiohttp_faq_terminating_websockets: -How to programmatically close websocket server-side? ----------------------------------------------------- +How do I programmatically close a WebSocket server-side? +-------------------------------------------------------- +Let's say we have an application with two endpoints: -For example we have an application with two endpoints: + 1. ``/echo`` a WebSocket echo server that authenticates the user + 2. ``/logout_user`` that, when invoked, closes all open + WebSockets for that user. - 1. ``/echo`` a websocket echo server that authenticates the user somehow - 2. ``/logout_user`` that when invoked needs to close all open - websockets for that user. - -One simple solution is keeping a shared registry of websocket +One simple solution is to keep a shared registry of WebSocket responses for a user in the :class:`aiohttp.web.Application` instance and call :meth:`aiohttp.web.WebSocketResponse.close` on all of them in ``/logout_user`` handler:: @@ -227,11 +225,11 @@ web.run_app(app, host='localhost', port=8080) -How to make request from a specific IP address? ------------------------------------------------ +How do I make a request from a specific IP address? +--------------------------------------------------- -If your system has several IP interfaces you may choose one which will -be used used to bind socket locally:: +If your system has several IP interfaces, you may choose one which will +be used used to bind a socket locally:: conn = aiohttp.TCPConnector(local_addr=('127.0.0.1', 0), loop=loop) async with aiohttp.ClientSession(connector=conn) as session: @@ -240,18 +238,18 @@ .. seealso:: :class:`aiohttp.TCPConnector` and ``local_addr`` parameter. -API stability and deprecation policy ------------------------------------- +What is the API stability and deprecation policy? +------------------------------------------------- -*aiohttp* follows strong [SemVer](https://semver.org/) schema. +*aiohttp* follows strong `Semantic Versioning `_ (SemVer). -Obsolete attributes and methods are marked as *deprecated* in -documentation and raises :class:`DeprecationWarning` on usage. +Obsolete attributes and methods are marked as *deprecated* in the +documentation and raise :class:`DeprecationWarning` upon usage. -Let's assume now we have aiohttp ``X.Y.Z`` where ``X`` is *major* version, +Assume aiohttp ``X.Y.Z`` where ``X`` is major version, ``Y`` is minor version and ``Z`` is bugfix number. -E.g. now the latest released version is ``aiohttp==3.0.6``. +For example, if the latest released version is ``aiohttp==3.0.6``: ``3.0.7`` fixes some bugs but have no new features. @@ -262,49 +260,170 @@ **except** deprecations from the **last** ``3.Y`` release. These deprecations will be removed by ``5.0.0``. -Unfortunately we have break the rules in case of found **security -vulnerability**. - +Unfortunately we may have to break these rules when a **security +vulnerability** is found. If a security problem cannot be fixed without breaking backward -compatibility -- a bugfix release may do it. The probability for this -is very low but shit happens, sorry. +compatibility, a bugfix release may break compatibility. This is unlikely, but +possible. -All *backward incompatible* changes are explicitly marked in -:ref:`CHANGES ` chapter. +All backward incompatible changes are explicitly marked in +:ref:`the changelog `. -How to enable gzip compression globally for the whole application? ------------------------------------------------------------------- +How do I enable gzip compression globally for my entire application? +-------------------------------------------------------------------- -It's impossible. Choosing what to compress and where don't apply such -time consuming operation is very tricky matter. +It's impossible. Choosing what to compress and what not to compress is +is a tricky matter. -If you need global compression -- write own custom middleware. Or +If you need global compression, write a custom middleware. Or enable compression in NGINX (you are deploying aiohttp behind reverse -proxy, is not it). +proxy, right?). -How to manage ClientSession inside web server? ----------------------------------------------- +How do I manage a ClientSession within a web server? +---------------------------------------------------- :class:`aiohttp.ClientSession` should be created once for the lifetime of the server in order to benefit from connection pooling. -Session saves cookies internally. If you don't need cookies processing +Sessions save cookies internally. If you don't need cookie processing, use :class:`aiohttp.DummyCookieJar`. If you need separate cookies -for different http calls but process them in logical chains use single +for different http calls but process them in logical chains, use a single :class:`aiohttp.TCPConnector` with separate -client session and ``own_connector=False``. +client sessions and ``own_connector=False``. -How to access db connection stored in app from subapplication? --------------------------------------------------------------- +How do I access database connections from a subapplication? +----------------------------------------------------------- -Restricting access from subapplication to main (or outer) app is the +Restricting access from subapplication to main (or outer) app is a deliberate choice. -Subapplication is an isolated unit by design. If you need to share -database object please do it explicitly:: +A subapplication is an isolated unit by design. If you need to share a +database object, do it explicitly:: subapp['db'] = mainapp['db'] mainapp.add_subapp('/prefix', subapp) + + +How do I perform operations in a request handler after sending the response? +---------------------------------------------------------------------------- + +Middlewares can be written to handle post-response operations, but +they run after every request. You can explicitly send the response by +calling :meth:`aiohttp.web.Response.write_eof`, which starts sending +before the handler returns, giving you a chance to execute follow-up +operations:: + + def ping_handler(request): + """Send PONG and increase DB counter.""" + + # explicitly send the response + resp = web.json_response({'message': 'PONG'}) + await resp.prepare(request) + await resp.write_eof() + + # increase the pong count + APP['db'].inc_pong() + + return resp + +A :class:`aiohttp.web.Response` object must be returned. This is +required by aiohttp web contracts, even though the response +already been sent. + + +How do I make sure my custom middleware response will behave correctly? +------------------------------------------------------------------------ + +Sometimes your middleware handlers might need to send a custom response. +This is just fine as long as you always create a new +:class:`aiohttp.web.Response` object when required. + +The response object is a Finite State Machine. Once it has been dispatched +by the server, it will reach its final state and cannot be used again. + +The following middleware will make the server hang, once it serves the second +response:: + + from aiohttp import web + + def misbehaved_middleware(): + # don't do this! + cached = web.Response(status=200, text='Hi, I am cached!') + + @web.middleware + async def middleware(request, handler): + # ignoring response for the sake of this example + _res = handler(request) + return cached + + return middleware + +The rule of thumb is *one request, one response*. + + +Why is creating a ClientSession outside of an event loop dangerous? +------------------------------------------------------------------- + +Short answer is: life-cycle of all asyncio objects should be shorter +than life-cycle of event loop. + +Full explanation is longer. All asyncio object should be correctly +finished/disconnected/closed before event loop shutdown. Otherwise +user can get unexpected behavior. In the best case it is a warning +about unclosed resource, in the worst case the program just hangs, +awaiting for coroutine is never resumed etc. + +Consider the following code from ``mod.py``:: + + import aiohttp + + session = aiohttp.ClientSession() + + async def fetch(url): + async with session.get(url) as resp: + return await resp.text() + +The session grabs current event loop instance and stores it in a +private variable. + +The main module imports the module and installs ``uvloop`` (an +alternative fast event loop implementation). + +``main.py``:: + + import asyncio + import uvloop + import mod + + asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) + asyncio.run(main()) + +The code is broken: ``session`` is bound to default ``asyncio`` loop +on import time but the loop is changed **after the import** by +``set_event_loop()``. As result ``fetch()`` call hangs. + + +To avoid import dependency hell *aiohttp* encourages creation of +``ClientSession`` from async function. The same policy works for +``web.Application`` too. + +Another use case is unit test writing. Very many test libraries +(*aiohttp test tools* first) creates a new loop instance for every +test function execution. It's done for sake of tests isolation. +Otherwise pending activity (timers, network packets etc.) from +previous test may interfere with current one producing very cryptic +and unstable test failure. + +Note: *class variables* are hidden globals actually. The following +code has the same problem as ``mod.py`` example, ``session`` variable +is the hidden global object:: + + class A: + session = aiohttp.ClientSession() + + async def fetch(self, url): + async with session.get(url) as resp: + return await resp.text() diff -Nru python-aiohttp-3.1.3/docs/index.rst python-aiohttp-3.5.1/docs/index.rst --- python-aiohttp-3.1.3/docs/index.rst 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/index.rst 2018-12-24 20:58:54.000000000 +0000 @@ -55,12 +55,10 @@ import aiohttp import asyncio - import async_timeout async def fetch(session, url): - async with async_timeout.timeout(10): - async with session.get(url) as response: - return await response.text() + async with session.get(url) as response: + return await response.text() async def main(): async with aiohttp.ClientSession() as session: @@ -100,7 +98,7 @@ Tutorial ======== -:ref:`Polls tutorial ` +:ref:`Polls tutorial ` Source code @@ -112,7 +110,7 @@ `_ if you have found a bug or have some suggestion in order to improve the library. -The library uses `Travis `_ for +The library uses `Travis `_ for Continuous Integration. @@ -198,6 +196,7 @@ .. toctree:: :name: mastertoc + :maxdepth: 2 client web diff -Nru python-aiohttp-3.1.3/docs/logging.rst python-aiohttp-3.5.1/docs/logging.rst --- python-aiohttp-3.1.3/docs/logging.rst 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/logging.rst 2018-12-24 20:58:54.000000000 +0000 @@ -28,22 +28,24 @@ Access logs ----------- -Access log by default is switched on and uses ``'aiohttp.access'`` -logger name. +Access logs are enabled by default. If the `debug` flag is set, and the default +logger ``'aiohttp.access'`` is used, access logs will be output to +:obj:`~sys.stderr` if no handlers are attached. +Furthermore, if the default logger has no log level set, the log level will be +set to :obj:`logging.DEBUG`. -The log may be controlled by :meth:`aiohttp.web.Application.make_handler` call. +This logging may be controlled by :meth:`aiohttp.web.AppRunner` and +:func:`aiohttp.web.run_app`. -Pass *access_log* parameter with value of :class:`logging.Logger` -instance to override default logger. +To override the default logger, pass an instance of :class:`logging.Logger` to +override the default logger. .. note:: - Use ``web.run_app(app, access_log=None)`` for disabling access logs. + Use ``web.run_app(app, access_log=None)`` to disable access logs. -Other parameter called *access_log_format* may be used for specifying log -format (see below). - +In addition, *access_log_format* may be used to specify the log format. .. _aiohttp-logging-access-log-format-spec: @@ -69,7 +71,7 @@ +--------------+---------------------------------------------------------+ | ``%s`` | Response status code | +--------------+---------------------------------------------------------+ -| ``%b`` | Size of response in bytes, excluding HTTP headers | +| ``%b`` | Size of response in bytes, including HTTP headers | +--------------+---------------------------------------------------------+ | ``%T`` | The time taken to serve the request, in seconds | +--------------+---------------------------------------------------------+ @@ -83,7 +85,7 @@ | ``%{FOO}o`` | ``response.headers['FOO']`` | +--------------+---------------------------------------------------------+ -Default access log format is:: +The default access log format is:: '%a %t "%r" %s %b "%{Referer}i" "%{User-Agent}i"' @@ -91,7 +93,7 @@ *access_log_class* introduced. -Example of drop-in replacement for :class:`aiohttp.helpers.AccessLogger`:: +Example of a drop-in replacement for :class:`aiohttp.helpers.AccessLogger`:: from aiohttp.abc import AbstractAccessLogger @@ -102,28 +104,42 @@ f'"{request.method} {request.path} ' f'done in {time}s: {response.status}') -.. note:: - When `Gunicorn `_ is used for - :ref:`deployment ` its default access log format - will be automatically replaced with the default aiohttp's access log format. +.. _gunicorn-accesslog: + +Gunicorn access logs +^^^^^^^^^^^^^^^^^^^^ +When `Gunicorn `_ is used for +:ref:`deployment `, its default access log format +will be automatically replaced with the default aiohttp's access log format. + +If Gunicorn's option access_logformat_ is +specified explicitly, it should use aiohttp's format specification. + +Gunicorn's access log works only if accesslog_ is specified explicitly in your +config or as a command line option. +This configuration can be either a path or ``'-'``. If the application uses +a custom logging setup intercepting the ``'gunicorn.access'`` logger, +accesslog_ should be set to ``'-'`` to prevent Gunicorn to create an empty +access log file upon every startup. + - If Gunicorn's option access_logformat_ is - specified explicitly it should use aiohttp's format specification. Error logs ---------- -*aiohttp.web* uses logger named ``'aiohttp.server'`` to store errors +:mod:`aiohttp.web` uses a logger named ``'aiohttp.server'`` to store errors given on web requests handling. -The log is enabled by default. +This log is enabled by default. -To use different logger name please specify *logger* parameter -(:class:`logging.Logger` instance) on performing -:meth:`aiohttp.web.Application.make_handler` call. +To use a different logger name, pass *logger* (:class:`logging.Logger` +instance) to the :meth:`aiohttp.web.AppRunner` constructor. .. _access_logformat: http://docs.gunicorn.org/en/stable/settings.html#access-log-format + +.. _accesslog: + http://docs.gunicorn.org/en/stable/settings.html#accesslog diff -Nru python-aiohttp-3.1.3/docs/misc.rst python-aiohttp-3.5.1/docs/misc.rst --- python-aiohttp-3.1.3/docs/misc.rst 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/misc.rst 2018-12-24 20:58:54.000000000 +0000 @@ -12,12 +12,10 @@ glossary .. toctree:: - :hidden: + :titlesonly: changes -* :ref:`aiohttp_changes` - Indices and tables ------------------ diff -Nru python-aiohttp-3.1.3/docs/multipart_reference.rst python-aiohttp-3.5.1/docs/multipart_reference.rst --- python-aiohttp-3.1.3/docs/multipart_reference.rst 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/multipart_reference.rst 2018-12-24 20:58:54.000000000 +0000 @@ -157,7 +157,7 @@ Returns the next body part reader. -.. class:: MultipartWriter(subtype='mixed', boundary=None) +.. class:: MultipartWriter(subtype='mixed', boundary=None, close_boundary=True) Multipart body writer. @@ -191,6 +191,14 @@ Size of the payload. - .. comethod:: write(writer) + .. comethod:: write(writer, close_boundary=True) Write body. + + :param bool close_boundary: The (:class:`bool`) that will emit + boundary closing. You may want to disable + when streaming (``multipart/x-mixed-replace``) + + .. versionadded:: 3.4 + + Support ``close_boundary`` argument. diff -Nru python-aiohttp-3.1.3/docs/multipart.rst python-aiohttp-3.5.1/docs/multipart.rst --- python-aiohttp-3.1.3/docs/multipart.rst 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/multipart.rst 2018-12-24 20:58:54.000000000 +0000 @@ -179,14 +179,35 @@ await session.post('http://example.com', data=mpwriter) -Behind the scenes :meth:`MultipartWriter.serialize` will yield chunks of every +Behind the scenes :meth:`MultipartWriter.write` will yield chunks of every part and if body part has `Content-Encoding` or `Content-Transfer-Encoding` they will be applied on streaming content. -Please note, that on :meth:`MultipartWriter.serialize` all the file objects +Please note, that on :meth:`MultipartWriter.write` all the file objects will be read until the end and there is no way to repeat a request without rewinding their pointers to the start. +Example MJPEG Streaming ``multipart/x-mixed-replace``. By default +:meth:`MultipartWriter.write` appends closing ``--boundary--`` and breaks your +content. Providing `close_boundary = False` prevents this.:: + + my_boundary = 'some-boundary' + response = web.StreamResponse( + status=200, + reason='OK', + headers={ + 'Content-Type': 'multipart/x-mixed-replace;boundary=--%s' % my_boundary + } + ) + while True: + frame = get_jpeg_frame() + with MultipartWriter('image/jpeg', boundary=my_boundary) as mpwriter: + mpwriter.append(frame, { + 'Content-Type': 'image/jpeg' + }) + await mpwriter.write(response, close_boundary=False) + await response.drain() + Hacking Multipart ----------------- @@ -206,9 +227,17 @@ to serialize a :class:`MultipartWriter` by our own in the way to calculate its size:: - body = b''.join(mpwriter.serialize()) + class Writer: + def __init__(self): + self.buffer = bytearray() + + async def write(self, data): + self.buffer.extend(data) + + writer = Writer() + mpwriter.writer(writer) await aiohttp.post('http://example.com', - data=body, headers=mpwriter.headers) + data=writer.buffer, headers=mpwriter.headers) Sometimes the server response may not be well formed: it may or may not contains nested parts. For instance, we request a resource which returns Binary files /tmp/tmpYRAZo5/bce_IiBcz8/python-aiohttp-3.1.3/docs/old-logo.png and /tmp/tmpYRAZo5/6pNZuTByL6/python-aiohttp-3.5.1/docs/old-logo.png differ diff -Nru python-aiohttp-3.1.3/docs/powered_by.rst python-aiohttp-3.5.1/docs/powered_by.rst --- python-aiohttp-3.1.3/docs/powered_by.rst 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/powered_by.rst 2018-12-24 20:58:54.000000000 +0000 @@ -30,6 +30,9 @@ bikes location. * `Wargaming: World of Tanks `_ * `Yandex `_ -* `Rambler `_ +* `Rambler `_ * `Escargot `_ - Chat server * `Prom.ua `_ - Online trading platform +* `globo.com `_ - (some parts) Brazilian largest media portal +* `Glose `_ - Social reader for E-Books +* `Emoji Generator `_ - Text icon generator diff -Nru python-aiohttp-3.1.3/docs/signals.rst python-aiohttp-3.5.1/docs/signals.rst --- python-aiohttp-3.1.3/docs/signals.rst 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/signals.rst 2018-12-24 20:58:54.000000000 +0000 @@ -5,7 +5,7 @@ Signal is a list of registered asynchronous callbacks. -The signal's life-cycle has two stages: after creation it's content +The signal's life-cycle has two stages: after creation its content could be filled by using standard list operations: ``sig.append()`` etc. diff -Nru python-aiohttp-3.1.3/docs/spelling_wordlist.txt python-aiohttp-3.5.1/docs/spelling_wordlist.txt --- python-aiohttp-3.1.3/docs/spelling_wordlist.txt 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/spelling_wordlist.txt 2018-12-24 20:58:54.000000000 +0000 @@ -9,6 +9,7 @@ api api’s app +apps app’s arg Arsenic @@ -23,11 +24,14 @@ backend backends Backport +Backporting +backport backports BaseEventLoop basename BasicAuth BodyPartReader +boolean botocore Bugfixes builtin @@ -64,6 +68,7 @@ Ctrl Cython cythonized +Cythonize de deduplicate # de-facto: @@ -253,6 +258,7 @@ Systemd tarball TCP +TLS teardown Teardown TestClient @@ -261,16 +267,19 @@ timestamps toolbar toplevel +towncrier tp tuples UI un unawaited +unclosed unicode unittest Unittest unix unsets +unstripped upstr url urldispatcher @@ -296,3 +305,4 @@ wss www xxx +yarl Binary files /tmp/tmpYRAZo5/bce_IiBcz8/python-aiohttp-3.1.3/docs/_static/aiohttp-icon-128x128.png and /tmp/tmpYRAZo5/6pNZuTByL6/python-aiohttp-3.5.1/docs/_static/aiohttp-icon-128x128.png differ diff -Nru python-aiohttp-3.1.3/docs/structures.rst python-aiohttp-3.5.1/docs/structures.rst --- python-aiohttp-3.1.3/docs/structures.rst 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/docs/structures.rst 2018-12-24 20:58:54.000000000 +0000 @@ -0,0 +1,55 @@ +.. _aiohttp-structures: + + +Common data structures +====================== + +.. module:: aiohttp + +.. currentmodule:: aiohttp + + +Common data structures used by *aiohttp* internally. + + +FrozenList +---------- + +A list-like structure which implements +:class:`collections.abc.MutableSequence`. + +The list is *mutable* unless :meth:`FrozenList.freeze` is called, +after that the list modification raises :exc:`RuntimeError`. + + +.. class:: FrozenList(items) + + Construct a new *non-frozen* list from *items* iterable. + + The list implements all :class:`collections.abc.MutableSequence` + methods plus two additional APIs. + + .. attribute:: frozen + + A read-only property, ``True`` is the list is *frozen* + (modifications are forbidden). + + .. method:: freeze() + + Freeze the list. There is no way to *thaw* it back. + + +ChainMapProxy +------------- + +An *immutable* version of :class:`collections.ChainMap`. Internally +the proxy is a list of mappings (dictionaries), if the requested key +is not present in the first mapping the second is looked up and so on. + +The class supports :class:`collections.abc.Mapping` interface. + +.. class:: ChainMapProxy(maps) + + Create a new chained mapping proxy from a list of mappings (*maps*). + + .. versionadded:: 3.2 diff -Nru python-aiohttp-3.1.3/docs/testing.rst python-aiohttp-3.5.1/docs/testing.rst --- python-aiohttp-3.1.3/docs/testing.rst 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/testing.rst 2018-12-24 20:58:54.000000000 +0000 @@ -43,7 +43,7 @@ But for :mod:`aiohttp.test_tools` the deprecation period could be reduced. Moreover we may break *backward compatibility* without *deprecation -peroid* for some very strong reason. +period* for some very strong reason. The Test Client and Servers @@ -153,6 +153,7 @@ :meth:`aiohttp.web.Application.make_handler` .. versionchanged:: 3.0 + .. deprecated:: 3.2 The fixture was renamed from ``test_server`` to ``aiohttp_server``. @@ -296,6 +297,8 @@ The event loop in which the application and server are running. + .. deprecated:: 3.5 + .. attribute:: app The application returned by :meth:`get_app` @@ -478,14 +481,14 @@ High level test creation:: - from aiohttp.test_utils import TestClient, loop_context + from aiohttp.test_utils import TestClient, TestServer, loop_context from aiohttp import request # loop_context is provided as a utility. You can use any - # asyncio.BaseEventLoop class in it's place. + # asyncio.BaseEventLoop class in its place. with loop_context() as loop: app = _create_example_app() - with TestClient(app, loop=loop) as client: + with TestClient(TestServer(app), loop=loop) as client: async def test_get_route(): nonlocal client @@ -500,11 +503,11 @@ If it's preferred to handle the creation / teardown on a more granular basis, the TestClient object can be used directly:: - from aiohttp.test_utils import TestClient + from aiohttp.test_utils import TestClient, TestServer with loop_context() as loop: app = _create_example_app() - client = TestClient(app, loop=loop) + client = TestClient(TestSever(app), loop=loop) loop.run_until_complete(client.start_server()) root = "http://127.0.0.1:{}".format(port) @@ -650,10 +653,9 @@ :param app_or_server: :class:`BaseTestServer` instance for making client requests to it. - If the parameter is - :class:`aiohttp.web.Application` the tool - creates :class:`TestServer` implicitly for - serving the application. + In order to pass a :class:`aiohttp.web.Application` + you need to convert it first to :class:`TestServer` + first with ``TestServer(app)``. :param cookie_jar: an optional :class:`aiohttp.CookieJar` instance, may be useful with ``CookieJar(unsafe=True)`` @@ -684,6 +686,12 @@ :class:`BaseTestServer` test server instance used in conjunction with client. + .. attribute:: app + + An alias for :attr:`self.server.app`. return ``None`` if + ``self.server`` is not :class:`TestServer` + instance(e.g. :class:`RawTestServer` instance for test low-level server). + .. attribute:: session An internal :class:`aiohttp.ClientSession`. @@ -709,7 +717,7 @@ Routes a request to tested http server. The interface is identical to - :meth:`asyncio.ClientSession.request`, except the loop kwarg is + :meth:`aiohttp.ClientSession.request`, except the loop kwarg is overridden by the instance used by the test server. .. comethod:: get(path, *args, **kwargs) diff -Nru python-aiohttp-3.1.3/docs/third_party.rst python-aiohttp-3.5.1/docs/third_party.rst --- python-aiohttp-3.1.3/docs/third_party.rst 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/third_party.rst 2018-12-24 20:58:54.000000000 +0000 @@ -206,8 +206,31 @@ - `aiohttp-sentry `_ An aiohttp middleware for reporting errors to Sentry. Python 3.5+ is required. +- `aiohttp-datadog `_ + An aiohttp middleware for reporting metrics to DataDog. Python 3.5+ is required. + - `async-v20 `_ Asynchronous FOREX client for OANDA's v20 API. Python 3.6+ - `aiohttp-jwt `_ An aiohttp middleware for JWT(JSON Web Token) support. Python 3.5+ is required. + +- `AWS Xray Python SDK `_ + Native tracing support for Aiohttp applications. + +- `GINO `_ + An asyncio ORM on top of SQLAlchemy core, delivered with an aiohttp extension. + +- `aiohttp-apispec `_ + Build and document REST APIs with ``aiohttp`` and ``apispec``. + +- `eider-py `_ Python implementation of + the `Eider RPC protocol `_. + +- `asynapplicationinsights `_ A client + for `Azure Application Insights `_ + implemented using ``aiohttp`` client, including a middleware for ``aiohttp`` servers to collect web apps + telemetry. + +- `aiogmaps `_ + Asynchronous client for Google Maps API Web Services. Python 3.6+ required. diff -Nru python-aiohttp-3.1.3/docs/tutorial.rst python-aiohttp-3.5.1/docs/tutorial.rst --- python-aiohttp-3.1.3/docs/tutorial.rst 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/tutorial.rst 1970-01-01 00:00:00.000000000 +0000 @@ -1,413 +0,0 @@ -.. _aiohttp-tutorial: - -Server Tutorial -=============== - -Are you going to learn *aiohttp* but don't know where to start? We have -example for you. Polls application is a great example for getting -started with aiohttp. - -If you want the full source code in advance or for comparison, check out -the `demo source`_. - -.. _demo source: - https://github.com/aio-libs/aiohttp/tree/master/demos/polls/ - - -.. _aiohttp-tutorial-setup: - -Setup your environment ----------------------- - -First of all check you python version: - -.. code-block:: shell - - $ python -V - Python 3.5.0 - -Tutorial requires Python 3.5.0 or newer. - -We’ll assume that you have already installed *aiohttp* library. You can check -aiohttp is installed and which version by running the following -command: - -.. code-block:: shell - - $ python3 -c 'import aiohttp; print(aiohttp.__version__)' - 3.0.5 - -Project structure looks very similar to other python based web projects: - -.. code-block:: none - - . - ├── README.rst - └── polls - ├── Makefile - ├── README.rst - ├── aiohttpdemo_polls - │ ├── __init__.py - │ ├── __main__.py - │ ├── db.py - │ ├── main.py - │ ├── routes.py - │ ├── templates - │ ├── utils.py - │ └── views.py - ├── config - │ └── polls.yaml - ├── images - │ └── example.png - ├── setup.py - ├── sql - │ ├── create_tables.sql - │ ├── install.sh - │ └── sample_data.sql - └── static - └── style.css - - -.. _aiohttp-tutorial-introduction: - -Getting started with aiohttp first app --------------------------------------- - -This tutorial based on Django polls tutorial. - - -Application ------------ - -All aiohttp server is built around :class:`aiohttp.web.Application` instance. -It is used for registering *startup*/*cleanup* signals, connecting routes etc. - -The following code creates an application:: - - from aiohttp import web - - - app = web.Application() - web.run_app(app, host='127.0.0.1', port=8080) - -Save it under ``aiohttpdemo_polls/main.py`` and start the server: - -.. code-block:: shell - - $ python3 main.py - -You'll see the following output on the command line: - -.. code-block:: shell - - ======== Running on http://127.0.0.1:8080 ======== - (Press CTRL+C to quit) - -Open ``http://127.0.0.1:8080`` in browser or do - -.. code-block:: shell - - $ curl -X GET localhost:8080 - -Alas, for now both return only ``404: Not Found``. -To show something more meaningful let's create a route and a view. - -.. _aiohttp-tutorial-views: - -Views ------ - -Let's start from first views. Create the file ``aiohttpdemo_polls/views.py`` with the following:: - - from aiohttp import web - - - async def index(request): - return web.Response(text='Hello Aiohttp!') - -This is the simplest view possible in Aiohttp. -Now we should create a route for this ``index`` view. Put this into ``aiohttpdemo_polls/routes.py`` (it is a good practice to separate views, routes, models etc. You'll have more of each, and it is nice to have them in different places):: - - from views import index - - - def setup_routes(app): - app.router.add_get('/', index) - - -Also, we should call ``setup_routes`` function somewhere, and the best place is in the ``main.py`` :: - - from aiohttp import web - from routes import setup_routes - - - app = web.Application() - setup_routes(app) - web.run_app(app, host='127.0.0.1', port=8080) - -Start server again. Now if we open browser we can see: - -.. code-block:: shell - - $ curl -X GET localhost:8080 - Hello Aiohttp! - -Success! For now your working directory should look like this: - -.. code-block:: none - - . - ├── .. - └── polls - ├── aiohttpdemo_polls - │ ├── main.py - │ ├── routes.py - │ └── views.py - -.. _aiohttp-tutorial-config: - -Configuration files -------------------- - -aiohttp is configuration agnostic. It means the library does not -require any configuration approach and does not have builtin support -for any config schema. - -But please take into account these facts: - - 1. 99% of servers have configuration files. - - 2. Every product (except Python-based solutions like Django and - Flask) does not store config files as part as source code. - - For example Nginx has own configuration files stored by default - under ``/etc/nginx`` folder. - - Mongo pushes config as ``/etc/mongodb.conf``. - - 3. Config files validation is good idea, strong checks may prevent - silly errors during product deployment. - -Thus we **suggest** to use the following approach: - - 1. Pushing configs as ``yaml`` files (``json`` or ``ini`` is also - good but ``yaml`` is the best). - - 2. Loading ``yaml`` config from a list of predefined locations, - e.g. ``./config/app_cfg.yaml``, ``/etc/app_cfg.yaml``. - - 3. Keeping ability to override config file by command line - parameter, e.g. ``./run_app --config=/opt/config/app_cfg.yaml``. - - 4. Applying strict validation checks to loaded dict. `trafaret - `_, `colander - `_ - or `JSON schema - `_ are good - candidates for such job. - - -Load config and push into application:: - - # load config from yaml file in current dir - conf = load_config(str(pathlib.Path('.') / 'config' / 'polls.yaml')) - app['config'] = conf - -.. _aiohttp-tutorial-database: - -Database --------- - -Setup -^^^^^ - -In this tutorial we will use the latest PostgreSQL database. You can install -PostgreSQL using this instruction http://www.postgresql.org/download/ - -Database schema -^^^^^^^^^^^^^^^ - -We use SQLAlchemy to describe database schemas. -For this tutorial we can use two simple models ``question`` and ``choice``:: - - import sqlalchemy as sa - - meta = sa.MetaData() - - question = sa.Table( - 'question', meta, - sa.Column('id', sa.Integer, nullable=False), - sa.Column('question_text', sa.String(200), nullable=False), - sa.Column('pub_date', sa.Date, nullable=False), - - # Indexes # - sa.PrimaryKeyConstraint('id', name='question_id_pkey')) - - choice = sa.Table( - 'choice', meta, - sa.Column('id', sa.Integer, nullable=False), - sa.Column('question_id', sa.Integer, nullable=False), - sa.Column('choice_text', sa.String(200), nullable=False), - sa.Column('votes', sa.Integer, server_default="0", nullable=False), - - # Indexes # - sa.PrimaryKeyConstraint('id', name='choice_id_pkey'), - sa.ForeignKeyConstraint(['question_id'], [question.c.id], - name='choice_question_id_fkey', - ondelete='CASCADE'), - ) - - - -You can find below description of tables in database: - -First table is question: - -+---------------+ -| question | -+===============+ -| id | -+---------------+ -| question_text | -+---------------+ -| pub_date | -+---------------+ - -and second table is choice table: - -+---------------+ -| choice | -+===============+ -| id | -+---------------+ -| choice_text | -+---------------+ -| votes | -+---------------+ -| question_id | -+---------------+ - -Creating connection engine -^^^^^^^^^^^^^^^^^^^^^^^^^^ - -For making DB queries we need an engine instance. Assuming ``conf`` is -a :class:`dict` with configuration info Postgres connection could be -done by the following coroutine: - -.. literalinclude:: ../demos/polls/aiohttpdemo_polls/db.py - :pyobject: init_pg - -The best place for connecting to DB is -:attr:`~aiohtp.web.Application.on_startup` signal:: - - app.on_startup.append(init_pg) - - -Graceful shutdown -^^^^^^^^^^^^^^^^^ - -There is a good practice to close all resources on program exit. - -Let's close DB connection in :attr:`~aiohtp.web.Application.on_cleanup` signal:: - - app.on_cleanup.append(close_pg) - - -.. literalinclude:: ../demos/polls/aiohttpdemo_polls/db.py - :pyobject: close_pg - - -.. _aiohttp-tutorial-templates: - -Templates ---------- - -Let's add more useful views: - -.. literalinclude:: ../demos/polls/aiohttpdemo_polls/views.py - :pyobject: poll - -Templates are very convenient way for web page writing. We return a -dict with page content, ``aiohttp_jinja2.template`` decorator -processes it by jinja2 template renderer. - -For setting up template engine we need to install ``aiohttp_jinja2`` -library first: - -.. code-block:: shell - - $ pip install aiohttp_jinja2 - -After installing we need to setup the library:: - - import aiohttp_jinja2 - import jinja2 - - aiohttp_jinja2.setup( - app, loader=jinja2.PackageLoader('aiohttpdemo_polls', 'templates')) - - -In the tutorial we push template files under -``polls/aiohttpdemo_polls/templates`` folder. - - -.. _aiohttp-tutorial-static: - -Static files ------------- - -Any web site has static files: images, JavaScript sources, CSS files etc. - -The best way to handle static in production is setting up reverse -proxy like NGINX or using CDN services. - -But for development handling static files by aiohttp server is very convenient. - -Fortunately it can be done easy by single call: - -.. literalinclude:: ../demos/polls/aiohttpdemo_polls/routes.py - :pyobject: setup_static_routes - -where ``project_root`` is the path to root folder. - - -.. _aiohttp-tutorial-middlewares: - -Middlewares ------------ - -Middlewares are stacked around every web-handler. They are called -*before* handler for pre-processing request and *after* getting -response back for post-processing given response. - -Here we'll add a simple middleware for displaying pretty looking pages -for *404 Not Found* and *500 Internal Error*. - -Middlewares could be registered in ``app`` by adding new middleware to -``app.middlewares`` list: - -.. literalinclude:: ../demos/polls/aiohttpdemo_polls/middlewares.py - :pyobject: setup_middlewares - -Middleware itself is a factory which accepts *application* and *next -handler* (the following middleware or *web-handler* in case of the -latest middleware in the list). - -The factory returns *middleware handler* which has the same signature -as regular *web-handler* -- it accepts *request* and returns -*response*. - -Middleware for processing HTTP exceptions: - -.. literalinclude:: ../demos/polls/aiohttpdemo_polls/middlewares.py - :pyobject: error_pages - -Registered overrides are trivial Jinja2 template renderers: - -.. literalinclude:: ../demos/polls/aiohttpdemo_polls/middlewares.py - :pyobject: handle_404 - -.. literalinclude:: ../demos/polls/aiohttpdemo_polls/middlewares.py - :pyobject: handle_500 - -.. seealso:: :ref:`aiohttp-web-middlewares` diff -Nru python-aiohttp-3.1.3/docs/utilities.rst python-aiohttp-3.5.1/docs/utilities.rst --- python-aiohttp-3.1.3/docs/utilities.rst 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/utilities.rst 2018-12-24 20:58:54.000000000 +0000 @@ -16,4 +16,5 @@ multipart_reference streams signals + structures websocket_utilities diff -Nru python-aiohttp-3.1.3/docs/web_advanced.rst python-aiohttp-3.5.1/docs/web_advanced.rst --- python-aiohttp-3.1.3/docs/web_advanced.rst 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/web_advanced.rst 2018-12-24 20:58:54.000000000 +0000 @@ -96,7 +96,7 @@ app.router.add_get('/', handler) All not finished jobs will be terminated on -:attr:`aiohttp.web.Application.on_cleanup` signal. +:attr:`Application.on_cleanup` signal. To prevent cancellation of the whole :term:`web-handler` use ``@atomic`` decorator:: @@ -254,7 +254,7 @@ wrap your handlers with the :func:`aiohttp_jinja2.template` decorator:: @aiohttp_jinja2.template('tmpl.jinja2') - def handler(request): + async def handler(request): return {'name': 'Andrew', 'surname': 'Svetlov'} If you prefer the `Mako`_ template engine, please take a look at the @@ -269,7 +269,7 @@ @routes.get('/path') @aiohttp_jinja2.template('tmpl.jinja2') - def handler(request): + async def handler(request): return {'name': 'Andrew', 'surname': 'Svetlov'} @@ -306,7 +306,7 @@ .. warning:: Parallel reads from websocket are forbidden, there is no - possibility to call :meth:`aiohttp.web.WebSocketResponse.receive` + possibility to call :meth:`WebSocketResponse.receive` from two tasks. See :ref:`FAQ section ` for @@ -321,12 +321,18 @@ :mod:`aiohttp.web` discourages the use of *global variables*, aka *singletons*. Every variable should have its own context that is *not global*. -So, :class:`aiohttp.web.Application` and :class:`aiohttp.web.Request` +So, :class:`Application` and :class:`Request` support a :class:`collections.abc.MutableMapping` interface (i.e. they are dict-like objects), allowing them to be used as data stores. + +.. _aiohttp-web-data-sharing-app-config: + +Application's config +^^^^^^^^^^^^^^^^^^^^ + For storing *global-like* variables, feel free to save them in an -:class:`~.Application` instance:: +:class:`Application` instance:: app['my_private_key'] = data @@ -335,8 +341,24 @@ async def handler(request): data = request.app['my_private_key'] -Variables that are only needed for the lifetime of a :class:`~.Request`, can be -stored in a :class:`~.Request`:: +In case of :ref:`nested applications +` the desired lookup strategy could +be the following: + +1. Search the key in the current nested application. +2. If the key is not found continue searching in the parent application(s). + +For this please use :attr:`Request.config_dict` read-only property:: + + async def handler(request): + data = request.config_dict['my_private_key'] + + +Request's storage +^^^^^^^^^^^^^^^^^ + +Variables that are only needed for the lifetime of a :class:`Request`, can be +stored in a :class:`Request`:: async def handler(request): request['my_private_key'] = "data" @@ -346,7 +368,10 @@ :ref:`aiohttp-web-signals` handlers to store data for further processing by the next handlers in the chain. -:class:`aiohttp.web.StreamResponse` and :class:`aiohttp.web.Response` objects +Response's storage +^^^^^^^^^^^^^^^^^^ + +:class:`StreamResponse` and :class:`Response` objects also support :class:`collections.abc.MutableMapping` interface. This is useful when you want to share data with signals and middlewares once all the work in the handler is done:: @@ -357,6 +382,9 @@ return response +Naming hint +^^^^^^^^^^^ + To avoid clashing with other *aiohttp* users and third-party libraries, please choose a unique key name for storing data. @@ -365,6 +393,82 @@ Otherwise, something based on your company name/url would be satisfactory (i.e. ``org.company.app``). + +.. _aiohttp-web-contextvars: + + +ContextVars support +------------------- + +Starting from Python 3.7 asyncio has :mod:`Context Variables ` as a +context-local storage (a generalization of thread-local concept that works with asyncio +tasks also). + + +*aiohttp* server supports it in the following way: + +* A server inherits the current task's context used when creating it. + :func:`aiohttp.web.run_app()` runs a task for handling all underlying jobs running + the app, but alternatively :ref:`aiohttp-web-app-runners` can be used. + +* Application initialization / finalization events (:attr:`Application.cleanup_ctx`, + :attr:`Application.on_startup` and :attr:`Application.on_shutdown`, + :attr:`Application.on_cleanup`) are executed inside the same context. + + E.g. all context modifications made on application startup a visible on teardown. + +* On every request handling *aiohttp* creates a context copy. :term:`web-handler` has + all variables installed on initialization stage. But the context modification made by + a handler or middleware is invisible to another HTTP request handling call. + +An example of context vars usage:: + + from contextvars import ContextVar + + from aiohttp import web + + VAR = ContextVar('VAR', default='default') + + + async def coro(): + return VAR.get() + + + async def handler(request): + var = VAR.get() + VAR.set('handler') + ret = await coro() + return web.Response(text='\n'.join([var, + ret])) + + + async def on_startup(app): + print('on_startup', VAR.get()) + VAR.set('on_startup') + + + async def on_cleanup(app): + print('on_cleanup', VAR.get()) + VAR.set('on_cleanup') + + + async def init(): + print('init', VAR.get()) + VAR.set('init') + app = web.Application() + app.router.add_get('/', handler) + + app.on_startup.append(on_startup) + app.on_cleanup.append(on_cleanup) + return app + + + web.run_app(init()) + print('done', VAR.get()) + +.. versionadded:: 3.5 + + .. _aiohttp-web-middlewares: Middlewares @@ -392,8 +496,8 @@ Every *middleware* should accept two parameters, a :class:`request ` instance and a *handler*, and return the response or raise an exception. If the exception is not an instance of -:exc:`aiohttp.web.HTTPException` it is converted to ``500`` -:exc:`aiohttp.web.HTTPInternalServerError` after processing the +:exc:`HTTPException` it is converted to ``500`` +:exc:`HTTPInternalServerError` after processing the middlewares chain. .. warning:: @@ -423,7 +527,7 @@ from aiohttp import web - def test(request): + async def test(request): print('Handler function called') return web.Response(text="Hello") @@ -479,42 +583,22 @@ app = web.Application(middlewares=[error_middleware]) -Old Style Middleware -^^^^^^^^^^^^^^^^^^^^ - -.. deprecated:: 2.3 - - Prior to *v2.3* middleware required an outer *middleware factory* - which returned the middleware coroutine. Since *v2.3* this is not - required; instead the ``@middleware`` decorator should - be used. - -Old style middleware (with an outer factory and no ``@middleware`` -decorator) is still supported. Furthermore, old and new style middleware -can be mixed. +Middleware Factory +^^^^^^^^^^^^^^^^^^ -A *middleware factory* is simply a coroutine that implements the logic of a -*middleware*. For example, here's a trivial *middleware factory*:: +A *middleware factory* is a function that creates a middleware with passed arguments. For example, here's a trivial *middleware factory*:: - async def middleware_factory(app, handler): - async def middleware_handler(request): + def middleware_factory(text): + @middleware + async def sample_middleware(request, handler): resp = await handler(request) - resp.text = resp.text + ' wink' + resp.text = resp.text + text return resp - return middleware_handler + return sample_middleware -A *middleware factory* should accept two parameters, an -:class:`app ` instance and a *handler*, and return a new handler. +Remember that contrary to regular middlewares you need the result of a middleware factory not the function itself. So when passing a middleware factory to an app you actually need to call it:: -.. note:: - - Both the outer *middleware_factory* coroutine and the inner - *middleware_handler* coroutine are called for every request handled. - -*Middleware factories* should return a new handler that has the same signature -as a :ref:`request handler `. That is, it should accept a -single :class:`Request` instance and return a :class:`Response`, or raise an -exception. + app = web.Application(middlewares=[middleware_factory(' wink')]) .. _aiohttp-web-signals: @@ -527,10 +611,10 @@ being prepared. For this :mod:`aiohttp.web` provides *signals*. For example, a middleware can only change HTTP headers for *unprepared* -responses (see :meth:`~aiohttp.web.StreamResponse.prepare`), but sometimes we +responses (see :meth:`StreamResponse.prepare`), but sometimes we need a hook for changing HTTP headers for streamed responses and WebSockets. This can be accomplished by subscribing to the -:attr:`~aiohttp.web.Application.on_response_prepare` signal:: +:attr:`Application.on_response_prepare` signal:: async def on_prepare(request, response): response.headers['My-Header'] = 'value' @@ -538,8 +622,8 @@ app.on_response_prepare.append(on_prepare) -Additionally, the :attr:`~aiohttp.web.Application.on_startup` and -:attr:`~aiohttp.web.Application.on_cleanup` signals can be subscribed to for +Additionally, the :attr:`Application.on_startup` and +:attr:`Application.on_cleanup` signals can be subscribed to for application component setup and tear down accordingly. The following example will properly initialize and dispose an aiopg connection @@ -567,17 +651,8 @@ Signal handlers should not return a value but may modify incoming mutable parameters. -Signal handlers will be run sequentially, in order they were added. If handler -is asynchronous, it will be awaited before calling next one. - -.. warning:: - - Signals API has provisional status, meaning it may be changed in future - releases. - - Signal subscription and sending will most likely be the same, but signal - object creation is subject to change. As long as you are not creating new - signals, but simply reusing existing ones, you will not be affected. +Signal handlers will be run sequentially, in order they were +added. All handlers must be asynchronous since *aiohttp* 3.0. .. _aiohttp-web-cleanup-ctx: @@ -641,7 +716,7 @@ Thus we'll create a totally separate application named ``admin`` and connect it to main app with prefix by -:meth:`~aiohttp.web.Application.add_subapp`:: +:meth:`Application.add_subapp`:: admin = web.Application() # setup admin routes, signals and middlewares @@ -655,13 +730,13 @@ the call chain. The same is going for -:attr:`~aiohttp.web.Application.on_response_prepare` signal -- the +:attr:`Application.on_response_prepare` signal -- the signal is delivered to both top level ``app`` and ``admin`` if processing URL is routed to ``admin`` sub-application. -Common signals like :attr:`~aiohttp.web.Application.on_startup`, -:attr:`~aiohttp.web.Application.on_shutdown` and -:attr:`~aiohttp.web.Application.on_cleanup` are delivered to all +Common signals like :attr:`Application.on_startup`, +:attr:`Application.on_shutdown` and +:attr:`Application.on_cleanup` are delivered to all registered sub-applications. The passed parameter is sub-application instance, not top-level application. @@ -764,7 +839,7 @@ :func:`run_app` provides a simple *blocking* API for running an :class:`Application`. -For starting the application *asynchronously* on serving on multiple +For starting the application *asynchronously* or serving on multiple HOST/PORT :class:`AppRunner` exists. The simple startup code for serving HTTP site on ``'localhost'``, port @@ -803,26 +878,31 @@ The following :term:`websocket` snippet shows an example for websocket handler:: + from aiohttp import web + import weakref + app = web.Application() - app['websockets'] = [] + app['websockets'] = weakref.WeakSet() async def websocket_handler(request): ws = web.WebSocketResponse() await ws.prepare(request) - request.app['websockets'].append(ws) + request.app['websockets'].add(ws) try: async for msg in ws: ... finally: - request.app['websockets'].remove(ws) + request.app['websockets'].discard(ws) return ws Signal handler may look like:: + from aiohttp import WSCloseCode + async def on_shutdown(app): - for ws in app['websockets']: + for ws in set(app['websockets']): await ws.close(code=WSCloseCode.GOING_AWAY, message='Server shutdown') @@ -898,8 +978,8 @@ -------------------- Pages like *404 Not Found* and *500 Internal Error* could be handled -by custom middleware, see :ref:`aiohttp-tutorial-middlewares` for -details. +by custom middleware, see :ref:`polls demo ` +for example. .. _aiohttp-web-forwarded-support: @@ -910,8 +990,8 @@ deploying *aiohttp* web server behind a *Reverse Proxy Server* like :term:`nginx` for production usage. -In this way properties like :attr:`~BaseRequest.scheme` -:attr:`~BaseRequest.host` and :attr:`~BaseRequest.remote` are +In this way properties like :attr:`BaseRequest.scheme` +:attr:`BaseRequest.host` and :attr:`BaseRequest.remote` are incorrect. Real values should be given from proxy server, usually either @@ -925,9 +1005,9 @@ That's why *aiohttp server* should setup *forwarded* headers in custom middleware in tight conjunction with *reverse proxy configuration*. -For changing :attr:`~BaseRequest.scheme` :attr:`~BaseRequest.host` and -:attr:`~BaseRequest.remote` the middleware might use -:meth:`~BaseRequest.clone`. +For changing :attr:`BaseRequest.scheme` :attr:`BaseRequest.host` and +:attr:`BaseRequest.remote` the middleware might use +:meth:`BaseRequest.clone`. .. seealso:: @@ -965,13 +1045,12 @@ $ pip install aiohttp_debugtoolbar -After that attach the :mod:`aiohttp_debugtoolbar` middleware to your -:class:`aiohttp.web.Application` and call :func:`aiohttp_debugtoolbar.setup`:: +Just call :func:`aiohttp_debugtoolbar.setup`:: import aiohttp_debugtoolbar from aiohttp_debugtoolbar import toolbar_middleware_factory - app = web.Application(middlewares=[toolbar_middleware_factory]) + app = web.Application() aiohttp_debugtoolbar.setup(app) The toolbar is ready to use. Enjoy!!! diff -Nru python-aiohttp-3.1.3/docs/web_lowlevel.rst python-aiohttp-3.5.1/docs/web_lowlevel.rst --- python-aiohttp-3.1.3/docs/web_lowlevel.rst 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/web_lowlevel.rst 2018-12-24 20:58:54.000000000 +0000 @@ -55,9 +55,13 @@ return web.Response(text="OK") - async def main(loop): + async def main(): server = web.Server(handler) - await loop.create_server(server, "127.0.0.1", 8080) + runner = web.ServerRunner(server) + await runner.setup() + site = web.TCPSite(runner, 'localhost', 8080) + await site.start() + print("======= Serving on http://127.0.0.1:8080/ ======") # pause here for very long time by serving HTTP requests and @@ -68,7 +72,7 @@ loop = asyncio.get_event_loop() try: - loop.run_until_complete(main(loop)) + loop.run_until_complete(main()) except KeyboardInterrupt: pass loop.close() @@ -79,10 +83,11 @@ This *handler* is processed by ``server`` (:class:`Server` which acts as *protocol factory*). Network communication is created by -``loop.create_server`` call to serve ``http://127.0.0.1:8080/``. +:ref:`runners API ` to serve +``http://127.0.0.1:8080/``. -The handler should process every request: ``GET``, ``POST``, -Web-Socket for every *path*. +The handler should process every request for every *path*, e.g. +``GET``, ``POST``, Web-Socket. The example is very basic: it always return ``200 OK`` response, real -life code should be much more complex. +life code is much more complex usually. diff -Nru python-aiohttp-3.1.3/docs/web_quickstart.rst python-aiohttp-3.5.1/docs/web_quickstart.rst --- python-aiohttp-3.1.3/docs/web_quickstart.rst 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/web_quickstart.rst 2018-12-24 20:58:54.000000000 +0000 @@ -12,7 +12,7 @@ In order to implement a web server, first create a :ref:`request handler `. -A request handler is a :ref:`coroutine ` or regular function that +A request handler must be a :ref:`coroutine ` that accepts a :class:`Request` instance as its only parameter and returns a :class:`Response` instance:: @@ -129,7 +129,7 @@ :meth:`RouteTableDef.route`, allowing a handler to serve incoming requests on a *path* having **any** *HTTP method*:: - app.add_routes[web.route('*', '/path', all_handler)] + app.add_routes([web.route('*', '/path', all_handler)]) The *HTTP method* can be queried later in the request handler using the :attr:`Request.method` property. @@ -259,7 +259,7 @@ def __init__(self): pass - def handle_intro(self, request): + async def handle_intro(self, request): return web.Response(text="Hello, world") async def handle_greeting(self, request): @@ -408,7 +408,7 @@ It is a common case to return JSON data in response, :mod:`aiohttp.web` provides a shortcut for returning JSON -- :func:`aiohttp.web.json_response`:: - def handler(request): + async def handler(request): data = {'some': 'data'} return web.json_response(data) @@ -611,6 +611,45 @@ app.add_routes([web.get('/ws', websocket_handler)]) +.. _aiohttp-web-redirects: + +Redirects +--------- + +To redirect user to another endpoint - raise :class:`HTTPFound` with +an absolute URL, relative URL or view name (the argument from router):: + + raise web.HTTPFound('/redirect') + +The following example shows redirect to view named 'login' in routes:: + + async def handler(request): + location = request.app.router['login'].url_for() + raise web.HTTPFound(location=location) + + router.add_get('/handler', handler) + router.add_get('/login', login_handler, name='login') + +Example with login validation:: + + @aiohttp_jinja2.template('login.html') + async def login(request): + + if request.method == 'POST': + form = await request.post() + error = validate_login(form) + if error: + return {'error': error} + else: + # login form is valid + location = request.app.router['index'].url_for() + raise web.HTTPFound(location=location) + + return {} + + app.router.add_get('/', index, name='index') + app.router.add_get('/login', login, name='login') + app.router.add_post('/login', login, name='login') .. _aiohttp-web-exceptions: diff -Nru python-aiohttp-3.1.3/docs/web_reference.rst python-aiohttp-3.5.1/docs/web_reference.rst --- python-aiohttp-3.1.3/docs/web_reference.rst 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/web_reference.rst 2018-12-24 20:58:54.000000000 +0000 @@ -71,8 +71,6 @@ The value could be overridden by :meth:`~BaseRequest.clone`. - ``'http'`` otherwise. - Read-only :class:`str` property. .. versionchanged:: 2.3 @@ -227,7 +225,7 @@ Read-only :class:`asyncio.AbstractEventLoop` property. - .. versionadded:: 2.3 + .. deprecated:: 3.5 .. attribute:: cookies @@ -268,7 +266,7 @@ Use :meth:`can_read_body` instead. - .. attribute:: content_type + .. attribute:: content_type Read-only property with *content* part of *Content-Type* header. @@ -411,7 +409,7 @@ :meth:`~Request.json` call will return the same value. - .. comethod:: multipart(*, reader=aiohttp.multipart.MultipartReader) + .. comethod:: multipart() Returns :class:`aiohttp.multipart.MultipartReader` which processes incoming *multipart* request. @@ -432,6 +430,10 @@ .. seealso:: :ref:`aiohttp-multipart` + .. versionchanged:: 3.4 + + Dropped *reader* parameter. + .. comethod:: post() A :ref:`coroutine ` that reads POST parameters from @@ -465,7 +467,7 @@ .. class:: Request - An request used for receiving request's information by *web handler*. + A request used for receiving request's information by *web handler*. Every :ref:`handler` accepts a request instance as the first positional parameter. @@ -489,6 +491,16 @@ An :class:`Application` instance used to call :ref:`request handler `, Read-only property. + .. attribute:: config_dict + + A :class:`aiohttp.ChainMapProxy` instance for mapping all properties + from the current application returned by :attr:`app` property + and all its parents. + + .. seealso:: :ref:`aiohttp-web-data-sharing-app-config` + + .. versionadded:: 3.2 + .. note:: You should never create the :class:`Request` instance manually @@ -498,6 +510,7 @@ + .. _aiohttp-web-response: @@ -524,7 +537,7 @@ :ref:`web-handler` is returning a :class:`Response` instance:: - def handler(request): + async def handler(request): return Response(text="All right!") Response classes are :obj:`dict` like objects, @@ -792,7 +805,8 @@ ^^^^^^^^ .. class:: Response(*, body=None, status=200, reason=None, text=None, \ - headers=None, content_type=None, charset=None) + headers=None, content_type=None, charset=None, zlib_executor_size=sentinel, + zlib_executor=None) The most usable response class, inherited from :class:`StreamResponse`. @@ -817,6 +831,15 @@ :param str charset: response's charset. ``'utf-8'`` if *text* is passed also, ``None`` otherwise. + :param int zlib_executor_size: length in bytes which will trigger zlib compression + of body to happen in an executor + + .. versionadded:: 3.5 + + :param int zlib_executor: executor to use for zlib compression + + .. versionadded:: 3.5 + .. attribute:: body @@ -826,6 +849,11 @@ Setting :attr:`body` also recalculates :attr:`~StreamResponse.content_length` value. + Assigning :class:`str` to :attr:`body` will make the :attr:`body` + type of :class:`aiohttp.payload.StringPayload`, which tries to encode + the given data based on *Content-Type* HTTP header, while defaulting + to ``UTF-8``. + Resetting :attr:`body` (assigning ``None``) sets :attr:`~StreamResponse.content_length` to ``None`` too, dropping *Content-Length* HTTP header. @@ -849,7 +877,7 @@ .. class:: WebSocketResponse(*, timeout=10.0, receive_timeout=None, \ autoclose=True, autoping=True, heartbeat=None, \ - protocols=(), compress=True) + protocols=(), compress=True, max_msg_size=4194304) Class for handling server-side websockets, inherited from :class:`StreamResponse`. @@ -887,6 +915,12 @@ :param bool compress: Enable per-message deflate extension support. False for disabled, default value is True. + :param int max_msg_size: maximum size of read websocket message, 4 + MB by default. To disable the size limit use ``0``. + + .. versionadded:: 3.3 + + The class supports ``async for`` statement for iterating over incoming messages:: @@ -941,7 +975,7 @@ Read-only property, close code from peer. It is set to ``None`` on opened connection. - .. attribute:: protocol + .. attribute:: ws_protocol Websocket *subprotocol* chosen after :meth:`start` call. @@ -1197,10 +1231,8 @@ Application is a synonym for web-server. To get fully working example, you have to make *application*, register -supported urls in *router* and create a *server socket* with -:class:`~aiohttp.web.Server` as a *protocol -factory*. *Server* could be constructed with -:meth:`Application.make_handler`. +supported urls in *router* and pass it to :func:`aiohttp.web.run_app` +or :class:`aiohttp.web.AppRunner`. *Application* contains a *router* instance and a list of callbacks that will be called during application finishing. @@ -1234,6 +1266,11 @@ creates :class:`UrlDispatcher` by default if *router* is ``None``. + .. deprecated:: 3.3 + + The custom routers support is deprecated, the parameter will + be removed in 4.0. + :param middlewares: :class:`list` of middleware factories, see :ref:`aiohttp-web-middlewares` for details. @@ -1254,6 +1291,10 @@ :param debug: Switches debug mode. + .. deprecated:: 3.5 + + Use asyncio :ref:`asyncio-debug-mode` instead. + .. attribute:: router Read-only property that returns *router instance*. @@ -1266,11 +1307,16 @@ :ref:`event loop` used for processing HTTP requests. + .. deprecated:: 3.5 .. attribute:: debug Boolean value indicating whether the debug mode is turned on or off. + .. deprecated:: 3.5 + + Use asyncio :ref:`asyncio-debug-mode` instead. + .. attribute:: on_response_prepare A :class:`~aiohttp.Signal` that is fired at the beginning @@ -1360,6 +1406,21 @@ :returns: a :class:`PrefixedSubAppResource` instance. + .. method:: add_domain(domain, subapp) + + Register nested sub-application that serves + the domain name or domain name mask. + + In resolving process if request.headers['host'] + matches the pattern *domain* then + further resolving is passed to *subapp*. + + :param str domain: domain or mask of domain for the resource. + + :param Application subapp: nested application. + + :returns: a :class:`MatchedSubAppResource` instance. + .. method:: add_routes(routes_table) Register route definitions from *routes_table*. @@ -1375,54 +1436,56 @@ .. method:: make_handler(loop=None, **kwargs) - Creates HTTP protocol factory for handling requests. + Creates HTTP protocol factory for handling requests. - :param loop: :ref:`event loop` used - for processing HTTP requests. + :param loop: :ref:`event loop` used + for processing HTTP requests. - If param is ``None`` :func:`asyncio.get_event_loop` - used for getting default event loop. + If param is ``None`` :func:`asyncio.get_event_loop` + used for getting default event loop. - .. deprecated:: 2.0 - - :param bool tcp_keepalive: Enable TCP Keep-Alive. Default: ``True``. - :param int keepalive_timeout: Number of seconds before closing Keep-Alive - connection. Default: ``75`` seconds (NGINX's default value). - :param logger: Custom logger object. Default: - :data:`aiohttp.log.server_logger`. - :param access_log: Custom logging object. Default: - :data:`aiohttp.log.access_logger`. - :param access_log_class: class for `access_logger`. Default: - :data:`aiohttp.helpers.AccessLogger`. - Must to be a subclass of :class:`aiohttp.abc.AbstractAccessLogger`. - :param str access_log_format: Access log format string. Default: - :attr:`helpers.AccessLogger.LOG_FORMAT`. - :param int max_line_size: Optional maximum header line size. Default: - ``8190``. - :param int max_headers: Optional maximum header size. Default: ``32768``. - :param int max_field_size: Optional maximum header field size. Default: - ``8190``. - - :param float lingering_time: maximum time during which the server - reads and ignore additional data coming from the client when - lingering close is on. Use ``0`` for disabling lingering on - server channel closing. - - :param float lingering_timeout: maximum waiting time for more - client data to arrive when lingering close is in effect - - You should pass result of the method as *protocol_factory* to - :meth:`~asyncio.AbstractEventLoop.create_server`, e.g.:: - - loop = asyncio.get_event_loop() + .. deprecated:: 2.0 + + :param bool tcp_keepalive: Enable TCP Keep-Alive. Default: ``True``. + :param int keepalive_timeout: Number of seconds before closing Keep-Alive + connection. Default: ``75`` seconds (NGINX's default value). + :param logger: Custom logger object. Default: + :data:`aiohttp.log.server_logger`. + :param access_log: Custom logging object. Default: + :data:`aiohttp.log.access_logger`. + :param access_log_class: Class for `access_logger`. Default: + :data:`aiohttp.helpers.AccessLogger`. + Must to be a subclass of :class:`aiohttp.abc.AbstractAccessLogger`. + :param str access_log_format: Access log format string. Default: + :attr:`helpers.AccessLogger.LOG_FORMAT`. + :param int max_line_size: Optional maximum header line size. Default: + ``8190``. + :param int max_headers: Optional maximum header size. Default: ``32768``. + :param int max_field_size: Optional maximum header field size. Default: + ``8190``. + + :param float lingering_time: Maximum time during which the server + reads and ignores additional data coming from the client when + lingering close is on. Use ``0`` to disable lingering on + server channel closing. + + You should pass result of the method as *protocol_factory* to + :meth:`~asyncio.AbstractEventLoop.create_server`, e.g.:: + + loop = asyncio.get_event_loop() + + app = Application() + + # setup route table + # app.router.add_route(...) - app = Application() + await loop.create_server(app.make_handler(), + '0.0.0.0', 8080) - # setup route table - # app.router.add_route(...) + .. deprecated:: 3.2 - await loop.create_server(app.make_handler(), - '0.0.0.0', 8080) + The method is deprecated and will be removed in future + aiohttp versions. Please use :ref:`aiohttp-web-app-runners` instead. .. comethod:: startup() @@ -1471,12 +1534,12 @@ A protocol factory compatible with :meth:`~asyncio.AbstreactEventLoop.create_server`. - .. class:: Server +.. class:: Server The class is responsible for creating HTTP protocol objects that can handle HTTP connections. - .. attribute:: Server.connections + .. attribute:: connections List of all currently opened connections. @@ -1812,6 +1875,13 @@ Read-only *name* of resource or ``None``. + .. attribute:: canonical + + Read-only *canonical path* associate with the resource. For example + ``/path/to`` or ``/path/{to}`` + + .. versionadded:: 3.3 + .. comethod:: resolve(request) Resolve resource by finding appropriate :term:`web-handler` for @@ -1875,6 +1945,12 @@ The class corresponds to resources with plain-text matching, ``'/path/to'`` for example. + .. attribute:: canonical + + Read-only *canonical path* associate with the resource. Returns the path + used to create the PlainResource. For example ``/path/to`` + + .. versionadded:: 3.3 .. method:: url_for() @@ -1889,6 +1965,13 @@ :ref:`variable ` matching, e.g. ``'/path/{to}/{param}'`` etc. + .. attribute:: canonical + + Read-only *canonical path* associate with the resource. Returns the + formatter obtained from the path used to create the DynamicResource. + For example, from a path ``/get/{num:^\d+}``, it returns ``/get/{num}`` + + .. versionadded:: 3.3 .. method:: url_for(**params) @@ -1907,6 +1990,13 @@ The class corresponds to resources for :ref:`static file serving `. + .. attribute:: canonical + + Read-only *canonical path* associate with the resource. Returns the prefix + used to create the StaticResource. For example ``/prefix`` + + .. versionadded:: 3.3 + .. method:: url_for(filename, append_version=None) Returns a :class:`~yarl.URL` for file path under resource prefix. @@ -1922,7 +2012,7 @@ (hash) to the url query string for cache boosting - By default has value from an constructor (``False`` by default) + By default has value from a constructor (``False`` by default) When set to ``True`` - ``v=FILE_HASH`` query string param will be added When set to ``False`` has no impact @@ -1934,6 +2024,14 @@ A resource for serving nested applications. The class instance is returned by :class:`~aiohttp.web.Application.add_subapp` call. + .. attribute:: canonical + + Read-only *canonical path* associate with the resource. Returns the + prefix used to create the PrefixedSubAppResource. + For example ``/prefix`` + + .. versionadded:: 3.3 + .. method:: url_for(**kwargs) The call is not allowed, it raises :exc:`RuntimeError`. @@ -2381,14 +2479,50 @@ .. versionadded:: 3.0 - :class:`AppRunner` and :class:`TCPSite` / :class:`UnixSite` / - :class:`SockSite` are added in aiohttp 3.0 + :class:`AppRunner` / :class:`ServerRunner` and :class:`TCPSite` / + :class:`UnixSite` / :class:`SockSite` are added in aiohttp 3.0 + + +.. class:: BaseRunner + + A base class for runners. Use :class:`AppRunner` for serving + :class:`Application`, :class:`ServerRunner` for low-level + :class:`Server`. + + .. attribute:: server + + Low-level web :class:`Server` for handling HTTP requests, + read-only attribute. + + .. attribute:: addresses + + A :class:`list` of served sockets addresses. + + See :meth:`socket.getsockname` for items type. + + .. versionadded:: 3.3 + + .. attribute:: sites + + A read-only :class:`set` of served sites (:class:`TCPSite` / + :class:`UnixSite` / :class:`SockSite` instances). + + .. comethod:: setup() + + Initialize the server. Should be called before adding sites. + + .. comethod:: cleanup() + + Stop handling all registered sites and cleanup used resources. + .. class:: AppRunner(app, *, handle_signals=False, **kwargs) A runner for :class:`Application`. Used with conjunction with sites to serve on specific port. + Inherited from :class:`BaseRunner`. + :param Application app: web application instance to serve. :param bool handle_signals: add signal handlers for @@ -2397,23 +2531,13 @@ default). :param kwargs: named parameters to pass into - :meth:`Application.make_handler`. + web protocol. .. attribute:: app Read-only attribute for accessing to :class:`Application` served instance. - .. attribute:: server - - Low-level web :class:`Server` for handling HTTP requests, - read-only attribute. - - .. attribute:: sites - - A read-only :class:`set` of served sites (:class:`TCPSite` / - :class:`UnixSite` / :class:`SockSite` instances). - .. comethod:: setup() Initialize application. Should be called before adding sites. @@ -2427,6 +2551,28 @@ :attr:`Application.on_shutdown` and :attr:`Application.on_cleanup` signals are called internally. + +.. class:: ServerRunner(web_server, *, handle_signals=False, **kwargs) + + A runner for low-level :class:`Server`. Used with conjunction with sites + to serve on specific port. + + Inherited from :class:`BaseRunner`. + + :param Server web_server: low-level web server instance to serve. + + :param bool handle_signals: add signal handlers for + :data:`signal.SIGINT` and + :data:`signal.SIGTERM` (``False`` by + default). + + :param kwargs: named parameters to pass into + web protocol. + + .. seealso:: + + :ref:`aiohttp-web-lowlevel` demonstrates low-level server usage + .. class:: BaseSite An abstract class for handled sites. @@ -2434,7 +2580,7 @@ .. attribute:: name An identifier for site, read-only :class:`str` property. Could - be an handled URL or UNIX socket path. + be a handled URL or UNIX socket path. .. comethod:: start() @@ -2447,7 +2593,7 @@ .. class:: TCPSite(runner, host=None, port=None, *, \ shutdown_timeout=60.0, ssl_context=None, \ - backlog=128, reuse_address=None, + backlog=128, reuse_address=None, \ reuse_port=None) Serve a runner on TCP socket. @@ -2688,27 +2834,41 @@ ^^^^^^^^^^^^^^^^^^^^^^^^^ .. function:: normalize_path_middleware(*, \ - append_slash=True, merge_slashes=True) + append_slash=True, \ + remove_slash=False, \ + merge_slashes=True, \ + redirect_class=HTTPMovedPermanently) + + Middleware factory which produces a middleware that normalizes + the path of a request. By normalizing it 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_slash* or *remove_slash* + 3. both *merge_slashes* and *append_slash* or *remove_slash* - Middleware that normalizes the path of a request. By normalizing - it means: + If the path resolves with at least one of those conditions, it will + redirect to the new path. - - Add a trailing slash to the path. - - Double slashes are replaced by one. + Only one of *append_slash* and *remove_slash* can be enabled. If both are + ``True`` the factory will raise an ``AssertionError`` - The middleware returns as soon as it finds a path that resolves - correctly. The order if all enabled is: + 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. - 1. *merge_slashes* - 2. *append_slash* - 3. both *merge_slashes* and *append_slash* + 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 the path resolves with at least one of those conditions, it will - redirect to the new path. + If *merge_slashes* is ``True``, merge multiple consecutive slashes in the + path into one. - If *append_slash* is ``True`` append slash when needed. If a resource is - defined with trailing slash and the request comes without it, it will - append it automatically. + .. versionadded:: 3.4 - If *merge_slashes* is ``True``, merge multiple consecutive slashes in the - path into one. + Support for *remove_slash* diff -Nru python-aiohttp-3.1.3/docs/web.rst python-aiohttp-3.5.1/docs/web.rst --- python-aiohttp-3.1.3/docs/web.rst 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/docs/web.rst 2018-12-24 20:58:54.000000000 +0000 @@ -11,7 +11,7 @@ .. toctree:: :name: server - Tutorial + Tutorial Quickstart Advanced Usage Low Level diff -Nru python-aiohttp-3.1.3/.editorconfig python-aiohttp-3.5.1/.editorconfig --- python-aiohttp-3.1.3/.editorconfig 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/.editorconfig 2018-12-24 20:58:53.000000000 +0000 @@ -0,0 +1,19 @@ +# EditorConfig is awesome: http://EditorConfig.org + +# top-most EditorConfig file +root = true + +# Unix-style newlines with a newline ending every file +[*] +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true +charset = utf-8 + +[Makefile] +indent_style = tab + +[*.{yml,yaml}] +indent_size = 2 diff -Nru python-aiohttp-3.1.3/examples/server_simple.py python-aiohttp-3.5.1/examples/server_simple.py --- python-aiohttp-3.1.3/examples/server_simple.py 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/examples/server_simple.py 2018-12-24 20:58:54.000000000 +0000 @@ -0,0 +1,31 @@ +# 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)]) + +web.run_app(app) diff -Nru python-aiohttp-3.1.3/examples/web_ws.py python-aiohttp-3.5.1/examples/web_ws.py --- python-aiohttp-3.1.3/examples/web_ws.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/examples/web_ws.py 2018-12-24 20:58:54.000000000 +0000 @@ -19,6 +19,8 @@ await resp.prepare(request) + await resp.send_str('Welcome!!!') + try: print('Someone joined.') for ws in request.app['sockets']: diff -Nru python-aiohttp-3.1.3/.github/CODEOWNERS python-aiohttp-3.5.1/.github/CODEOWNERS --- python-aiohttp-3.1.3/.github/CODEOWNERS 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/.github/CODEOWNERS 2018-12-24 20:58:53.000000000 +0000 @@ -0,0 +1,22 @@ +* @asvetlov +/.github/* @webknjaz @asvetlov +/.circleci/* @webknjaz @asvetlov +/CHANGES/* @asvetlov +/docs/* @asvetlov +/examples/* @asvetlov +/requirements/* @webknjaz @asvetlov +/tests/* @asvetlov +/tools/* @webknjaz @asvetlov +/vendor/* @webknjaz @asvetlov +*.ini @webknjaz @asvetlov +*.md @webknjaz @asvetlov +*.rst @webknjaz @asvetlov +*.toml @webknjaz @asvetlov +*.txt @webknjaz @asvetlov +*.yml @webknjaz @asvetlov +*.yaml @webknjaz @asvetlov +.editorconfig @webknjaz @asvetlov +.git* @webknjaz +Makefile @webknjaz @asvetlov +setup.py @webknjaz @asvetlov +setup.cfg @webknjaz @asvetlov diff -Nru python-aiohttp-3.1.3/.gitignore python-aiohttp-3.5.1/.gitignore --- python-aiohttp-3.1.3/.gitignore 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/.gitignore 2018-12-24 20:58:53.000000000 +0000 @@ -23,10 +23,15 @@ .vimrc aiohttp/_frozenlist.c aiohttp/_frozenlist.html +aiohttp/_helpers.c +aiohttp/_helpers.html aiohttp/_websocket.c aiohttp/_websocket.html aiohttp/_http_parser.c aiohttp/_http_parser.html +aiohttp/_http_writer.c +aiohttp/_http_writer.html +aiohttp/_headers.html bin build htmlcov @@ -51,3 +56,4 @@ .python-version .pytest_cache .vscode +.mypy_cache \ No newline at end of file diff -Nru python-aiohttp-3.1.3/.gitmodules python-aiohttp-3.5.1/.gitmodules --- python-aiohttp-3.1.3/.gitmodules 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/.gitmodules 2018-12-24 20:58:53.000000000 +0000 @@ -0,0 +1,4 @@ +[submodule "vendor/http-parser"] + path = vendor/http-parser + url = git://github.com/nodejs/http-parser.git + branch = 54f55a2 diff -Nru python-aiohttp-3.1.3/HISTORY.rst python-aiohttp-3.5.1/HISTORY.rst --- python-aiohttp-3.1.3/HISTORY.rst 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/HISTORY.rst 2018-12-24 20:58:54.000000000 +0000 @@ -1,3 +1,323 @@ +3.4.4 (2018-09-05) +================== + +- Fix installation from sources when compiling toolkit is not available (`#3241 `_) + +3.4.3 (2018-09-04) +================== + +- Add ``app.pre_frozen`` state to properly handle startup signals in sub-applications. (`#3237 `_) + + +3.4.2 (2018-09-01) +================== + +- Fix ``iter_chunks`` type annotation (`#3230 `_) + +3.4.1 (2018-08-28) +================== + +- Fix empty header parsing regression. (`#3218 `_) +- Fix BaseRequest.raw_headers doc. (`#3215 `_) +- Fix documentation building on ReadTheDocs (`#3221 `_) + + +3.4.0 (2018-08-25) +================== + +Features +-------- + +- Add type hints (`#3049 `_) +- Add ``raise_for_status`` request parameter (`#3073 `_) +- Add type hints to HTTP client (`#3092 `_) +- Minor server optimizations (`#3095 `_) +- Preserve the cause when `HTTPException` is raised from another exception. (`#3096 `_) +- Add `close_boundary` option in `MultipartWriter.write` method. Support streaming (`#3104 `_) +- Added a ``remove_slash`` option to the ``normalize_path_middleware`` factory. (`#3173 `_) +- The class `AbstractRouteDef` is importable from `aiohttp.web`. (`#3183 `_) + + +Bugfixes +-------- + +- Prevent double closing when client connection is released before the + last ``data_received()`` callback. (`#3031 `_) +- Make redirect with `normalize_path_middleware` work when using url encoded paths. (`#3051 `_) +- Postpone web task creation to connection establishment. (`#3052 `_) +- Fix ``sock_read`` timeout. (`#3053 `_) +- When using a server-request body as the `data=` argument of a client request, iterate over the content with `readany` instead of `readline` to avoid `Line too long` errors. (`#3054 `_) +- fix `UrlDispatcher` has no attribute `add_options`, add `web.options` (`#3062 `_) +- correct filename in content-disposition with multipart body (`#3064 `_) +- Many HTTP proxies has buggy keepalive support. + Let's not reuse connection but close it after processing every response. (`#3070 `_) +- raise 413 "Payload Too Large" rather than raising ValueError in request.post() + Add helpful debug message to 413 responses (`#3087 `_) +- Fix `StreamResponse` equality, now that they are `MutableMapping` objects. (`#3100 `_) +- Fix server request objects comparison (`#3116 `_) +- Do not hang on `206 Partial Content` response with `Content-Encoding: gzip` (`#3123 `_) +- Fix timeout precondition checkers (`#3145 `_) + + +Improved Documentation +---------------------- + +- Add a new FAQ entry that clarifies that you should not reuse response + objects in middleware functions. (`#3020 `_) +- Add FAQ section "Why is creating a ClientSession outside of an event loop dangerous?" (`#3072 `_) +- Fix link to Rambler (`#3115 `_) +- Fix TCPSite documentation on the Server Reference page. (`#3146 `_) +- Fix documentation build configuration file for Windows. (`#3147 `_) +- Remove no longer existing lingering_timeout parameter of Application.make_handler from documentation. (`#3151 `_) +- Mention that ``app.make_handler`` is deprecated, recommend to use runners + API instead. (`#3157 `_) + + +Deprecations and Removals +------------------------- + +- Drop ``loop.current_task()`` from ``helpers.current_task()`` (`#2826 `_) +- Drop ``reader`` parameter from ``request.multipart()``. (`#3090 `_) + + +3.3.2 (2018-06-12) +================== + +- Many HTTP proxies has buggy keepalive support. Let's not reuse connection but + close it after processing every response. (`#3070 `_) + +- Provide vendor source files in tarball (`#3076 `_) + + +3.3.1 (2018-06-05) +================== + +- Fix ``sock_read`` timeout. (`#3053 `_) +- When using a server-request body as the ``data=`` argument of a client request, + iterate over the content with ``readany`` instead of ``readline`` to avoid ``Line + too long`` errors. (`#3054 `_) + + +3.3.0 (2018-06-01) +================== + +Features +-------- + +- Raise ``ConnectionResetError`` instead of ``CancelledError`` on trying to + write to a closed stream. (`#2499 `_) +- Implement ``ClientTimeout`` class and support socket read timeout. (`#2768 `_) +- Enable logging when ``aiohttp.web`` is used as a program (`#2956 `_) +- Add canonical property to resources (`#2968 `_) +- Forbid reading response BODY after release (`#2983 `_) +- Implement base protocol class to avoid a dependency from internal + ``asyncio.streams.FlowControlMixin`` (`#2986 `_) +- Cythonize ``@helpers.reify``, 5% boost on macro benchmark (`#2995 `_) +- Optimize HTTP parser (`#3015 `_) +- Implement ``runner.addresses`` property. (`#3036 `_) +- Use ``bytearray`` instead of a list of ``bytes`` in websocket reader. It + improves websocket message reading a little. (`#3039 `_) +- Remove heartbeat on closing connection on keepalive timeout. The used hack + violates HTTP protocol. (`#3041 `_) +- Limit websocket message size on reading to 4 MB by default. (`#3045 `_) + + +Bugfixes +-------- + +- Don't reuse a connection with the same URL but different proxy/TLS settings + (`#2981 `_) +- When parsing the Forwarded header, the optional port number is now preserved. + (`#3009 `_) + + +Improved Documentation +---------------------- + +- Make Change Log more visible in docs (`#3029 `_) +- Make style and grammar improvements on the FAQ page. (`#3030 `_) +- Document that signal handlers should be async functions since aiohttp 3.0 + (`#3032 `_) + + +Deprecations and Removals +------------------------- + +- Deprecate custom application's router. (`#3021 `_) + + +Misc +---- + +- #3008, #3011 + + +3.2.1 (2018-05-10) +================== + +- Don't reuse a connection with the same URL but different proxy/TLS settings + (`#2981 `_) + + +3.2.0 (2018-05-06) +================== + +Features +-------- + +- Raise ``TooManyRedirects`` exception when client gets redirected too many + times instead of returning last response. (`#2631 `_) +- Extract route definitions into separate ``web_routedef.py`` file (`#2876 `_) +- Raise an exception on request body reading after sending response. (`#2895 `_) +- ClientResponse and RequestInfo now have real_url property, which is request + url without fragment part being stripped (`#2925 `_) +- Speed up connector limiting (`#2937 `_) +- Added and links property for ClientResponse object (`#2948 `_) +- Add ``request.config_dict`` for exposing nested applications data. (`#2949 `_) +- Speed up HTTP headers serialization, server micro-benchmark runs 5% faster + now. (`#2957 `_) +- Apply assertions in debug mode only (`#2966 `_) + + +Bugfixes +-------- + +- expose property `app` for TestClient (`#2891 `_) +- Call on_chunk_sent when write_eof takes as a param the last chunk (`#2909 `_) +- A closing bracket was added to `__repr__` of resources (`#2935 `_) +- Fix compression of FileResponse (`#2942 `_) +- Fixes some bugs in the limit connection feature (`#2964 `_) + + +Improved Documentation +---------------------- + +- Drop ``async_timeout`` usage from documentation for client API in favor of + ``timeout`` parameter. (`#2865 `_) +- Improve Gunicorn logging documentation (`#2921 `_) +- Replace multipart writer `.serialize()` method with `.write()` in + documentation. (`#2965 `_) + + +Deprecations and Removals +------------------------- + +- Deprecate Application.make_handler() (`#2938 `_) + + +Misc +---- + +- #2958 + + +3.1.3 (2018-04-12) +================== + +- Fix cancellation broadcast during DNS resolve (`#2910 `_) + + +3.1.2 (2018-04-05) +================== + +- Make ``LineTooLong`` exception more detailed about actual data size (`#2863 `_) +- Call ``on_chunk_sent`` when write_eof takes as a param the last chunk (`#2909 `_) + + +3.1.1 (2018-03-27) +================== + +- Support *asynchronous iterators* (and *asynchronous generators* as + well) in both client and server API as request / response BODY + payloads. (`#2802 `_) + + +3.1.0 (2018-03-21) +================== + +Welcome to aiohttp 3.1 release. + +This is an *incremental* release, fully backward compatible with *aiohttp 3.0*. + +But we have added several new features. + +The most visible one is ``app.add_routes()`` (an alias for existing +``app.router.add_routes()``. The addition is very important because +all *aiohttp* docs now uses ``app.add_routes()`` call in code +snippets. All your existing code still do register routes / resource +without any warning but you've got the idea for a favorite way: noisy +``app.router.add_get()`` is replaced by ``app.add_routes()``. + +The library does not make a preference between decorators:: + + routes = web.RouteTableDef() + + @routes.get('/') + async def hello(request): + return web.Response(text="Hello, world") + + app.add_routes(routes) + +and route tables as a list:: + + async def hello(request): + return web.Response(text="Hello, world") + + app.add_routes([web.get('/', hello)]) + +Both ways are equal, user may decide basing on own code taste. + +Also we have a lot of minor features, bug fixes and documentation +updates, see below. + +Features +-------- + +- Relax JSON content-type checking in the ``ClientResponse.json()`` to allow + "application/xxx+json" instead of strict "application/json". (`#2206 `_) +- Bump C HTTP parser to version 2.8 (`#2730 `_) +- Accept a coroutine as an application factory in ``web.run_app`` and gunicorn + worker. (`#2739 `_) +- Implement application cleanup context (``app.cleanup_ctx`` property). (`#2747 `_) +- Make ``writer.write_headers`` a coroutine. (`#2762 `_) +- Add tracking signals for getting request/response bodies. (`#2767 `_) +- Deprecate ClientResponseError.code in favor of .status to keep similarity + with response classes. (`#2781 `_) +- Implement ``app.add_routes()`` method. (`#2787 `_) +- Implement ``web.static()`` and ``RouteTableDef.static()`` API. (`#2795 `_) +- Install a test event loop as default by ``asyncio.set_event_loop()``. The + change affects aiohttp test utils but backward compatibility is not broken + for 99.99% of use cases. (`#2804 `_) +- Refactor ``ClientResponse`` constructor: make logically required constructor + arguments mandatory, drop ``_post_init()`` method. (`#2820 `_) +- Use ``app.add_routes()`` in server docs everywhere (`#2830 `_) +- Websockets refactoring, all websocket writer methods are converted into + coroutines. (`#2836 `_) +- Provide ``Content-Range`` header for ``Range`` requests (`#2844 `_) + + +Bugfixes +-------- + +- Fix websocket client return EofStream. (`#2784 `_) +- Fix websocket demo. (`#2789 `_) +- Property ``BaseRequest.http_range`` now returns a python-like slice when + requesting the tail of the range. It's now indicated by a negative value in + ``range.start`` rather then in ``range.stop`` (`#2805 `_) +- Close a connection if an unexpected exception occurs while sending a request + (`#2827 `_) +- Fix firing DNS tracing events. (`#2841 `_) + + +Improved Documentation +---------------------- + +- Document behavior when cchardet detects encodings that are unknown to Python. + (`#2732 `_) +- Add diagrams for tracing request life style. (`#2748 `_) +- Drop removed functionality for passing ``StreamReader`` as data at client + side. (`#2793 `_) + 3.0.9 (2018-03-14) ================== @@ -14,8 +334,8 @@ ================== - Fix SSL proxy support by client. (`#2810 `_) -- Restore a imperative check in ``setup.py`` for python version. The check - works in parallel to environment marker. As effect a error about unsupported +- Restore an imperative check in ``setup.py`` for python version. The check + works in parallel to environment marker. As effect an error about unsupported Python versions is raised even on outdated systems with very old ``setuptools`` version installed. (`#2813 `_) diff -Nru python-aiohttp-3.1.3/Makefile python-aiohttp-3.5.1/Makefile --- python-aiohttp-3.1.3/Makefile 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/Makefile 2018-12-24 20:58:54.000000000 +0000 @@ -3,63 +3,62 @@ all: test .install-deps: $(shell find requirements -type f) - @pip install -U -r requirements/dev.txt + pip install -r requirements/cython.txt + pip install -r requirements/dev.txt @touch .install-deps isort: isort -rc aiohttp isort -rc tests isort -rc examples - isort -rc demos flake: .flake .flake: .install-deps $(shell find aiohttp -type f) \ $(shell find tests -type f) \ - $(shell find examples -type f) \ - $(shell find demos -type f) - @flake8 aiohttp examples tests demos + $(shell find examples -type f) + flake8 aiohttp examples tests python setup.py check -rms @if ! isort -c -rc aiohttp tests examples; then \ echo "Import sort errors, run 'make isort' to fix them!!!"; \ isort --diff -rc aiohttp tests examples; \ false; \ fi + @if ! LC_ALL=C sort -c CONTRIBUTORS.txt; then \ + echo "CONTRIBUTORS.txt sort error"; \ + fi @touch .flake check_changes: - @./tools/check_changes.py + ./tools/check_changes.py + +mypy: .flake + if python -c "import sys; sys.exit(sys.implementation.name!='cpython')"; then \ + mypy aiohttp; \ + fi -.develop: .install-deps $(shell find aiohttp -type f) .flake check_changes - @pip install -e . +.develop: .install-deps $(shell find aiohttp -type f) .flake check_changes mypy + # pip install -e . @touch .develop test: .develop - @pytest -q ./tests + @pytest -c pytest.ci.ini -q vtest: .develop - @pytest -s -v ./tests + @pytest -c pytest.ci.ini -s -v cov cover coverage: tox cov-dev: .develop - @echo "Run without extensions" - @AIOHTTP_NO_EXTENSIONS=1 pytest --cov=aiohttp tests - @pytest --cov=aiohttp --cov-report=term --cov-report=html --cov-append tests + @pytest -c pytest.ci.ini --cov-report=html @echo "open file://`pwd`/htmlcov/index.html" -cov-ci-no-ext: .develop - @echo "Run without extensions" - @AIOHTTP_NO_EXTENSIONS=1 pytest --cov=aiohttp tests -cov-ci-aio-debug: .develop - @echo "Run in debug mode" - @PYTHONASYNCIODEBUG=1 pytest --cov=aiohttp --cov-append tests cov-ci-run: .develop @echo "Regular run" - @pytest --cov=aiohttp --cov-report=term --cov-report=html --cov-append tests + @pytest -c pytest.ci.ini --cov-report=html -cov-dev-full: cov-ci-no-ext cov-ci-aio-debug cov-ci-run +cov-dev-full: cov-ci-run @echo "open file://`pwd`/htmlcov/index.html" clean: diff -Nru python-aiohttp-3.1.3/MANIFEST.in python-aiohttp-3.5.1/MANIFEST.in --- python-aiohttp-3.1.3/MANIFEST.in 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/MANIFEST.in 2018-12-24 20:58:54.000000000 +0000 @@ -7,10 +7,14 @@ graft docs graft examples graft tests +recursive-include vendor * +global-include aiohttp *.pyi global-exclude *.pyc global-exclude *.pyd global-exclude *.so -exclude aiohttp/_frozenlist.html -exclude aiohttp/_http_parser.html -exclude aiohttp/_websocket.html +global-exclude *.lib +global-exclude *.dll +global-exclude *.a +global-exclude *.obj +exclude aiohttp/*.html prune docs/_build diff -Nru python-aiohttp-3.1.3/PKG-INFO python-aiohttp-3.5.1/PKG-INFO --- python-aiohttp-3.1.3/PKG-INFO 2018-04-13 10:03:23.000000000 +0000 +++ python-aiohttp-3.5.1/PKG-INFO 2018-12-24 20:59:58.000000000 +0000 @@ -1,13 +1,22 @@ -Metadata-Version: 1.2 +Metadata-Version: 2.1 Name: aiohttp -Version: 3.1.3 +Version: 3.5.1 Summary: Async http client/server framework (asyncio) -Home-page: https://github.com/aio-libs/aiohttp/ +Home-page: https://github.com/aio-libs/aiohttp Author: Nikolay Kim Author-email: fafhrd91@gmail.com Maintainer: Nikolay Kim , Andrew Svetlov Maintainer-email: aio-libs@googlegroups.com License: Apache 2 +Project-URL: CI: Circle, https://circleci.com/gh/aio-libs/aiohttp +Project-URL: CI: Shippable, https://app.shippable.com/github/aio-libs/aiohttp +Project-URL: Docs: RTD, https://docs.aiohttp.org +Project-URL: GitHub: repo, https://github.com/aio-libs/aiohttp +Project-URL: Chat: Gitter, https://gitter.im/aio-libs/Lobby +Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/aiohttp +Project-URL: CI: AppVeyor, https://ci.appveyor.com/project/aio-libs/aiohttp +Project-URL: CI: Travis, https://travis-ci.com/aio-libs/aiohttp +Project-URL: GitHub: issues, https://github.com/aio-libs/aiohttp/issues Description: ================================== Async http client/server framework ================================== @@ -17,21 +26,28 @@ :width: 64px :alt: aiohttp logo - .. image:: https://travis-ci.org/aio-libs/aiohttp.svg?branch=master - :target: https://travis-ci.org/aio-libs/aiohttp + | + + .. image:: https://travis-ci.com/aio-libs/aiohttp.svg?branch=master + :target: https://travis-ci.com/aio-libs/aiohttp :align: right :alt: Travis status for master branch + .. image:: https://ci.appveyor.com/api/projects/status/tnddy9k6pphl8w7k/branch/master?svg=true + :target: https://ci.appveyor.com/project/aio-libs/aiohttp + :align: right + :alt: AppVeyor 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://badge.fury.io/py/aiohttp + :target: https://pypi.org/project/aiohttp :alt: Latest PyPI package version .. image:: https://readthedocs.org/projects/aiohttp/badge/?version=latest - :target: http://docs.aiohttp.org/ + :target: https://docs.aiohttp.org/ :alt: Latest Read The Docs .. image:: https://badges.gitter.im/Join%20Chat.svg @@ -42,9 +58,9 @@ ============ - Supports both client and server side of HTTP protocol. - - Supports both client and server Web-Sockets out-of-the-box without the + - Supports both client and server Web-Sockets out-of-the-box and avoids Callback Hell. - - Web-server has middlewares and pluggable routing. + - Provides Web-server with middlewares and pluggable routing. Getting started @@ -53,18 +69,16 @@ Client ------ - To retrieve something from the web: + To get something from the web: .. code-block:: python import aiohttp import asyncio - import async_timeout async def fetch(session, url): - async with async_timeout.timeout(10): - async with session.get(url) as response: - return await response.text() + async with session.get(url) as response: + return await response.text() async def main(): async with aiohttp.ClientSession() as session: @@ -79,10 +93,11 @@ Server ------ - This is simple usage example: + An example using a simple server: .. code-block:: python + # examples/server_simple.py from aiohttp import web async def handle(request): @@ -95,11 +110,11 @@ await ws.prepare(request) async for msg in ws: - if msg.type == web.MsgType.text: + if msg.type == web.WSMsgType.text: await ws.send_str("Hello, {}".format(msg.data)) - elif msg.type == web.MsgType.binary: + elif msg.type == web.WSMsgType.binary: await ws.send_bytes(msg.data) - elif msg.type == web.MsgType.close: + elif msg.type == web.WSMsgType.close: break return ws @@ -118,6 +133,13 @@ https://aiohttp.readthedocs.io/ + + Demos + ===== + + https://github.com/aio-libs/aiohttp-demos + + External links ============== @@ -175,20 +197,20 @@ ======== The aiohttp community would like to thank Keepsafe - (https://www.getkeepsafe.com) for it's support in the early days of + (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: + The latest developer version is available in a GitHub repository: https://github.com/aio-libs/aiohttp Benchmarks ========== - If you are interested in by efficiency, AsyncIO community maintains a + 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 @@ -208,112 +230,95 @@ .. towncrier release notes start - 3.1.3 (2018-04-12) - ================== - - - Fix cancellation broadcast during DNS resolve (`#2910 `_) - - - 3.1.2 (2018-04-05) - ================== - - - Make ``LineTooLong`` exception more detailed about actual data size (`#2863 `_) - - Call ``on_chunk_sent`` when write_eof takes as a param the last chunk (`#2909 `_) - - - 3.1.1 (2018-03-27) - ================== - - - Support *asynchronous iterators* (and *asynchronous generators* as - well) in both client and server API as request / response BODY - payloads. (`#2802 `_) - - - 3.1.0 (2018-03-21) - ================== + 3.5.1 (2018-12-24) + ==================== - Welcome to aiohttp 3.1 release. + - Fix a regression about ``ClientSession._requote_redirect_url`` modification in debug + mode. - This is an *incremental* release, fully backward compatible with *aiohttp 3.0*. + 3.5.0 (2018-12-22) + ==================== - But we have added several new features. - - The most visible one is ``app.add_routes()`` (an alias for existing - ``app.router.add_routes()``. The addition is very important because - all *aiohttp* docs now uses ``app.add_routes()`` call in code - snippets. All your existing code still do register routes / resource - without any warning but you've got the idea for a favorite way: noisy - ``app.router.add_get()`` is replaced by ``app.add_routes()``. - - The library does not make a preference between decorators:: - - routes = web.RouteTableDef() - - @routes.get('/') - async def hello(request): - return web.Response(text="Hello, world") - - app.add_routes(routes) - - and route tables as a list:: - - async def hello(request): - return web.Response(text="Hello, world") - - app.add_routes([web.get('/', hello)]) + Features + -------- - Both ways are equal, user may decide basing on own code taste. + - The library type annotations are checked in strict mode now. + - Add support for setting cookies for individual request (`#2387 `_) + - Application.add_domain implementation (`#2809 `_) + - The default ``app`` in the request returned by ``test_utils.make_mocked_request`` + can now have objects assigned to it and retrieved using the ``[]`` operator. (`#3174 `_) + - Make ``request.url`` accessible when transport is closed. (`#3177 `_) + - Add ``zlib_executor_size`` argument to ``Response`` constructor to allow compression to run in a background executor to avoid blocking the main thread and potentially triggering health check failures. (`#3205 `_) + - Enable users to set `ClientTimeout` in `aiohttp.request` (`#3213 `_) + - Don't raise a warning if ``NETRC`` environment variable is not set and ``~/.netrc`` file + doesn't exist. (`#3267 `_) + - Add default logging handler to web.run_app - Also we have a lot of minor features, bug fixes and documentation - updates, see below. + If the `Application.debug` flag is set and the default logger `aiohttp.access` is used, access logs will now be output using a `stderr` `StreamHandler` if no handlers are attached. Furthermore, if the default logger has no log level set, the log level will be set to `DEBUG`. (`#3324 `_) + - Add method argument to ``session.ws_connect()``. - Features - -------- + Sometimes server API requires a different HTTP method for WebSocket connection establishment. - - Relax JSON content-type checking in the ``ClientResponse.json()`` to allow - "application/xxx+json" instead of strict "application/json". (`#2206 `_) - - Bump C HTTP parser to version 2.8 (`#2730 `_) - - Accept a coroutine as an application factory in ``web.run_app`` and gunicorn - worker. (`#2739 `_) - - Implement application cleanup context (``app.cleanup_ctx`` property). (`#2747 `_) - - Make ``writer.write_headers`` a coroutine. (`#2762 `_) - - Add tracking signals for getting request/response bodies. (`#2767 `_) - - Deprecate ClientResponseError.code in favor of .status to keep similarity - with response classes. (`#2781 `_) - - Implement ``app.add_routes()`` method. (`#2787 `_) - - Implement ``web.static()`` and ``RouteTableDef.static()`` API. (`#2795 `_) - - Install a test event loop as default by ``asyncio.set_event_loop()``. The - change affects aiohttp test utils but backward compatibility is not broken - for 99.99% of use cases. (`#2804 `_) - - Refactor ``ClientResponse`` constructor: make logically required constructor - arguments mandatory, drop ``_post_init()`` method. (`#2820 `_) - - Use ``app.add_routes()`` in server docs everywhere (`#2830 `_) - - Websockets refactoring, all websocket writer methods are converted into - coroutines. (`#2836 `_) - - Provide ``Content-Range`` header for ``Range`` requests (`#2844 `_) + For example, ``Docker exec`` needs POST. (`#3378 `_) + - Create a task per request handling. (`#3406 `_) Bugfixes -------- - - Fix websocket client return EofStream. (`#2784 `_) - - Fix websocket demo. (`#2789 `_) - - Property ``BaseRequest.http_range`` now returns a python-like slice when - requesting the tail of the range. It's now indicated by a negative value in - ``range.start`` rather then in ``range.stop`` (`#2805 `_) - - Close a connection if an unexpected exception occurs while sending a request - (`#2827 `_) - - Fix firing DNS tracing events. (`#2841 `_) + - Enable passing `access_log_class` via `handler_args` (`#3158 `_) + - Return empty bytes with end-of-chunk marker in empty stream reader. (`#3186 `_) + - Accept ``CIMultiDictProxy`` instances for ``headers`` argument in ``web.Response`` + constructor. (`#3207 `_) + - Don't uppercase HTTP method in parser (`#3233 `_) + - Make method match regexp RFC-7230 compliant (`#3235 `_) + - Add ``app.pre_frozen`` state to properly handle startup signals in sub-applications. (`#3237 `_) + - Enhanced parsing and validation of helpers.BasicAuth.decode. (`#3239 `_) + - Change imports from collections module in preparation for 3.8. (`#3258 `_) + - Ensure Host header is added first to ClientRequest to better replicate browser (`#3265 `_) + - Fix forward compatibility with Python 3.8: importing ABCs directly from the collections module will not be supported anymore. (`#3273 `_) + - Keep the query string by `normalize_path_middleware`. (`#3278 `_) + - Fix missing parameter ``raise_for_status`` for aiohttp.request() (`#3290 `_) + - Bracket IPv6 addresses in the HOST header (`#3304 `_) + - Fix default message for server ping and pong frames. (`#3308 `_) + - Fix tests/test_connector.py typo and tests/autobahn/server.py duplicate loop def. (`#3337 `_) + - Fix false-negative indicator end_of_HTTP_chunk in StreamReader.readchunk function (`#3361 `_) + - Release HTTP response before raising status exception (`#3364 `_) + - Fix task cancellation when ``sendfile()`` syscall is used by static file handling. (`#3383 `_) + - Fix stack trace for ``asyncio.TimeoutError`` which was not logged, when it is caught + in the handler. (`#3414 `_) Improved Documentation ---------------------- - - Document behavior when cchardet detects encodings that are unknown to Python. - (`#2732 `_) - - Add diagrams for tracing request life style. (`#2748 `_) - - Drop removed functionality for passing ``StreamReader`` as data at client - side. (`#2793 `_) + - Improve documentation of ``Application.make_handler`` parameters. (`#3152 `_) + - Fix BaseRequest.raw_headers doc. (`#3215 `_) + - Fix typo in TypeError exception reason in ``web.Application._handle`` (`#3229 `_) + - Make server access log format placeholder %b documentation reflect + behavior and docstring. (`#3307 `_) + + + Deprecations and Removals + ------------------------- + + - Deprecate modification of ``session.requote_redirect_url`` (`#2278 `_) + - Deprecate ``stream.unread_data()`` (`#3260 `_) + - Deprecated use of boolean in ``resp.enable_compression()`` (`#3318 `_) + - Encourage creation of aiohttp public objects inside a coroutine (`#3331 `_) + - Drop dead ``Connection.detach()`` and ``Connection.writer``. Both methods were broken + for more than 2 years. (`#3358 `_) + - Deprecate ``app.loop``, ``request.loop``, ``client.loop`` and ``connector.loop`` properties. (`#3374 `_) + - Deprecate explicit debug argument. Use asyncio debug mode instead. (`#3381 `_) + - Deprecate body parameter in HTTPException (and derived classes) constructor. (`#3385 `_) + - Deprecate bare connector close, use ``async with connector:`` and ``await connector.close()`` instead. (`#3417 `_) + - Deprecate obsolete ``read_timeout`` and ``conn_timeout`` in ``ClientSession`` constructor. (`#3438 `_) + + + Misc + ---- + + - #3341, #3351 Platform: UNKNOWN Classifier: License :: OSI Approved :: Apache Software License Classifier: Intended Audience :: Developers @@ -321,6 +326,7 @@ Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 Classifier: Development Status :: 5 - Production/Stable Classifier: Operating System :: POSIX Classifier: Operating System :: MacOS :: MacOS X @@ -328,3 +334,4 @@ Classifier: Topic :: Internet :: WWW/HTTP Classifier: Framework :: AsyncIO Requires-Python: >=3.5.3 +Provides-Extra: speedups diff -Nru python-aiohttp-3.1.3/pytest.ci.ini python-aiohttp-3.5.1/pytest.ci.ini --- python-aiohttp-3.1.3/pytest.ci.ini 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/pytest.ci.ini 2018-12-24 20:58:54.000000000 +0000 @@ -0,0 +1,7 @@ +[pytest] +addopts = --cov=aiohttp --cov-report term-missing:skip-covered -v -rxXs +filterwarnings = error +junit_suite_name = aiohttp_test_suite +norecursedirs = dist docs build .tox .eggs +minversion = 3.8.2 +testpaths = tests/ diff -Nru python-aiohttp-3.1.3/pytest.ini python-aiohttp-3.5.1/pytest.ini --- python-aiohttp-3.1.3/pytest.ini 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/pytest.ini 2018-12-24 20:58:54.000000000 +0000 @@ -0,0 +1,7 @@ +[pytest] +addopts = --cov=aiohttp -v -rxXs +filterwarnings = error +junit_suite_name = aiohttp_test_suite +norecursedirs = dist docs build .tox .eggs +minversion = 3.8.2 +testpaths = tests/ diff -Nru python-aiohttp-3.1.3/README.rst python-aiohttp-3.5.1/README.rst --- python-aiohttp-3.1.3/README.rst 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/README.rst 2018-12-24 20:58:54.000000000 +0000 @@ -7,21 +7,28 @@ :width: 64px :alt: aiohttp logo -.. image:: https://travis-ci.org/aio-libs/aiohttp.svg?branch=master - :target: https://travis-ci.org/aio-libs/aiohttp +| + +.. image:: https://travis-ci.com/aio-libs/aiohttp.svg?branch=master + :target: https://travis-ci.com/aio-libs/aiohttp :align: right :alt: Travis status for master branch +.. image:: https://ci.appveyor.com/api/projects/status/tnddy9k6pphl8w7k/branch/master?svg=true + :target: https://ci.appveyor.com/project/aio-libs/aiohttp + :align: right + :alt: AppVeyor 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://badge.fury.io/py/aiohttp + :target: https://pypi.org/project/aiohttp :alt: Latest PyPI package version .. image:: https://readthedocs.org/projects/aiohttp/badge/?version=latest - :target: http://docs.aiohttp.org/ + :target: https://docs.aiohttp.org/ :alt: Latest Read The Docs .. image:: https://badges.gitter.im/Join%20Chat.svg @@ -32,9 +39,9 @@ ============ - Supports both client and server side of HTTP protocol. -- Supports both client and server Web-Sockets out-of-the-box without the +- Supports both client and server Web-Sockets out-of-the-box and avoids Callback Hell. -- Web-server has middlewares and pluggable routing. +- Provides Web-server with middlewares and pluggable routing. Getting started @@ -43,18 +50,16 @@ Client ------ -To retrieve something from the web: +To get something from the web: .. code-block:: python import aiohttp import asyncio - import async_timeout async def fetch(session, url): - async with async_timeout.timeout(10): - async with session.get(url) as response: - return await response.text() + async with session.get(url) as response: + return await response.text() async def main(): async with aiohttp.ClientSession() as session: @@ -69,10 +74,11 @@ Server ------ -This is simple usage example: +An example using a simple server: .. code-block:: python + # examples/server_simple.py from aiohttp import web async def handle(request): @@ -85,11 +91,11 @@ await ws.prepare(request) async for msg in ws: - if msg.type == web.MsgType.text: + if msg.type == web.WSMsgType.text: await ws.send_str("Hello, {}".format(msg.data)) - elif msg.type == web.MsgType.binary: + elif msg.type == web.WSMsgType.binary: await ws.send_bytes(msg.data) - elif msg.type == web.MsgType.close: + elif msg.type == web.WSMsgType.close: break return ws @@ -108,6 +114,13 @@ https://aiohttp.readthedocs.io/ + +Demos +===== + +https://github.com/aio-libs/aiohttp-demos + + External links ============== @@ -165,19 +178,19 @@ ======== The aiohttp community would like to thank Keepsafe -(https://www.getkeepsafe.com) for it's support in the early days of +(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: +The latest developer version is available in a GitHub repository: https://github.com/aio-libs/aiohttp Benchmarks ========== -If you are interested in by efficiency, AsyncIO community maintains a +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 -Nru python-aiohttp-3.1.3/.readthedocs.yml python-aiohttp-3.5.1/.readthedocs.yml --- python-aiohttp-3.1.3/.readthedocs.yml 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/.readthedocs.yml 2018-12-24 20:58:53.000000000 +0000 @@ -2,4 +2,4 @@ image: latest python: version: 3.6 - pip_install: true + pip_install: false diff -Nru python-aiohttp-3.1.3/requirements/ci.txt python-aiohttp-3.5.1/requirements/ci.txt --- python-aiohttp-3.1.3/requirements/ci.txt 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/requirements/ci.txt 2018-12-24 20:58:54.000000000 +0000 @@ -1,5 +1,7 @@ setuptools-git==1.2 +mypy==0.650; implementation_name=="cpython" +mypy-extensions==0.4.1; implementation_name=="cpython" --r doc.txt -r ci-wheel.txt +-r doc.txt -e . diff -Nru python-aiohttp-3.1.3/requirements/ci-wheel.txt python-aiohttp-3.5.1/requirements/ci-wheel.txt --- python-aiohttp-3.1.3/requirements/ci-wheel.txt 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/requirements/ci-wheel.txt 2018-12-24 20:58:54.000000000 +0000 @@ -1,28 +1,24 @@ -attrs==17.4.0 -async-generator==1.9 -async-timeout==2.0.1 +-r flake.txt +attrs==18.2.0 +async-generator==1.10 +async-timeout==3.0.1 brotlipy==0.7.0 -cchardet==2.1.1 +cchardet==2.1.4 chardet==3.0.4 -coverage==4.5.1 -cython==0.28.1 -flake8==3.5.0 -gunicorn==19.7.1 -isort==4.3.4 -pip==9.0.2 -pyflakes==1.6.0 -multidict==4.1.0 -pytest==3.4.2 -pytest-cov==2.5.1 -pytest-mock==1.7.1 -pytest-xdist==1.22.2 -towncrier==17.8.0 -tox==2.9.1 -twine==1.10.0 -yarl==1.1.1 +coverage==4.5.2 +cython==0.29.2 +gunicorn==19.9.0 +multidict==4.5.2 +pytest==4.0.2 +pytest-cov==2.6.0 +pytest-mock==1.10.0 +tox==3.6.0 +twine==1.12.1 +yarl==1.3.0 # Using PEP 508 env markers to control dependency on runtimes: aiodns==1.1.1; platform_system!="Windows" # required c-ares will not build on windows -codecov==2.0.15; platform_system!="Windows" # We only use it in Travis CI -uvloop==0.9.1; platform_system!="Windows" and implementation_name=="cpython" # MagicStack/uvloop#14 -idna-ssl==1.0.1; python_version<"3.7" +codecov==2.0.15 +uvloop==0.11.3; platform_system!="Windows" and implementation_name=="cpython" and python_version<"3.7" # MagicStack/uvloop#14 +idna-ssl==1.1.0; python_version<"3.7" +typing_extensions==3.6.6; python_version<"3.7" diff -Nru python-aiohttp-3.1.3/requirements/cython.txt python-aiohttp-3.5.1/requirements/cython.txt --- python-aiohttp-3.1.3/requirements/cython.txt 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/requirements/cython.txt 2018-12-24 20:58:54.000000000 +0000 @@ -0,0 +1 @@ +cython==0.29.2 diff -Nru python-aiohttp-3.1.3/requirements/dev.txt python-aiohttp-3.5.1/requirements/dev.txt --- python-aiohttp-3.1.3/requirements/dev.txt 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/requirements/dev.txt 2018-12-24 20:58:54.000000000 +0000 @@ -1,5 +1,3 @@ -r ci.txt -ipdb==0.11 -pytest-sugar==0.9.1 -ipython==6.2.1 -cherry_picker==1.0.0; python_version>="3.6" +-r towncrier.txt +cherry_picker==1.2.1; python_version>="3.6" diff -Nru python-aiohttp-3.1.3/requirements/doc-spelling.txt python-aiohttp-3.5.1/requirements/doc-spelling.txt --- python-aiohttp-3.1.3/requirements/doc-spelling.txt 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/requirements/doc-spelling.txt 2018-12-24 20:58:54.000000000 +0000 @@ -1 +1 @@ -sphinxcontrib-spelling==4.1.0; platform_system!="Windows" # We only use it in Travis CI +sphinxcontrib-spelling==4.2.0; platform_system!="Windows" # We only use it in Travis CI diff -Nru python-aiohttp-3.1.3/requirements/doc.txt python-aiohttp-3.5.1/requirements/doc.txt --- python-aiohttp-3.1.3/requirements/doc.txt 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/requirements/doc.txt 2018-12-24 20:58:54.000000000 +0000 @@ -1,5 +1,5 @@ -sphinx==1.7.1 +sphinx==1.8.2 sphinxcontrib-asyncio==0.2.0 pygments>=2.1 -aiohttp-theme==0.1.4 +aiohttp-theme==0.1.5 sphinxcontrib-blockdiag==1.5.5 diff -Nru python-aiohttp-3.1.3/requirements/flake.txt python-aiohttp-3.5.1/requirements/flake.txt --- python-aiohttp-3.1.3/requirements/flake.txt 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/requirements/flake.txt 2018-12-24 20:58:54.000000000 +0000 @@ -0,0 +1,2 @@ +flake8==3.6.0 +isort==4.3.4 diff -Nru python-aiohttp-3.1.3/requirements/towncrier.txt python-aiohttp-3.5.1/requirements/towncrier.txt --- python-aiohttp-3.1.3/requirements/towncrier.txt 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/requirements/towncrier.txt 2018-12-24 20:58:54.000000000 +0000 @@ -0,0 +1 @@ +towncrier==18.6.0 diff -Nru python-aiohttp-3.1.3/requirements/wheel.txt python-aiohttp-3.5.1/requirements/wheel.txt --- python-aiohttp-3.1.3/requirements/wheel.txt 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/requirements/wheel.txt 2018-12-24 20:58:54.000000000 +0000 @@ -1,3 +1,3 @@ -cython==0.28.1 -pytest==3.4.2 -twine==1.10.0 +cython==0.29.2 +pytest==4.0.2 +twine==1.12.1 diff -Nru python-aiohttp-3.1.3/setup.cfg python-aiohttp-3.5.1/setup.cfg --- python-aiohttp-3.1.3/setup.cfg 2018-04-13 10:03:23.000000000 +0000 +++ python-aiohttp-3.5.1/setup.cfg 2018-12-24 20:59:58.000000000 +0000 @@ -1,3 +1,9 @@ +[aliases] +test = pytest + +[metadata] +license_file = LICENSE.txt + [pep8] max-line-length = 79 @@ -5,14 +11,9 @@ zip_ok = false [flake8] -ignore = N801,N802,N803,E226 +ignore = N801,N802,N803,E226,W504,E252 max-line-length = 79 -[tool:pytest] -testpaths = tests -addopts = --aiohttp-loop=all -filterwarnings = error - [isort] known_third_party = jinja2 known_first_party = aiohttp,aiohttp_jinja2,aiopg @@ -28,6 +29,48 @@ source = aiohttp, tests omit = site-packages +[mypy] +follow_imports = silent +strict_optional = True +warn_redundant_casts = True +check_untyped_defs = True +disallow_any_generics = True +disallow_untyped_defs = True +warn_unused_ignores = True + +[mypy-pytest] +ignore_missing_imports = true + +[mypy-uvloop] +ignore_missing_imports = true + +[mypy-tokio] +ignore_missing_imports = true + +[mypy-async_generator] +ignore_missing_imports = true + +[mypy-aiodns] +ignore_missing_imports = true + +[mypy-gunicorn.config] +ignore_missing_imports = true + +[mypy-gunicorn.workers] +ignore_missing_imports = true + +[mypy-brotli] +ignore_missing_imports = true + +[mypy-chardet] +ignore_missing_imports = true + +[mypy-cchardet] +ignore_missing_imports = true + +[mypy-idna_ssl] +ignore_missing_imports = true + [egg_info] tag_build = tag_date = 0 diff -Nru python-aiohttp-3.1.3/setup.py python-aiohttp-3.5.1/setup.py --- python-aiohttp-3.1.3/setup.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/setup.py 2018-12-24 20:58:54.000000000 +0000 @@ -7,12 +7,12 @@ DistutilsPlatformError) from setuptools import Extension, setup -from setuptools.command.test import test as TestCommand if sys.version_info < (3, 5, 3): raise RuntimeError("aiohttp 3.x requires Python 3.5.3+") +here = pathlib.Path(__file__).parent try: from Cython.Build import cythonize @@ -20,17 +20,36 @@ except ImportError: USE_CYTHON = False +if (here / '.git').exists() and not USE_CYTHON: + print("Install cython when building from git clone", file=sys.stderr) + print("Hint:", file=sys.stderr) + print(" pip install cython", file=sys.stderr) + sys.exit(1) + + +if (here / '.git').exists() and not (here / 'vendor/http-parser/README.md'): + print("Install submodules when building from git clone", file=sys.stderr) + print("Hint:", file=sys.stderr) + print(" git submodule update --init", file=sys.stderr) + sys.exit(2) + + ext = '.pyx' if USE_CYTHON else '.c' extensions = [Extension('aiohttp._websocket', ['aiohttp/_websocket' + ext]), Extension('aiohttp._http_parser', ['aiohttp/_http_parser' + ext, - 'vendor/http-parser/http_parser.c'], + 'vendor/http-parser/http_parser.c', + 'aiohttp/_find_header.c'], define_macros=[('HTTP_PARSER_STRICT', 0)], ), Extension('aiohttp._frozenlist', - ['aiohttp/_frozenlist' + ext])] + ['aiohttp/_frozenlist' + ext]), + Extension('aiohttp._helpers', + ['aiohttp/_helpers' + ext]), + Extension('aiohttp._http_writer', + ['aiohttp/_http_writer' + ext])] if USE_CYTHON: @@ -58,7 +77,6 @@ raise BuildFailed() -here = pathlib.Path(__file__).parent txt = (here / 'aiohttp' / '__init__.py').read_text('utf-8') try: @@ -67,30 +85,29 @@ except IndexError: raise RuntimeError('Unable to determine version.') - -install_requires = ['attrs>=17.3.0', 'chardet>=2.0,<4.0', - 'multidict>=4.0,<5.0', - 'async_timeout>=1.2,<3.0', - 'yarl>=1.0,<2.0'] - -if sys.version_info < (3, 7): - install_requires.append('idna-ssl>=1.0') +install_requires = [ + 'attrs>=17.3.0', + 'chardet>=2.0,<4.0', + 'multidict>=4.0,<5.0', + 'async_timeout>=3.0,<4.0', + 'yarl>=1.0,<2.0', + 'idna-ssl>=1.0; python_version<"3.7"', + 'typing_extensions>=3.6.5; python_version<"3.7"', +] def read(f): return (here / f).read_text('utf-8').strip() -class PyTest(TestCommand): - user_options = [] - - def run(self): - import subprocess - errno = subprocess.call([sys.executable, '-m', 'pytest', 'tests']) - raise SystemExit(errno) - +NEEDS_PYTEST = {'pytest', 'test'}.intersection(sys.argv) +pytest_runner = ['pytest-runner'] if NEEDS_PYTEST else [] -tests_require = install_requires + ['pytest', 'gunicorn', 'pytest-timeout'] +tests_require = [ + 'pytest', 'gunicorn', + 'pytest-timeout', 'async-generator', + 'pytest-xdist', +] args = dict( @@ -105,6 +122,7 @@ 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', 'Development Status :: 5 - Production/Stable', 'Operating System :: POSIX', 'Operating System :: MacOS :: MacOS X', @@ -117,16 +135,35 @@ maintainer=', '.join(('Nikolay Kim ', 'Andrew Svetlov ')), maintainer_email='aio-libs@googlegroups.com', - url='https://github.com/aio-libs/aiohttp/', + url='https://github.com/aio-libs/aiohttp', + project_urls={ + 'Chat: Gitter': 'https://gitter.im/aio-libs/Lobby', + 'CI: AppVeyor': 'https://ci.appveyor.com/project/aio-libs/aiohttp', + 'CI: Circle': 'https://circleci.com/gh/aio-libs/aiohttp', + 'CI: Shippable': 'https://app.shippable.com/github/aio-libs/aiohttp', + 'CI: Travis': 'https://travis-ci.com/aio-libs/aiohttp', + 'Coverage: codecov': 'https://codecov.io/github/aio-libs/aiohttp', + 'Docs: RTD': 'https://docs.aiohttp.org', + 'GitHub: issues': 'https://github.com/aio-libs/aiohttp/issues', + 'GitHub: repo': 'https://github.com/aio-libs/aiohttp', + }, license='Apache 2', packages=['aiohttp'], python_requires='>=3.5.3', install_requires=install_requires, + extras_require={ + 'speedups': [ + 'aiodns', + 'brotlipy', + 'cchardet', + ], + }, tests_require=tests_require, + setup_requires=pytest_runner, include_package_data=True, ext_modules=extensions, - cmdclass=dict(build_ext=ve_build_ext, - test=PyTest)) + cmdclass=dict(build_ext=ve_build_ext), +) try: setup(**args) Binary files /tmp/tmpYRAZo5/bce_IiBcz8/python-aiohttp-3.1.3/tests/aiohttp.jpg and /tmp/tmpYRAZo5/6pNZuTByL6/python-aiohttp-3.5.1/tests/aiohttp.jpg differ Binary files /tmp/tmpYRAZo5/bce_IiBcz8/python-aiohttp-3.1.3/tests/aiohttp.png and /tmp/tmpYRAZo5/6pNZuTByL6/python-aiohttp-3.5.1/tests/aiohttp.png differ diff -Nru python-aiohttp-3.1.3/tests/autobahn/server.py python-aiohttp-3.5.1/tests/autobahn/server.py --- python-aiohttp-3.1.3/tests/autobahn/server.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/autobahn/server.py 2018-12-24 20:58:54.000000000 +0000 @@ -34,7 +34,7 @@ app = web.Application() app.router.add_route('GET', '/', wshandler) - handler = app.make_handler() + handler = app._make_handler() srv = await loop.create_server(handler, '127.0.0.1', 9001) print("Server started at http://127.0.0.1:9001") return app, srv, handler @@ -50,8 +50,6 @@ loop = asyncio.get_event_loop() logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s') - - loop = asyncio.get_event_loop() app, srv, handler = loop.run_until_complete(main(loop)) try: loop.run_forever() diff -Nru python-aiohttp-3.1.3/tests/conftest.py python-aiohttp-3.5.1/tests/conftest.py --- python-aiohttp-3.1.3/tests/conftest.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/conftest.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,7 +1,8 @@ +import pathlib +import shutil import tempfile import pytest -from py import path pytest_plugins = ['aiohttp.pytest_plugin', 'pytester'] @@ -12,6 +13,6 @@ """Provides a temporary directory with a shorter file system path than the tmpdir fixture. """ - tmpdir = path.local(tempfile.mkdtemp()) + tmpdir = pathlib.Path(tempfile.mkdtemp()) yield tmpdir - tmpdir.remove(rec=1) + shutil.rmtree(tmpdir, ignore_errors=True) diff -Nru python-aiohttp-3.1.3/tests/test_base_protocol.py python-aiohttp-3.5.1/tests/test_base_protocol.py --- python-aiohttp-3.1.3/tests/test_base_protocol.py 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_base_protocol.py 2018-12-24 20:58:54.000000000 +0000 @@ -0,0 +1,182 @@ +import asyncio +from contextlib import suppress +from unittest import mock + +import pytest + +from aiohttp.base_protocol import BaseProtocol + + +async def test_loop() -> None: + loop = asyncio.get_event_loop() + asyncio.set_event_loop(None) + pr = BaseProtocol(loop) + assert pr._loop is loop + + +async def test_pause_writing() -> None: + loop = asyncio.get_event_loop() + pr = BaseProtocol(loop) + assert not pr._paused + pr.pause_writing() + assert pr._paused + + +async def test_resume_writing_no_waiters() -> None: + loop = asyncio.get_event_loop() + pr = BaseProtocol(loop=loop) + pr.pause_writing() + assert pr._paused + pr.resume_writing() + assert not pr._paused + + +async def test_connection_made() -> None: + loop = asyncio.get_event_loop() + pr = BaseProtocol(loop=loop) + tr = mock.Mock() + assert pr.transport is None + pr.connection_made(tr) + assert pr.transport is not None + + +async def test_connection_lost_not_paused() -> None: + loop = asyncio.get_event_loop() + pr = BaseProtocol(loop=loop) + tr = mock.Mock() + pr.connection_made(tr) + assert not pr._connection_lost + pr.connection_lost(None) + assert pr.transport is None + assert pr._connection_lost + + +async def test_connection_lost_paused_without_waiter() -> None: + loop = asyncio.get_event_loop() + pr = BaseProtocol(loop=loop) + tr = mock.Mock() + pr.connection_made(tr) + assert not pr._connection_lost + pr.pause_writing() + pr.connection_lost(None) + assert pr.transport is None + assert pr._connection_lost + + +async def test_drain_lost() -> None: + loop = asyncio.get_event_loop() + pr = BaseProtocol(loop=loop) + tr = mock.Mock() + pr.connection_made(tr) + pr.connection_lost(None) + with pytest.raises(ConnectionResetError): + await pr._drain_helper() + + +async def test_drain_not_paused() -> None: + loop = asyncio.get_event_loop() + pr = BaseProtocol(loop=loop) + tr = mock.Mock() + pr.connection_made(tr) + assert pr._drain_waiter is None + await pr._drain_helper() + assert pr._drain_waiter is None + + +async def test_resume_drain_waited() -> None: + loop = asyncio.get_event_loop() + pr = BaseProtocol(loop=loop) + tr = mock.Mock() + pr.connection_made(tr) + pr.pause_writing() + + t = loop.create_task(pr._drain_helper()) + await asyncio.sleep(0) + + assert pr._drain_waiter is not None + pr.resume_writing() + assert (await t) is None + assert pr._drain_waiter is None + + +async def test_lost_drain_waited_ok() -> None: + loop = asyncio.get_event_loop() + pr = BaseProtocol(loop=loop) + tr = mock.Mock() + pr.connection_made(tr) + pr.pause_writing() + + t = loop.create_task(pr._drain_helper()) + await asyncio.sleep(0) + + assert pr._drain_waiter is not None + pr.connection_lost(None) + assert (await t) is None + assert pr._drain_waiter is None + + +async def test_lost_drain_waited_exception() -> None: + loop = asyncio.get_event_loop() + pr = BaseProtocol(loop=loop) + tr = mock.Mock() + pr.connection_made(tr) + pr.pause_writing() + + t = loop.create_task(pr._drain_helper()) + await asyncio.sleep(0) + + assert pr._drain_waiter is not None + exc = RuntimeError() + pr.connection_lost(exc) + with pytest.raises(RuntimeError) as cm: + await t + assert cm.value is exc + assert pr._drain_waiter is None + + +async def test_lost_drain_cancelled() -> None: + loop = asyncio.get_event_loop() + pr = BaseProtocol(loop=loop) + tr = mock.Mock() + pr.connection_made(tr) + pr.pause_writing() + + fut = loop.create_future() + + async def wait(): + fut.set_result(None) + await pr._drain_helper() + + t = loop.create_task(wait()) + await fut + t.cancel() + + assert pr._drain_waiter is not None + pr.connection_lost(None) + with suppress(asyncio.CancelledError): + await t + assert pr._drain_waiter is None + + +async def test_resume_drain_cancelled() -> None: + loop = asyncio.get_event_loop() + pr = BaseProtocol(loop=loop) + tr = mock.Mock() + pr.connection_made(tr) + pr.pause_writing() + + fut = loop.create_future() + + async def wait(): + fut.set_result(None) + await pr._drain_helper() + + t = loop.create_task(wait()) + await fut + t.cancel() + + assert pr._drain_waiter is not None + pr.resume_writing() + with suppress(asyncio.CancelledError): + await t + assert pr._drain_waiter is None diff -Nru python-aiohttp-3.1.3/tests/test_classbasedview.py python-aiohttp-3.5.1/tests/test_classbasedview.py --- python-aiohttp-3.1.3/tests/test_classbasedview.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_classbasedview.py 2018-12-24 20:58:54.000000000 +0000 @@ -6,13 +6,13 @@ from aiohttp.web_urldispatcher import View -def test_ctor(): +def test_ctor() -> None: request = mock.Mock() view = View(request) assert view.request is request -async def test_render_ok(): +async def test_render_ok() -> None: resp = web.Response(text='OK') class MyView(View): @@ -25,7 +25,7 @@ assert resp is resp2 -async def test_render_unknown_method(): +async def test_render_unknown_method() -> None: class MyView(View): async def get(self): @@ -40,7 +40,7 @@ assert ctx.value.status == 405 -async def test_render_unsupported_method(): +async def test_render_unsupported_method() -> None: class MyView(View): async def get(self): diff -Nru python-aiohttp-3.1.3/tests/test_client_connection.py python-aiohttp-3.5.1/tests/test_client_connection.py --- python-aiohttp-3.1.3/tests/test_client_connection.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_client_connection.py 2018-12-24 20:58:54.000000000 +0000 @@ -12,11 +12,6 @@ @pytest.fixture -def request(): - return mock.Mock() - - -@pytest.fixture def loop(): return mock.Mock() @@ -31,15 +26,15 @@ return mock.Mock(should_close=False) -def test_ctor(connector, key, protocol, loop): +def test_ctor(connector, key, protocol, loop) -> None: conn = Connection(connector, key, protocol, loop) - assert conn.loop is loop + with pytest.warns(DeprecationWarning): + assert conn.loop is loop assert conn.protocol is protocol - assert conn.writer is protocol.writer conn.close() -def test_callbacks_on_close(connector, key, protocol, loop): +def test_callbacks_on_close(connector, key, protocol, loop) -> None: conn = Connection(connector, key, protocol, loop) notified = False @@ -52,7 +47,7 @@ assert notified -def test_callbacks_on_release(connector, key, protocol, loop): +def test_callbacks_on_release(connector, key, protocol, loop) -> None: conn = Connection(connector, key, protocol, loop) notified = False @@ -65,20 +60,7 @@ assert notified -def test_callbacks_on_detach(connector, key, protocol, loop): - conn = Connection(connector, key, protocol, loop) - notified = False - - def cb(): - nonlocal notified - notified = True - - conn.add_callback(cb) - conn.detach() - assert notified - - -def test_callbacks_exception(connector, key, protocol, loop): +def test_callbacks_exception(connector, key, protocol, loop) -> None: conn = Connection(connector, key, protocol, loop) notified = False @@ -95,7 +77,7 @@ assert notified -def test_del(connector, key, protocol, loop): +def test_del(connector, key, protocol, loop) -> None: loop.is_closed.return_value = False conn = Connection(connector, key, protocol, loop) exc_handler = mock.Mock() @@ -113,7 +95,7 @@ loop.call_exception_handler.assert_called_with(msg) -def test_close(connector, key, protocol, loop): +def test_close(connector, key, protocol, loop) -> None: conn = Connection(connector, key, protocol, loop) assert not conn.closed conn.close() @@ -122,7 +104,7 @@ assert conn.closed -def test_release(connector, key, protocol, loop): +def test_release(connector, key, protocol, loop) -> None: conn = Connection(connector, key, protocol, loop) assert not conn.closed conn.release() @@ -132,7 +114,7 @@ assert conn.closed -def test_release_proto_should_close(connector, key, protocol, loop): +def test_release_proto_should_close(connector, key, protocol, loop) -> None: protocol.should_close = True conn = Connection(connector, key, protocol, loop) assert not conn.closed @@ -143,7 +125,7 @@ assert conn.closed -def test_release_released(connector, key, protocol, loop): +def test_release_released(connector, key, protocol, loop) -> None: conn = Connection(connector, key, protocol, loop) conn.release() connector._release.reset_mock() @@ -151,22 +133,3 @@ assert not protocol.transport.close.called assert conn._protocol is None assert not connector._release.called - - -def test_detach(connector, key, protocol, loop): - conn = Connection(connector, key, protocol, loop) - assert not conn.closed - conn.detach() - assert conn._protocol is None - assert connector._release_acquired.called - assert not connector._release.called - assert conn.closed - - -def test_detach_closed(connector, key, protocol, loop): - conn = Connection(connector, key, protocol, loop) - conn.release() - conn.detach() - - assert not connector._release_acquired.called - assert conn._protocol is None diff -Nru python-aiohttp-3.1.3/tests/test_client_exceptions.py python-aiohttp-3.5.1/tests/test_client_exceptions.py --- python-aiohttp-3.1.3/tests/test_client_exceptions.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_client_exceptions.py 2018-12-24 20:58:54.000000000 +0000 @@ -6,14 +6,14 @@ from aiohttp import client -def test_fingerprint_mismatch(): +def test_fingerprint_mismatch() -> None: err = client.ServerFingerprintMismatch('exp', 'got', 'host', 8888) expected = ('') assert expected == repr(err) -def test_invalid_url(): +def test_invalid_url() -> None: url = URL('http://example.com') err = client.InvalidURL(url) assert err.args[0] is url @@ -21,20 +21,20 @@ assert repr(err) == "" -def test_response_default_status(): +def test_response_default_status() -> None: err = client.ClientResponseError(history=None, request_info=None) assert err.status == 0 -def test_response_status(): +def test_response_status() -> None: err = client.ClientResponseError(status=400, history=None, request_info=None) assert err.status == 400 -def test_response_deprecated_code_property(): +def test_response_deprecated_code_property() -> None: with pytest.warns(DeprecationWarning): err = client.ClientResponseError(code=400, history=None, @@ -47,7 +47,7 @@ assert err.code == err.status -def test_response_both_code_and_status(): +def test_response_both_code_and_status() -> None: with pytest.raises(ValueError): client.ClientResponseError(code=400, status=400, diff -Nru python-aiohttp-3.1.3/tests/test_client_fingerprint.py python-aiohttp-3.5.1/tests/test_client_fingerprint.py --- python-aiohttp-3.1.3/tests/test_client_fingerprint.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_client_fingerprint.py 2018-12-24 20:58:54.000000000 +0000 @@ -10,25 +10,25 @@ ssl = pytest.importorskip('ssl') -def test_fingerprint_sha256(): +def test_fingerprint_sha256() -> None: sha256 = hashlib.sha256(b'12345678'*64).digest() fp = aiohttp.Fingerprint(sha256) assert fp.fingerprint == sha256 -def test_fingerprint_sha1(): +def test_fingerprint_sha1() -> None: sha1 = hashlib.sha1(b'12345678'*64).digest() with pytest.raises(ValueError): aiohttp.Fingerprint(sha1) -def test_fingerprint_md5(): +def test_fingerprint_md5() -> None: md5 = hashlib.md5(b'12345678'*64).digest() with pytest.raises(ValueError): aiohttp.Fingerprint(md5) -def test_fingerprint_check_no_ssl(): +def test_fingerprint_check_no_ssl() -> None: sha256 = hashlib.sha256(b'12345678'*64).digest() fp = aiohttp.Fingerprint(sha256) transport = mock.Mock() @@ -36,25 +36,25 @@ assert fp.check(transport) is None -def test__merge_ssl_params_verify_ssl(): +def test__merge_ssl_params_verify_ssl() -> None: with pytest.warns(DeprecationWarning): assert _merge_ssl_params(None, False, None, None) is False -def test__merge_ssl_params_verify_ssl_conflict(): +def test__merge_ssl_params_verify_ssl_conflict() -> None: ctx = ssl.SSLContext() with pytest.warns(DeprecationWarning): with pytest.raises(ValueError): _merge_ssl_params(ctx, False, None, None) -def test__merge_ssl_params_ssl_context(): +def test__merge_ssl_params_ssl_context() -> None: ctx = ssl.SSLContext() with pytest.warns(DeprecationWarning): assert _merge_ssl_params(None, None, ctx, None) is ctx -def test__merge_ssl_params_ssl_context_conflict(): +def test__merge_ssl_params_ssl_context_conflict() -> None: ctx1 = ssl.SSLContext() ctx2 = ssl.SSLContext() with pytest.warns(DeprecationWarning): @@ -62,14 +62,14 @@ _merge_ssl_params(ctx1, None, ctx2, None) -def test__merge_ssl_params_fingerprint(): +def test__merge_ssl_params_fingerprint() -> None: digest = hashlib.sha256(b'123').digest() with pytest.warns(DeprecationWarning): ret = _merge_ssl_params(None, None, None, digest) assert ret.fingerprint == digest -def test__merge_ssl_params_fingerprint_conflict(): +def test__merge_ssl_params_fingerprint_conflict() -> None: fingerprint = aiohttp.Fingerprint(hashlib.sha256(b'123').digest()) ctx = ssl.SSLContext() with pytest.warns(DeprecationWarning): @@ -77,11 +77,11 @@ _merge_ssl_params(ctx, None, None, fingerprint) -def test__merge_ssl_params_ssl(): +def test__merge_ssl_params_ssl() -> None: ctx = ssl.SSLContext() assert ctx is _merge_ssl_params(ctx, None, None, None) -def test__merge_ssl_params_invlid(): +def test__merge_ssl_params_invlid() -> None: with pytest.raises(TypeError): _merge_ssl_params(object(), None, None, None) diff -Nru python-aiohttp-3.1.3/tests/test_client_functional.py python-aiohttp-3.5.1/tests/test_client_functional.py --- python-aiohttp-3.1.3/tests/test_client_functional.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_client_functional.py 2018-12-24 20:58:54.000000000 +0000 @@ -16,6 +16,7 @@ import aiohttp from aiohttp import Fingerprint, ServerFingerprintMismatch, hdrs, web from aiohttp.abc import AbstractResolver +from aiohttp.client_exceptions import TooManyRedirects from aiohttp.test_utils import unused_port @@ -42,7 +43,8 @@ return val -async def test_keepalive_two_requests_success(aiohttp_client): +async def test_keepalive_two_requests_success( + aiohttp_client) -> None: async def handler(request): body = await request.read() assert b'' == body @@ -62,7 +64,7 @@ assert 1 == len(client._session.connector._conns) -async def test_keepalive_response_released(aiohttp_client): +async def test_keepalive_response_released(aiohttp_client) -> None: async def handler(request): body = await request.read() assert b'' == body @@ -82,7 +84,7 @@ assert 1 == len(client._session.connector._conns) -async def test_keepalive_server_force_close_connection(aiohttp_client): +async def test_keepalive_server_force_close_connection(aiohttp_client) -> None: async def handler(request): body = await request.read() assert b'' == body @@ -104,7 +106,7 @@ assert 0 == len(client._session.connector._conns) -async def test_release_early(aiohttp_client): +async def test_release_early(aiohttp_client) -> None: async def handler(request): await request.read() return web.Response(body=b'OK') @@ -118,7 +120,7 @@ assert 1 == len(client._session.connector._conns) -async def test_HTTP_304(aiohttp_client): +async def test_HTTP_304(aiohttp_client) -> None: async def handler(request): body = await request.read() assert b'' == body @@ -134,7 +136,7 @@ assert content == b'' -async def test_HTTP_304_WITH_BODY(aiohttp_client): +async def test_HTTP_304_WITH_BODY(aiohttp_client) -> None: async def handler(request): body = await request.read() assert b'' == body @@ -150,7 +152,7 @@ assert content == b'' -async def test_auto_header_user_agent(aiohttp_client): +async def test_auto_header_user_agent(aiohttp_client) -> None: async def handler(request): assert 'aiohttp' in request.headers['user-agent'] return web.Response() @@ -160,10 +162,10 @@ client = await aiohttp_client(app) resp = await client.get('/') - assert 200, resp.status + assert 200 == resp.status -async def test_skip_auto_headers_user_agent(aiohttp_client): +async def test_skip_auto_headers_user_agent(aiohttp_client) -> None: async def handler(request): assert hdrs.USER_AGENT not in request.headers return web.Response() @@ -176,7 +178,7 @@ assert 200 == resp.status -async def test_skip_default_auto_headers_user_agent(aiohttp_client): +async def test_skip_default_auto_headers_user_agent(aiohttp_client) -> None: async def handler(request): assert hdrs.USER_AGENT not in request.headers return web.Response() @@ -189,7 +191,7 @@ assert 200 == resp.status -async def test_skip_auto_headers_content_type(aiohttp_client): +async def test_skip_auto_headers_content_type(aiohttp_client) -> None: async def handler(request): assert hdrs.CONTENT_TYPE not in request.headers return web.Response() @@ -202,7 +204,7 @@ assert 200 == resp.status -async def test_post_data_bytesio(aiohttp_client): +async def test_post_data_bytesio(aiohttp_client) -> None: data = b'some buffer' async def handler(request): @@ -219,7 +221,7 @@ assert 200 == resp.status -async def test_post_data_with_bytesio_file(aiohttp_client): +async def test_post_data_with_bytesio_file(aiohttp_client) -> None: data = b'some buffer' async def handler(request): @@ -236,7 +238,7 @@ assert 200 == resp.status -async def test_post_data_stringio(aiohttp_client): +async def test_post_data_stringio(aiohttp_client) -> None: data = 'some buffer' async def handler(request): @@ -254,7 +256,7 @@ assert 200 == resp.status -async def test_post_data_textio_encoding(aiohttp_client): +async def test_post_data_textio_encoding(aiohttp_client) -> None: data = 'текст' async def handler(request): @@ -272,7 +274,7 @@ assert 200 == resp.status -async def test_ssl_client(ssl_ctx, aiohttp_server, aiohttp_client): +async def test_ssl_client(ssl_ctx, aiohttp_server, aiohttp_client) -> None: connector = aiohttp.TCPConnector(ssl=False) async def handler(request): @@ -336,7 +338,8 @@ assert exc.got == fingerprint -async def test_format_task_get(aiohttp_server, loop): +async def test_format_task_get(aiohttp_server) -> None: + loop = asyncio.get_event_loop() async def handler(request): return web.Response(body=b'OK') @@ -352,7 +355,7 @@ await client.close() -async def test_str_params(aiohttp_client): +async def test_str_params(aiohttp_client) -> None: async def handler(request): assert 'q=t est' in request.rel_url.query_string @@ -366,7 +369,7 @@ assert 200 == resp.status -async def test_drop_params_on_redirect(aiohttp_client): +async def test_drop_params_on_redirect(aiohttp_client) -> None: async def handler_redirect(request): return web.Response(status=301, headers={'Location': '/ok?a=redirect'}) @@ -384,7 +387,7 @@ assert resp.status == 200 -async def test_drop_fragment_on_redirect(aiohttp_client): +async def test_drop_fragment_on_redirect(aiohttp_client) -> None: async def handler_redirect(request): return web.Response(status=301, headers={'Location': '/ok#fragment'}) @@ -402,7 +405,7 @@ assert resp.url.path == '/ok' -async def test_drop_fragment(aiohttp_client): +async def test_drop_fragment(aiohttp_client) -> None: async def handler_ok(request): return web.Response(status=200) @@ -416,7 +419,7 @@ assert resp.url.path == '/ok' -async def test_history(aiohttp_client): +async def test_history(aiohttp_client) -> None: async def handler_redirect(request): return web.Response(status=301, headers={'Location': '/ok'}) @@ -438,7 +441,7 @@ assert resp_redirect.status == 200 -async def test_keepalive_closed_by_server(aiohttp_client): +async def test_keepalive_closed_by_server(aiohttp_client) -> None: async def handler(request): body = await request.read() assert b'' == body @@ -462,7 +465,7 @@ assert 0 == len(client._session.connector._conns) -async def test_wait_for(aiohttp_client): +async def test_wait_for(aiohttp_client) -> None: async def handler(request): return web.Response(body=b'OK') @@ -476,7 +479,7 @@ assert txt == 'OK' -async def test_raw_headers(aiohttp_client): +async def test_raw_headers(aiohttp_client) -> None: async def handler(request): return web.Response() @@ -494,7 +497,39 @@ resp.close() -async def test_204_with_gzipped_content_encoding(aiohttp_client): +async def test_host_header_first(aiohttp_client) -> None: + async def handler(request): + assert list(request.headers)[0] == hdrs.HOST + return web.Response() + + app = web.Application() + app.router.add_route('GET', '/', handler) + client = await aiohttp_client(app) + resp = await client.get('/') + assert resp.status == 200 + + +async def test_empty_header_values(aiohttp_client) -> None: + async def handler(request): + resp = web.Response() + resp.headers['X-Empty'] = '' + return resp + + app = web.Application() + app.router.add_route('GET', '/', handler) + client = await aiohttp_client(app) + resp = await client.get('/') + assert resp.status == 200 + raw_headers = tuple((bytes(h), bytes(v)) for h, v in resp.raw_headers) + assert raw_headers == ((b'X-Empty', b''), + (b'Content-Length', b'0'), + (b'Content-Type', b'application/octet-stream'), + (b'Date', mock.ANY), + (b'Server', mock.ANY)) + resp.close() + + +async def test_204_with_gzipped_content_encoding(aiohttp_client) -> None: async def handler(request): resp = web.StreamResponse(status=204) resp.content_length = 0 @@ -513,7 +548,7 @@ assert resp.closed -async def test_timeout_on_reading_headers(aiohttp_client, mocker): +async def test_timeout_on_reading_headers(aiohttp_client, mocker) -> None: mocker.patch('aiohttp.helpers.ceil').side_effect = ceil async def handler(request): @@ -530,7 +565,7 @@ await client.get('/', timeout=0.01) -async def test_timeout_on_conn_reading_headers(aiohttp_client, mocker): +async def test_timeout_on_conn_reading_headers(aiohttp_client, mocker) -> None: # tests case where user did not set a connection timeout mocker.patch('aiohttp.helpers.ceil').side_effect = ceil @@ -551,7 +586,7 @@ await client.get('/', timeout=0.01) -async def test_timeout_on_session_read_timeout(aiohttp_client, mocker): +async def test_timeout_on_session_read_timeout(aiohttp_client, mocker) -> None: mocker.patch('aiohttp.helpers.ceil').side_effect = ceil async def handler(request): @@ -564,13 +599,18 @@ app.router.add_route('GET', '/', handler) conn = aiohttp.TCPConnector() - client = await aiohttp_client(app, connector=conn, read_timeout=0.01) + client = await aiohttp_client( + app, + connector=conn, + timeout=aiohttp.ClientTimeout(sock_read=0.01)) with pytest.raises(asyncio.TimeoutError): await client.get('/') -async def test_timeout_on_reading_data(loop, aiohttp_client, mocker): +async def test_timeout_on_reading_data(aiohttp_client, mocker) -> None: + loop = asyncio.get_event_loop() + mocker.patch('aiohttp.helpers.ceil').side_effect = ceil fut = loop.create_future() @@ -592,7 +632,7 @@ await resp.read() -async def test_timeout_none(aiohttp_client, mocker): +async def test_timeout_none(aiohttp_client, mocker) -> None: mocker.patch('aiohttp.helpers.ceil').side_effect = ceil async def handler(request): @@ -608,7 +648,8 @@ assert resp.status == 200 -async def test_readline_error_on_conn_close(loop, aiohttp_client): +async def test_readline_error_on_conn_close(aiohttp_client) -> None: + loop = asyncio.get_event_loop() async def handler(request): resp_ = web.StreamResponse() @@ -646,7 +687,7 @@ await session.close() -async def test_no_error_on_conn_close_if_eof(aiohttp_client): +async def test_no_error_on_conn_close_if_eof(aiohttp_client) -> None: async def handler(request): resp_ = web.StreamResponse() @@ -675,7 +716,7 @@ await session.close() -async def test_error_not_overwrote_on_conn_close(aiohttp_client): +async def test_error_not_overwrote_on_conn_close(aiohttp_client) -> None: async def handler(request): resp_ = web.StreamResponse() @@ -697,7 +738,7 @@ assert isinstance(resp.content.exception(), ValueError) -async def test_HTTP_200_OK_METHOD(aiohttp_client): +async def test_HTTP_200_OK_METHOD(aiohttp_client) -> None: async def handler(request): return web.Response(text=request.method) @@ -723,7 +764,7 @@ assert meth.upper() == content -async def test_HTTP_200_OK_METHOD_connector(aiohttp_client): +async def test_HTTP_200_OK_METHOD_connector(aiohttp_client) -> None: async def handler(request): return web.Response(text=request.method) @@ -734,7 +775,7 @@ app = web.Application() for meth in ('get', 'post', 'put', 'delete', 'head'): app.router.add_route(meth.upper(), '/', handler) - client = await aiohttp_client(app, connector=conn, conn_timeout=0.2) + client = await aiohttp_client(app, connector=conn) for meth in ('get', 'post', 'put', 'delete', 'head'): resp = await client.request(meth, '/') @@ -751,7 +792,7 @@ assert meth.upper() == content -async def test_HTTP_302_REDIRECT_GET(aiohttp_client): +async def test_HTTP_302_REDIRECT_GET(aiohttp_client) -> None: async def handler(request): return web.Response(text=request.method) @@ -770,7 +811,7 @@ resp.close() -async def test_HTTP_302_REDIRECT_HEAD(aiohttp_client): +async def test_HTTP_302_REDIRECT_HEAD(aiohttp_client) -> None: async def handler(request): return web.Response(text=request.method) @@ -792,7 +833,7 @@ resp.close() -async def test_HTTP_302_REDIRECT_NON_HTTP(aiohttp_client): +async def test_HTTP_302_REDIRECT_NON_HTTP(aiohttp_client) -> None: async def redirect(request): raise web.HTTPFound(location='ftp://127.0.0.1/test/') @@ -805,7 +846,7 @@ await client.get('/redirect') -async def test_HTTP_302_REDIRECT_POST(aiohttp_client): +async def test_HTTP_302_REDIRECT_POST(aiohttp_client) -> None: async def handler(request): return web.Response(text=request.method) @@ -826,7 +867,8 @@ resp.close() -async def test_HTTP_302_REDIRECT_POST_with_content_length_hdr(aiohttp_client): +async def test_HTTP_302_REDIRECT_POST_with_content_length_hdr( + aiohttp_client) -> None: async def handler(request): return web.Response(text=request.method) @@ -836,7 +878,7 @@ raise web.HTTPFound(location='/') data = json.dumps({'some': 'data'}) - app = web.Application(debug=True) + app = web.Application() app.router.add_get('/', handler) app.router.add_post('/redirect', redirect) client = await aiohttp_client(app) @@ -853,7 +895,7 @@ resp.close() -async def test_HTTP_307_REDIRECT_POST(aiohttp_client): +async def test_HTTP_307_REDIRECT_POST(aiohttp_client) -> None: async def handler(request): return web.Response(text=request.method) @@ -875,7 +917,7 @@ resp.close() -async def test_HTTP_308_PERMANENT_REDIRECT_POST(aiohttp_client): +async def test_HTTP_308_PERMANENT_REDIRECT_POST(aiohttp_client) -> None: async def handler(request): return web.Response(text=request.method) @@ -897,7 +939,7 @@ resp.close() -async def test_HTTP_302_max_redirects(aiohttp_client): +async def test_HTTP_302_max_redirects(aiohttp_client) -> None: async def handler(request): return web.Response(text=request.method) @@ -914,13 +956,14 @@ app.router.add_get(r'/redirect/{count:\d+}', redirect) client = await aiohttp_client(app) - resp = await client.get('/redirect/5', max_redirects=2) - assert 302 == resp.status - assert 2 == len(resp.history) - resp.close() + with pytest.raises(TooManyRedirects) as ctx: + await client.get('/redirect/5', max_redirects=2) + assert 2 == len(ctx.value.history) + assert ctx.value.request_info.url.path == '/redirect/5' + assert ctx.value.request_info.method == 'GET' -async def test_HTTP_200_GET_WITH_PARAMS(aiohttp_client): +async def test_HTTP_200_GET_WITH_PARAMS(aiohttp_client) -> None: async def handler(request): return web.Response(text='&'.join( @@ -937,7 +980,7 @@ resp.close() -async def test_HTTP_200_GET_WITH_MultiDict_PARAMS(aiohttp_client): +async def test_HTTP_200_GET_WITH_MultiDict_PARAMS(aiohttp_client) -> None: async def handler(request): return web.Response(text='&'.join( @@ -955,7 +998,7 @@ resp.close() -async def test_HTTP_200_GET_WITH_MIXED_PARAMS(aiohttp_client): +async def test_HTTP_200_GET_WITH_MIXED_PARAMS(aiohttp_client) -> None: async def handler(request): return web.Response(text='&'.join( @@ -972,7 +1015,7 @@ resp.close() -async def test_POST_DATA(aiohttp_client): +async def test_POST_DATA(aiohttp_client) -> None: async def handler(request): data = await request.post() @@ -989,7 +1032,7 @@ resp.close() -async def test_POST_DATA_with_explicit_formdata(aiohttp_client): +async def test_POST_DATA_with_explicit_formdata(aiohttp_client) -> None: async def handler(request): data = await request.post() @@ -1009,7 +1052,7 @@ resp.close() -async def test_POST_DATA_with_charset(aiohttp_client): +async def test_POST_DATA_with_charset(aiohttp_client) -> None: async def handler(request): mp = await request.multipart() @@ -1031,7 +1074,7 @@ resp.close() -async def test_POST_DATA_formdats_with_charset(aiohttp_client): +async def test_POST_DATA_formdats_with_charset(aiohttp_client) -> None: async def handler(request): mp = await request.post() @@ -1052,7 +1095,7 @@ resp.close() -async def test_POST_DATA_with_charset_post(aiohttp_client): +async def test_POST_DATA_with_charset_post(aiohttp_client) -> None: async def handler(request): data = await request.post() @@ -1072,7 +1115,8 @@ resp.close() -async def test_POST_DATA_with_context_transfer_encoding(aiohttp_client): +async def test_POST_DATA_with_context_transfer_encoding( + aiohttp_client) -> None: async def handler(request): data = await request.post() @@ -1117,7 +1161,7 @@ resp.close() -async def test_POST_MultiDict(aiohttp_client): +async def test_POST_MultiDict(aiohttp_client) -> None: async def handler(request): data = await request.post() @@ -1134,7 +1178,7 @@ resp.close() -async def test_POST_DATA_DEFLATE(aiohttp_client): +async def test_POST_DATA_DEFLATE(aiohttp_client) -> None: async def handler(request): data = await request.post() @@ -1151,7 +1195,7 @@ resp.close() -async def test_POST_FILES(aiohttp_client, fname): +async def test_POST_FILES(aiohttp_client, fname) -> None: async def handler(request): data = await request.post() @@ -1174,7 +1218,7 @@ resp.close() -async def test_POST_FILES_DEFLATE(aiohttp_client, fname): +async def test_POST_FILES_DEFLATE(aiohttp_client, fname) -> None: async def handler(request): data = await request.post() @@ -1200,7 +1244,7 @@ resp.close() -async def test_POST_bytes(aiohttp_client): +async def test_POST_bytes(aiohttp_client) -> None: body = b'0' * 12345 async def handler(request): @@ -1217,7 +1261,7 @@ resp.close() -async def test_POST_bytes_too_large(aiohttp_client): +async def test_POST_bytes_too_large(aiohttp_client) -> None: body = b'0' * (2 ** 20 + 1) async def handler(request): @@ -1236,7 +1280,7 @@ resp.close() -async def test_POST_FILES_STR(aiohttp_client, fname): +async def test_POST_FILES_STR(aiohttp_client, fname) -> None: async def handler(request): data = await request.post() @@ -1256,7 +1300,7 @@ resp.close() -async def test_POST_FILES_STR_SIMPLE(aiohttp_client, fname): +async def test_POST_FILES_STR_SIMPLE(aiohttp_client, fname) -> None: async def handler(request): data = await request.read() @@ -1275,7 +1319,7 @@ resp.close() -async def test_POST_FILES_LIST(aiohttp_client, fname): +async def test_POST_FILES_LIST(aiohttp_client, fname) -> None: async def handler(request): data = await request.post() @@ -1295,7 +1339,7 @@ resp.close() -async def test_POST_FILES_CT(aiohttp_client, fname): +async def test_POST_FILES_CT(aiohttp_client, fname) -> None: async def handler(request): data = await request.post() @@ -1318,7 +1362,7 @@ resp.close() -async def test_POST_FILES_SINGLE(aiohttp_client, fname): +async def test_POST_FILES_SINGLE(aiohttp_client, fname) -> None: async def handler(request): data = await request.text() @@ -1344,7 +1388,8 @@ resp.close() -async def test_POST_FILES_SINGLE_content_disposition(aiohttp_client, fname): +async def test_POST_FILES_SINGLE_content_disposition( + aiohttp_client, fname) -> None: async def handler(request): data = await request.text() @@ -1372,7 +1417,7 @@ resp.close() -async def test_POST_FILES_SINGLE_BINARY(aiohttp_client, fname): +async def test_POST_FILES_SINGLE_BINARY(aiohttp_client, fname) -> None: async def handler(request): data = await request.read() @@ -1396,7 +1441,7 @@ resp.close() -async def test_POST_FILES_IO(aiohttp_client): +async def test_POST_FILES_IO(aiohttp_client) -> None: async def handler(request): data = await request.post() @@ -1415,7 +1460,7 @@ resp.close() -async def test_POST_FILES_IO_WITH_PARAMS(aiohttp_client): +async def test_POST_FILES_IO_WITH_PARAMS(aiohttp_client) -> None: async def handler(request): data = await request.post() @@ -1441,7 +1486,7 @@ resp.close() -async def test_POST_FILES_WITH_DATA(aiohttp_client, fname): +async def test_POST_FILES_WITH_DATA(aiohttp_client, fname) -> None: async def handler(request): data = await request.post() @@ -1465,7 +1510,7 @@ resp.close() -async def test_POST_STREAM_DATA(aiohttp_client, fname): +async def test_POST_STREAM_DATA(aiohttp_client, fname) -> None: async def handler(request): assert request.content_type == 'application/octet-stream' @@ -1499,7 +1544,7 @@ resp.close() -async def test_POST_STREAM_DATA_no_params(aiohttp_client, fname): +async def test_POST_STREAM_DATA_no_params(aiohttp_client, fname) -> None: async def handler(request): assert request.content_type == 'application/octet-stream' @@ -1533,7 +1578,7 @@ resp.close() -async def test_json(aiohttp_client): +async def test_json(aiohttp_client) -> None: async def handler(request): assert request.content_type == 'application/json' @@ -1554,7 +1599,7 @@ await client.post('/', data="some data", json={'some': 'data'}) -async def test_json_custom(aiohttp_client): +async def test_json_custom(aiohttp_client) -> None: async def handler(request): assert request.content_type == 'application/json' @@ -1583,7 +1628,7 @@ await client.post('/', data="some data", json={'some': 'data'}) -async def test_expect_continue(aiohttp_client): +async def test_expect_continue(aiohttp_client) -> None: expect_called = False async def handler(request): @@ -1608,7 +1653,7 @@ assert expect_called -async def test_encoding_deflate(aiohttp_client): +async def test_encoding_deflate(aiohttp_client) -> None: async def handler(request): resp = web.Response(text='text') @@ -1627,7 +1672,7 @@ resp.close() -async def test_encoding_deflate_nochunk(aiohttp_client): +async def test_encoding_deflate_nochunk(aiohttp_client) -> None: async def handler(request): resp = web.Response(text='text') @@ -1645,7 +1690,7 @@ resp.close() -async def test_encoding_gzip(aiohttp_client): +async def test_encoding_gzip(aiohttp_client) -> None: async def handler(request): resp = web.Response(text='text') @@ -1664,7 +1709,7 @@ resp.close() -async def test_encoding_gzip_write_by_chunks(aiohttp_client): +async def test_encoding_gzip_write_by_chunks(aiohttp_client) -> None: async def handler(request): resp = web.StreamResponse() @@ -1685,7 +1730,7 @@ resp.close() -async def test_encoding_gzip_nochunk(aiohttp_client): +async def test_encoding_gzip_nochunk(aiohttp_client) -> None: async def handler(request): resp = web.Response(text='text') @@ -1703,7 +1748,7 @@ resp.close() -async def test_bad_payload_compression(aiohttp_client): +async def test_bad_payload_compression(aiohttp_client) -> None: async def handler(request): resp = web.Response(text='text') @@ -1723,7 +1768,7 @@ resp.close() -async def test_bad_payload_chunked_encoding(aiohttp_client): +async def test_bad_payload_chunked_encoding(aiohttp_client) -> None: async def handler(request): resp = web.StreamResponse() @@ -1748,7 +1793,7 @@ resp.close() -async def test_bad_payload_content_length(aiohttp_client): +async def test_bad_payload_content_length(aiohttp_client) -> None: async def handler(request): resp = web.Response(text='text') @@ -1769,7 +1814,7 @@ resp.close() -async def test_payload_content_length_by_chunks(aiohttp_client): +async def test_payload_content_length_by_chunks(aiohttp_client) -> None: async def handler(request): resp = web.StreamResponse(headers={'content-length': '3'}) @@ -1789,7 +1834,7 @@ resp.close() -async def test_chunked(aiohttp_client): +async def test_chunked(aiohttp_client) -> None: async def handler(request): resp = web.Response(text='text') @@ -1808,7 +1853,7 @@ resp.close() -async def test_shortcuts(aiohttp_client): +async def test_shortcuts(aiohttp_client) -> None: async def handler(request): return web.Response(text=request.method) @@ -1836,7 +1881,7 @@ assert meth.upper() == content -async def test_cookies(aiohttp_client): +async def test_cookies(aiohttp_client) -> None: async def handler(request): assert request.cookies.keys() == {'test1', 'test3'} @@ -1857,7 +1902,34 @@ resp.close() -async def test_morsel_with_attributes(aiohttp_client): +async def test_cookies_per_request(aiohttp_client) -> None: + + async def handler(request): + assert request.cookies.keys() == {'test1', 'test3', 'test4', 'test6'} + assert request.cookies['test1'] == '123' + assert request.cookies['test3'] == '456' + assert request.cookies['test4'] == '789' + assert request.cookies['test6'] == 'abc' + return web.Response() + + c = http.cookies.Morsel() + c.set('test3', '456', '456') + + app = web.Application() + app.router.add_get('/', handler) + client = await aiohttp_client( + app, cookies={'test1': '123', 'test2': c}) + + rc = http.cookies.Morsel() + rc.set('test6', 'abc', 'abc') + + resp = await client.get( + '/', cookies={'test4': '789', 'test5': rc}) + assert 200 == resp.status + resp.close() + + +async def test_morsel_with_attributes(aiohttp_client) -> None: # A comment from original test: # # No cookie attribute should pass here @@ -1887,7 +1959,7 @@ resp.close() -async def test_set_cookies(aiohttp_client): +async def test_set_cookies(aiohttp_client) -> None: async def handler(request): ret = web.Response() @@ -1914,7 +1986,7 @@ mock.ANY) -async def test_request_conn_error(): +async def test_request_conn_error() -> None: client = aiohttp.ClientSession() with pytest.raises(aiohttp.ClientConnectionError): await client.get('http://0.0.0.0:1') @@ -1922,7 +1994,7 @@ @pytest.mark.xfail -async def test_broken_connection(aiohttp_client): +async def test_broken_connection(aiohttp_client) -> None: async def handler(request): request.transport.close() @@ -1936,7 +2008,7 @@ await client.get('/') -async def test_broken_connection_2(aiohttp_client): +async def test_broken_connection_2(aiohttp_client) -> None: async def handler(request): resp = web.StreamResponse(headers={'content-length': '1000'}) @@ -1955,7 +2027,7 @@ resp.close() -async def test_custom_headers(aiohttp_client): +async def test_custom_headers(aiohttp_client) -> None: async def handler(request): assert request.headers["x-api-key"] == "foo" @@ -1971,7 +2043,7 @@ assert resp.status == 200 -async def test_redirect_to_absolute_url(aiohttp_client): +async def test_redirect_to_absolute_url(aiohttp_client) -> None: async def handler(request): return web.Response(text=request.method) @@ -1989,7 +2061,7 @@ resp.close() -async def test_redirect_without_location_header(aiohttp_client): +async def test_redirect_without_location_header(aiohttp_client) -> None: body = b'redirect' async def handler_redirect(request): @@ -2004,7 +2076,7 @@ assert data == body -async def test_chunked_deprecated(aiohttp_client): +async def test_chunked_deprecated(aiohttp_client) -> None: async def handler_redirect(request): return web.Response(status=301) @@ -2017,7 +2089,7 @@ await client.post('/', chunked=1024) -async def test_raise_for_status(aiohttp_client): +async def test_raise_for_status(aiohttp_client) -> None: async def handler_redirect(request): raise web.HTTPBadRequest() @@ -2030,7 +2102,73 @@ await client.get('/') -async def test_invalid_idna(): +async def test_raise_for_status_per_request(aiohttp_client) -> None: + + async def handler_redirect(request): + raise web.HTTPBadRequest() + + app = web.Application() + app.router.add_route('GET', '/', handler_redirect) + client = await aiohttp_client(app) + + with pytest.raises(aiohttp.ClientResponseError): + await client.get('/', raise_for_status=True) + + +async def test_raise_for_status_disable_per_request(aiohttp_client) -> None: + + async def handler_redirect(request): + raise web.HTTPBadRequest() + + app = web.Application() + app.router.add_route('GET', '/', handler_redirect) + client = await aiohttp_client(app, raise_for_status=True) + + resp = await client.get('/', raise_for_status=False) + assert 400 == resp.status + resp.close() + + +async def test_request_raise_for_status_default(aiohttp_server) -> None: + async def handler(request): + raise web.HTTPBadRequest() + + app = web.Application() + app.router.add_get('/', handler) + server = await aiohttp_server(app) + + async with aiohttp.request('GET', server.make_url('/')) as resp: + assert resp.status == 400 + + +async def test_request_raise_for_status_disabled(aiohttp_server) -> None: + async def handler(request): + raise web.HTTPBadRequest() + + app = web.Application() + app.router.add_get('/', handler) + server = await aiohttp_server(app) + url = server.make_url('/') + + async with aiohttp.request('GET', url, raise_for_status=False) as resp: + assert resp.status == 400 + + +async def test_request_raise_for_status_enabled(aiohttp_server) -> None: + async def handler(request): + raise web.HTTPBadRequest() + + app = web.Application() + app.router.add_get('/', handler) + server = await aiohttp_server(app) + url = server.make_url('/') + + with pytest.raises(aiohttp.ClientResponseError): + async with aiohttp.request('GET', url, raise_for_status=True): + assert False, "never executed" # pragma: no cover + + +async def test_invalid_idna() -> None: session = aiohttp.ClientSession() try: with pytest.raises(aiohttp.InvalidURL): @@ -2039,7 +2177,7 @@ await session.close() -async def test_creds_in_auth_and_url(): +async def test_creds_in_auth_and_url() -> None: session = aiohttp.ClientSession() try: with pytest.raises(ValueError): @@ -2049,7 +2187,7 @@ await session.close() -async def test_drop_auth_on_redirect_to_other_host(aiohttp_server): +async def test_drop_auth_on_redirect_to_other_host(aiohttp_server) -> None: async def srv1(request): assert request.host == 'host1.com' @@ -2094,7 +2232,7 @@ assert resp.status == 200 -async def test_async_with_session(): +async def test_async_with_session() -> None: with pytest.warns(None) as cm: async with aiohttp.ClientSession() as session: pass @@ -2103,7 +2241,7 @@ assert session.closed -async def test_session_close_awaitable(): +async def test_session_close_awaitable() -> None: session = aiohttp.ClientSession() with pytest.warns(None) as cm: await session.close() @@ -2112,7 +2250,7 @@ assert session.closed -async def test_close_run_until_complete_not_deprecated(): +async def test_close_run_until_complete_not_deprecated() -> None: session = aiohttp.ClientSession() with pytest.warns(None) as cm: @@ -2121,7 +2259,7 @@ assert len(cm.list) == 0 -async def test_close_resp_on_error_async_with_session(aiohttp_server): +async def test_close_resp_on_error_async_with_session(aiohttp_server) -> None: async def handler(request): resp = web.StreamResponse(headers={'content-length': '100'}) await resp.prepare(request) @@ -2141,7 +2279,7 @@ assert len(session._connector._conns) == 0 -async def test_release_resp_on_normal_exit_from_cm(aiohttp_server): +async def test_release_resp_on_normal_exit_from_cm(aiohttp_server) -> None: async def handler(request): return web.Response() @@ -2156,7 +2294,7 @@ assert len(session._connector._conns) == 1 -async def test_non_close_detached_session_on_error_cm(aiohttp_server): +async def test_non_close_detached_session_on_error_cm(aiohttp_server) -> None: async def handler(request): resp = web.StreamResponse(headers={'content-length': '100'}) await resp.prepare(request) @@ -2177,7 +2315,7 @@ assert not session.closed -async def test_close_detached_session_on_non_existing_addr(): +async def test_close_detached_session_on_non_existing_addr() -> None: class FakeResolver(AbstractResolver): async def resolve(host, port=0, family=socket.AF_INET): return {} @@ -2198,7 +2336,7 @@ assert session.closed -async def test_aiohttp_request_context_manager(aiohttp_server): +async def test_aiohttp_request_context_manager(aiohttp_server) -> None: async def handler(request): return web.Response() @@ -2211,14 +2349,14 @@ assert resp.status == 200 -async def test_aiohttp_request_ctx_manager_not_found(): +async def test_aiohttp_request_ctx_manager_not_found() -> None: with pytest.raises(aiohttp.ClientConnectionError): async with aiohttp.request('GET', 'http://wrong-dns-name.com'): assert False, "never executed" # pragma: no cover -async def test_aiohttp_request_coroutine(aiohttp_server): +async def test_aiohttp_request_coroutine(aiohttp_server) -> None: async def handler(request): return web.Response() @@ -2231,7 +2369,7 @@ @asyncio.coroutine -def test_yield_from_in_session_request(aiohttp_client): +def test_yield_from_in_session_request(aiohttp_client) -> None: # a test for backward compatibility with yield from syntax async def handler(request): return web.Response() @@ -2245,7 +2383,7 @@ @asyncio.coroutine -def test_close_context_manager(aiohttp_client): +def test_close_context_manager(aiohttp_client) -> None: # a test for backward compatibility with yield from syntax async def handler(request): return web.Response() @@ -2259,7 +2397,7 @@ assert not ctx._coro.cr_running -async def test_session_auth(aiohttp_client): +async def test_session_auth(aiohttp_client) -> None: async def handler(request): return web.json_response({'headers': dict(request.headers)}) @@ -2274,7 +2412,7 @@ assert content['headers']["Authorization"] == "Basic bG9naW46cGFzcw==" -async def test_session_auth_override(aiohttp_client): +async def test_session_auth_override(aiohttp_client) -> None: async def handler(request): return web.json_response({'headers': dict(request.headers)}) @@ -2290,7 +2428,7 @@ assert val == "Basic b3RoZXJfbG9naW46cGFzcw==" -async def test_session_auth_header_conflict(aiohttp_client): +async def test_session_auth_header_conflict(aiohttp_client) -> None: async def handler(request): return web.Response() @@ -2303,7 +2441,7 @@ await client.get('/', headers=headers) -async def test_session_headers(aiohttp_client): +async def test_session_headers(aiohttp_client) -> None: async def handler(request): return web.json_response({'headers': dict(request.headers)}) @@ -2318,7 +2456,7 @@ assert content['headers']["X-Real-IP"] == "192.168.0.1" -async def test_session_headers_merge(aiohttp_client): +async def test_session_headers_merge(aiohttp_client) -> None: async def handler(request): return web.json_response({'headers': dict(request.headers)}) @@ -2336,7 +2474,7 @@ assert content['headers']["X-Sent-By"] == "aiohttp" -async def test_multidict_headers(aiohttp_client): +async def test_multidict_headers(aiohttp_client) -> None: async def handler(request): assert await request.read() == data return web.Response() @@ -2354,7 +2492,7 @@ assert r.status == 200 -async def test_request_conn_closed(aiohttp_client): +async def test_request_conn_closed(aiohttp_client) -> None: async def handler(request): request.transport.close() return web.Response() @@ -2368,7 +2506,7 @@ await resp.read() -async def test_dont_close_explicit_connector(aiohttp_client): +async def test_dont_close_explicit_connector(aiohttp_client) -> None: async def handler(request): return web.Response() @@ -2382,7 +2520,8 @@ assert 1 == len(client.session.connector._conns) -async def test_server_close_keepalive_connection(loop): +async def test_server_close_keepalive_connection() -> None: + loop = asyncio.get_event_loop() class Proto(asyncio.Protocol): @@ -2423,7 +2562,8 @@ await server.wait_closed() -async def test_handle_keepalive_on_closed_connection(loop): +async def test_handle_keepalive_on_closed_connection() -> None: + loop = asyncio.get_event_loop() class Proto(asyncio.Protocol): @@ -2468,7 +2608,7 @@ await server.wait_closed() -async def test_error_in_performing_request(loop, ssl_ctx, +async def test_error_in_performing_request(ssl_ctx, aiohttp_client, aiohttp_server): async def handler(request): return web.Response() @@ -2477,6 +2617,7 @@ # skip log messages about destroyed but pending tasks pass + loop = asyncio.get_event_loop() loop.set_exception_handler(exception_handler) app = web.Application() @@ -2495,7 +2636,8 @@ await client.get('/') -async def test_await_after_cancelling(loop, aiohttp_client): +async def test_await_after_cancelling(aiohttp_client) -> None: + loop = asyncio.get_event_loop() async def handler(request): return web.Response() @@ -2528,7 +2670,7 @@ await asyncio.gather(fetch1(), fetch2(), canceller()) -async def test_async_payload_generator(aiohttp_client): +async def test_async_payload_generator(aiohttp_client) -> None: async def handler(request): data = await request.read() @@ -2547,3 +2689,86 @@ resp = await client.post('/', data=gen()) assert resp.status == 200 + + +async def test_read_from_closed_response(aiohttp_client) -> None: + async def handler(request): + return web.Response(body=b'data') + + app = web.Application() + app.add_routes([web.get('/', handler)]) + + client = await aiohttp_client(app) + + async with client.get('/') as resp: + assert resp.status == 200 + + with pytest.raises(aiohttp.ClientConnectionError): + await resp.read() + + +async def test_read_from_closed_response2(aiohttp_client) -> None: + async def handler(request): + return web.Response(body=b'data') + + app = web.Application() + app.add_routes([web.get('/', handler)]) + + client = await aiohttp_client(app) + + async with client.get('/') as resp: + assert resp.status == 200 + await resp.read() + + with pytest.raises(aiohttp.ClientConnectionError): + await resp.read() + + +async def test_read_from_closed_content(aiohttp_client) -> None: + async def handler(request): + return web.Response(body=b'data') + + app = web.Application() + app.add_routes([web.get('/', handler)]) + + client = await aiohttp_client(app) + + async with client.get('/') as resp: + assert resp.status == 200 + + with pytest.raises(aiohttp.ClientConnectionError): + await resp.content.readline() + + +async def test_read_timeout(aiohttp_client) -> None: + async def handler(request): + await asyncio.sleep(5) + return web.Response() + + app = web.Application() + app.add_routes([web.get('/', handler)]) + + timeout = aiohttp.ClientTimeout(sock_read=0.1) + client = await aiohttp_client(app, timeout=timeout) + + with pytest.raises(aiohttp.ServerTimeoutError): + await client.get('/') + + +async def test_read_timeout_on_prepared_response(aiohttp_client) -> None: + async def handler(request): + resp = aiohttp.web.StreamResponse() + await resp.prepare(request) + await asyncio.sleep(5) + await resp.drain() + return resp + + app = web.Application() + app.add_routes([web.get('/', handler)]) + + timeout = aiohttp.ClientTimeout(sock_read=0.1) + client = await aiohttp_client(app, timeout=timeout) + + with pytest.raises(aiohttp.ServerTimeoutError): + async with await client.get('/') as resp: + await resp.read() diff -Nru python-aiohttp-3.1.3/tests/test_client_proto.py python-aiohttp-3.5.1/tests/test_client_proto.py --- python-aiohttp-3.1.3/tests/test_client_proto.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_client_proto.py 2018-12-24 20:58:54.000000000 +0000 @@ -9,7 +9,7 @@ from aiohttp.helpers import TimerNoop -async def test_oserror(loop): +async def test_oserror(loop) -> None: proto = ResponseHandler(loop=loop) transport = mock.Mock() proto.connection_made(transport) @@ -19,8 +19,10 @@ assert isinstance(proto.exception(), ClientOSError) -async def test_pause_resume_on_error(loop): +async def test_pause_resume_on_error(loop) -> None: proto = ResponseHandler(loop=loop) + transport = mock.Mock() + proto.connection_made(transport) proto.pause_reading() assert proto._reading_paused @@ -29,11 +31,11 @@ assert not proto._reading_paused -async def test_client_proto_bad_message(loop): +async def test_client_proto_bad_message(loop) -> None: proto = ResponseHandler(loop=loop) transport = mock.Mock() proto.connection_made(transport) - proto.set_response_params(read_until_eof=True) + proto.set_response_params() proto.data_received(b'HTTP\r\n\r\n') assert proto.should_close @@ -41,7 +43,7 @@ assert isinstance(proto.exception(), http.HttpProcessingError) -async def test_uncompleted_message(loop): +async def test_uncompleted_message(loop) -> None: proto = ResponseHandler(loop=loop) transport = mock.Mock() proto.connection_made(transport) @@ -57,7 +59,7 @@ assert dict(exc.message.headers) == {'Location': 'http://python.org/'} -async def test_client_protocol_readuntil_eof(loop): +async def test_client_protocol_readuntil_eof(loop) -> None: proto = ResponseHandler(loop=loop) transport = mock.Mock() proto.connection_made(transport) @@ -71,11 +73,11 @@ continue100=None, timer=TimerNoop(), request_info=mock.Mock(), - auto_decompress=True, traces=[], loop=loop, session=mock.Mock()) - await response.start(conn, read_until_eof=True) + proto.set_response_params(read_until_eof=True) + await response.start(conn) assert not response.content.is_eof() @@ -91,8 +93,40 @@ assert response.content.is_eof() -async def test_empty_data(loop): +async def test_empty_data(loop) -> None: proto = ResponseHandler(loop=loop) proto.data_received(b'') # do nothing + + +async def test_schedule_timeout(loop) -> None: + proto = ResponseHandler(loop=loop) + proto.set_response_params(read_timeout=1) + assert proto._read_timeout_handle is not None + + +async def test_drop_timeout(loop) -> None: + proto = ResponseHandler(loop=loop) + proto.set_response_params(read_timeout=1) + assert proto._read_timeout_handle is not None + proto._drop_timeout() + assert proto._read_timeout_handle is None + + +async def test_reschedule_timeout(loop) -> None: + proto = ResponseHandler(loop=loop) + proto.set_response_params(read_timeout=1) + assert proto._read_timeout_handle is not None + h = proto._read_timeout_handle + proto._reschedule_timeout() + assert proto._read_timeout_handle is not None + assert proto._read_timeout_handle is not h + + +async def test_eof_received(loop) -> None: + proto = ResponseHandler(loop=loop) + proto.set_response_params(read_timeout=1) + assert proto._read_timeout_handle is not None + proto.eof_received() + assert proto._read_timeout_handle is None diff -Nru python-aiohttp-3.1.3/tests/test_client_request.py python-aiohttp-3.5.1/tests/test_client_request.py --- python-aiohttp-3.1.3/tests/test_client_request.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_client_request.py 2018-12-24 20:58:54.000000000 +0000 @@ -41,8 +41,9 @@ @pytest.fixture -def protocol(loop): +def protocol(loop, transport): protocol = mock.Mock() + protocol.transport = transport protocol._drain_helper.return_value = loop.create_future() protocol._drain_helper.return_value.set_result(None) return protocol @@ -73,50 +74,58 @@ ) -def test_method1(make_request): +def test_method1(make_request) -> None: req = make_request('get', 'http://python.org/') assert req.method == 'GET' -def test_method2(make_request): +def test_method2(make_request) -> None: req = make_request('head', 'http://python.org/') assert req.method == 'HEAD' -def test_method3(make_request): +def test_method3(make_request) -> None: req = make_request('HEAD', 'http://python.org/') assert req.method == 'HEAD' -def test_version_1_0(make_request): +def test_version_1_0(make_request) -> None: req = make_request('get', 'http://python.org/', version='1.0') assert req.version == (1, 0) -def test_version_default(make_request): +def test_version_default(make_request) -> None: req = make_request('get', 'http://python.org/') assert req.version == (1, 1) -def test_request_info(make_request): +def test_request_info(make_request) -> None: req = make_request('get', 'http://python.org/') assert req.request_info == aiohttp.RequestInfo(URL('http://python.org/'), 'GET', req.headers) -def test_version_err(make_request): +def test_request_info_with_fragment(make_request) -> None: + req = make_request('get', 'http://python.org/#urlfragment') + assert req.request_info == aiohttp.RequestInfo( + URL('http://python.org/'), + 'GET', req.headers, + URL('http://python.org/#urlfragment')) + + +def test_version_err(make_request) -> None: with pytest.raises(ValueError): make_request('get', 'http://python.org/', version='1.c') -def test_https_proxy(make_request): +def test_https_proxy(make_request) -> None: with pytest.raises(ValueError): make_request( 'get', 'http://python.org/', proxy=URL('https://proxy.org')) -def test_keep_alive(make_request): +def test_keep_alive(make_request) -> None: req = make_request('get', 'http://python.org/', version=(0, 9)) assert not req.keep_alive() @@ -135,123 +144,148 @@ assert not req.keep_alive() -def test_host_port_default_http(make_request): +def test_host_port_default_http(make_request) -> None: req = make_request('get', 'http://python.org/') assert req.host == 'python.org' assert req.port == 80 assert not req.ssl -def test_host_port_default_https(make_request): +def test_host_port_default_https(make_request) -> None: req = make_request('get', 'https://python.org/') assert req.host == 'python.org' assert req.port == 443 assert req.is_ssl() -def test_host_port_nondefault_http(make_request): +def test_host_port_nondefault_http(make_request) -> None: req = make_request('get', 'http://python.org:960/') assert req.host == 'python.org' assert req.port == 960 assert not req.is_ssl() -def test_host_port_nondefault_https(make_request): +def test_host_port_nondefault_https(make_request) -> None: req = make_request('get', 'https://python.org:960/') assert req.host == 'python.org' assert req.port == 960 assert req.is_ssl() -def test_host_port_default_ws(make_request): +def test_host_port_default_ws(make_request) -> None: req = make_request('get', 'ws://python.org/') assert req.host == 'python.org' assert req.port == 80 assert not req.is_ssl() -def test_host_port_default_wss(make_request): +def test_host_port_default_wss(make_request) -> None: req = make_request('get', 'wss://python.org/') assert req.host == 'python.org' assert req.port == 443 assert req.is_ssl() -def test_host_port_nondefault_ws(make_request): +def test_host_port_nondefault_ws(make_request) -> None: req = make_request('get', 'ws://python.org:960/') assert req.host == 'python.org' assert req.port == 960 assert not req.is_ssl() -def test_host_port_nondefault_wss(make_request): +def test_host_port_nondefault_wss(make_request) -> None: req = make_request('get', 'wss://python.org:960/') assert req.host == 'python.org' assert req.port == 960 assert req.is_ssl() -def test_host_port_err(make_request): +def test_host_port_err(make_request) -> None: with pytest.raises(ValueError): make_request('get', 'http://python.org:123e/') -def test_hostname_err(make_request): +def test_hostname_err(make_request) -> None: with pytest.raises(ValueError): make_request('get', 'http://:8080/') -def test_host_header_host_without_port(make_request): +def test_host_header_host_first(make_request) -> None: + req = make_request('get', 'http://python.org/') + assert list(req.headers)[0] == 'Host' + + +def test_host_header_host_without_port(make_request) -> None: req = make_request('get', 'http://python.org/') assert req.headers['HOST'] == 'python.org' -def test_host_header_host_with_default_port(make_request): +def test_host_header_host_with_default_port(make_request) -> None: req = make_request('get', 'http://python.org:80/') assert req.headers['HOST'] == 'python.org' -def test_host_header_host_with_nondefault_port(make_request): +def test_host_header_host_with_nondefault_port(make_request) -> None: req = make_request('get', 'http://python.org:99/') assert req.headers['HOST'] == 'python.org:99' -def test_host_header_host_idna_encode(make_request): +def test_host_header_host_idna_encode(make_request) -> None: req = make_request('get', 'http://xn--9caa.com') assert req.headers['HOST'] == 'xn--9caa.com' -def test_host_header_host_unicode(make_request): +def test_host_header_host_unicode(make_request) -> None: req = make_request('get', 'http://éé.com') assert req.headers['HOST'] == 'xn--9caa.com' -def test_host_header_explicit_host(make_request): +def test_host_header_explicit_host(make_request) -> None: req = make_request('get', 'http://python.org/', headers={'host': 'example.com'}) assert req.headers['HOST'] == 'example.com' -def test_host_header_explicit_host_with_port(make_request): +def test_host_header_explicit_host_with_port(make_request) -> None: req = make_request('get', 'http://python.org/', headers={'host': 'example.com:99'}) assert req.headers['HOST'] == 'example.com:99' -def test_default_loop(loop): +def test_host_header_ipv4(make_request) -> None: + req = make_request('get', 'http://127.0.0.2') + assert req.headers['HOST'] == '127.0.0.2' + + +def test_host_header_ipv6(make_request) -> None: + req = make_request('get', 'http://[::2]') + assert req.headers['HOST'] == '[::2]' + + +def test_host_header_ipv4_with_port(make_request) -> None: + req = make_request('get', 'http://127.0.0.2:99') + assert req.headers['HOST'] == '127.0.0.2:99' + + +def test_host_header_ipv6_with_port(make_request) -> None: + req = make_request('get', 'http://[::2]:99') + assert req.headers['HOST'] == '[::2]:99' + + +def test_default_loop(loop) -> None: asyncio.set_event_loop(loop) req = ClientRequest('get', URL('http://python.org/')) assert req.loop is loop -def test_default_headers_useragent(make_request): +def test_default_headers_useragent(make_request) -> None: req = make_request('get', 'http://python.org/') assert 'SERVER' not in req.headers assert 'USER-AGENT' in req.headers -def test_default_headers_useragent_custom(make_request): +def test_default_headers_useragent_custom(make_request) -> None: req = make_request('get', 'http://python.org/', headers={'user-agent': 'my custom agent'}) @@ -259,14 +293,14 @@ assert 'my custom agent' == req.headers['User-Agent'] -def test_skip_default_useragent_header(make_request): +def test_skip_default_useragent_header(make_request) -> None: req = make_request('get', 'http://python.org/', skip_auto_headers=set([istr('user-agent')])) assert 'User-Agent' not in req.headers -def test_headers(make_request): +def test_headers(make_request) -> None: req = make_request('post', 'http://python.org/', headers={'Content-Type': 'text/plain'}) @@ -275,85 +309,85 @@ assert req.headers['ACCEPT-ENCODING'] == 'gzip, deflate' -def test_headers_list(make_request): +def test_headers_list(make_request) -> None: req = make_request('post', 'http://python.org/', headers=[('Content-Type', 'text/plain')]) assert 'CONTENT-TYPE' in req.headers assert req.headers['CONTENT-TYPE'] == 'text/plain' -def test_headers_default(make_request): +def test_headers_default(make_request) -> None: req = make_request('get', 'http://python.org/', headers={'ACCEPT-ENCODING': 'deflate'}) assert req.headers['ACCEPT-ENCODING'] == 'deflate' -def test_invalid_url(make_request): +def test_invalid_url(make_request) -> None: with pytest.raises(aiohttp.InvalidURL): make_request('get', 'hiwpefhipowhefopw') -def test_no_path(make_request): +def test_no_path(make_request) -> None: req = make_request('get', 'http://python.org') assert '/' == req.url.path -def test_ipv6_default_http_port(make_request): +def test_ipv6_default_http_port(make_request) -> None: req = make_request('get', 'http://[2001:db8::1]/') assert req.host == '2001:db8::1' assert req.port == 80 assert not req.ssl -def test_ipv6_default_https_port(make_request): +def test_ipv6_default_https_port(make_request) -> None: req = make_request('get', 'https://[2001:db8::1]/') assert req.host == '2001:db8::1' assert req.port == 443 assert req.is_ssl() -def test_ipv6_nondefault_http_port(make_request): +def test_ipv6_nondefault_http_port(make_request) -> None: req = make_request('get', 'http://[2001:db8::1]:960/') assert req.host == '2001:db8::1' assert req.port == 960 assert not req.is_ssl() -def test_ipv6_nondefault_https_port(make_request): +def test_ipv6_nondefault_https_port(make_request) -> None: req = make_request('get', 'https://[2001:db8::1]:960/') assert req.host == '2001:db8::1' assert req.port == 960 assert req.is_ssl() -def test_basic_auth(make_request): +def test_basic_auth(make_request) -> None: req = make_request('get', 'http://python.org', auth=aiohttp.BasicAuth('nkim', '1234')) assert 'AUTHORIZATION' in req.headers assert 'Basic bmtpbToxMjM0' == req.headers['AUTHORIZATION'] -def test_basic_auth_utf8(make_request): +def test_basic_auth_utf8(make_request) -> None: req = make_request('get', 'http://python.org', auth=aiohttp.BasicAuth('nkim', 'секрет', 'utf-8')) assert 'AUTHORIZATION' in req.headers assert 'Basic bmtpbTrRgdC10LrRgNC10YI=' == req.headers['AUTHORIZATION'] -def test_basic_auth_tuple_forbidden(make_request): +def test_basic_auth_tuple_forbidden(make_request) -> None: with pytest.raises(TypeError): make_request('get', 'http://python.org', auth=('nkim', '1234')) -def test_basic_auth_from_url(make_request): +def test_basic_auth_from_url(make_request) -> None: req = make_request('get', 'http://nkim:1234@python.org') assert 'AUTHORIZATION' in req.headers assert 'Basic bmtpbToxMjM0' == req.headers['AUTHORIZATION'] assert 'python.org' == req.host -def test_basic_auth_from_url_overriden(make_request): +def test_basic_auth_from_url_overridden(make_request) -> None: req = make_request('get', 'http://garbage@python.org', auth=aiohttp.BasicAuth('nkim', '1234')) assert 'AUTHORIZATION' in req.headers @@ -361,49 +395,49 @@ assert 'python.org' == req.host -def test_path_is_not_double_encoded1(make_request): +def test_path_is_not_double_encoded1(make_request) -> None: req = make_request('get', "http://0.0.0.0/get/test case") assert req.url.raw_path == "/get/test%20case" -def test_path_is_not_double_encoded2(make_request): +def test_path_is_not_double_encoded2(make_request) -> None: req = make_request('get', "http://0.0.0.0/get/test%2fcase") assert req.url.raw_path == "/get/test%2Fcase" -def test_path_is_not_double_encoded3(make_request): +def test_path_is_not_double_encoded3(make_request) -> None: req = make_request('get', "http://0.0.0.0/get/test%20case") assert req.url.raw_path == "/get/test%20case" -def test_path_safe_chars_preserved(make_request): +def test_path_safe_chars_preserved(make_request) -> None: req = make_request('get', "http://0.0.0.0/get/:=+/%2B/") assert req.url.path == "/get/:=+/+/" -def test_params_are_added_before_fragment1(make_request): +def test_params_are_added_before_fragment1(make_request) -> None: req = make_request('GET', "http://example.com/path#fragment", params={"a": "b"}) assert str(req.url) == "http://example.com/path?a=b" -def test_params_are_added_before_fragment2(make_request): +def test_params_are_added_before_fragment2(make_request) -> None: req = make_request('GET', "http://example.com/path?key=value#fragment", params={"a": "b"}) assert str(req.url) == "http://example.com/path?key=value&a=b" -def test_path_not_contain_fragment1(make_request): +def test_path_not_contain_fragment1(make_request) -> None: req = make_request('GET', "http://example.com/path#fragment") assert req.url.path == "/path" -def test_path_not_contain_fragment2(make_request): +def test_path_not_contain_fragment2(make_request) -> None: req = make_request('GET', "http://example.com/path?key=value#fragment") assert str(req.url) == "http://example.com/path?key=value" -def test_cookies(make_request): +def test_cookies(make_request) -> None: req = make_request('get', 'http://test.com/path', cookies={'cookie1': 'val1'}) @@ -411,7 +445,7 @@ assert 'cookie1=val1' == req.headers['COOKIE'] -def test_cookies_merge_with_headers(make_request): +def test_cookies_merge_with_headers(make_request) -> None: req = make_request('get', 'http://test.com/path', headers={'cookie': 'cookie1=val1'}, cookies={'cookie2': 'val2'}) @@ -419,25 +453,25 @@ assert 'cookie1=val1; cookie2=val2' == req.headers['COOKIE'] -def test_unicode_get1(make_request): +def test_unicode_get1(make_request) -> None: req = make_request('get', 'http://python.org', params={'foo': 'f\xf8\xf8'}) assert 'http://python.org/?foo=f%C3%B8%C3%B8' == str(req.url) -def test_unicode_get2(make_request): +def test_unicode_get2(make_request) -> None: req = make_request('', 'http://python.org', params={'f\xf8\xf8': 'f\xf8\xf8'}) assert 'http://python.org/?f%C3%B8%C3%B8=f%C3%B8%C3%B8' == str(req.url) -def test_unicode_get3(make_request): +def test_unicode_get3(make_request) -> None: req = make_request('', 'http://python.org', params={'foo': 'foo'}) assert 'http://python.org/?foo=foo' == str(req.url) -def test_unicode_get4(make_request): +def test_unicode_get4(make_request) -> None: def join(*suffix): return urllib.parse.urljoin('http://python.org/', '/'.join(suffix)) @@ -445,7 +479,7 @@ assert 'http://python.org/%C3%B8?foo=foo' == str(req.url) -def test_query_multivalued_param(make_request): +def test_query_multivalued_param(make_request) -> None: for meth in ClientRequest.ALL_METHODS: req = make_request( meth, 'http://python.org', @@ -454,38 +488,38 @@ assert str(req.url) == 'http://python.org/?test=foo&test=baz' -def test_query_str_param(make_request): +def test_query_str_param(make_request) -> None: for meth in ClientRequest.ALL_METHODS: req = make_request(meth, 'http://python.org', params='test=foo') assert str(req.url) == 'http://python.org/?test=foo' -def test_query_bytes_param_raises(make_request): +def test_query_bytes_param_raises(make_request) -> None: for meth in ClientRequest.ALL_METHODS: with pytest.raises(TypeError): make_request(meth, 'http://python.org', params=b'test=foo') -def test_query_str_param_is_not_encoded(make_request): +def test_query_str_param_is_not_encoded(make_request) -> None: for meth in ClientRequest.ALL_METHODS: req = make_request(meth, 'http://python.org', params='test=f+oo') assert str(req.url) == 'http://python.org/?test=f+oo' -def test_params_update_path_and_url(make_request): +def test_params_update_path_and_url(make_request) -> None: req = make_request('get', 'http://python.org', params=(('test', 'foo'), ('test', 'baz'))) assert str(req.url) == 'http://python.org/?test=foo&test=baz' -def test_params_empty_path_and_url(make_request): +def test_params_empty_path_and_url(make_request) -> None: req_empty = make_request('get', 'http://python.org', params={}) assert str(req_empty.url) == 'http://python.org' req_none = make_request('get', 'http://python.org') assert str(req_none.url) == 'http://python.org' -def test_gen_netloc_all(make_request): +def test_gen_netloc_all(make_request) -> None: req = make_request('get', 'https://aiohttp:pwpwpw@' + '12345678901234567890123456789' + @@ -494,7 +528,7 @@ '012345678901234567890:8080' -def test_gen_netloc_no_port(make_request): +def test_gen_netloc_no_port(make_request) -> None: req = make_request('get', 'https://aiohttp:pwpwpw@' + '12345678901234567890123456789' + @@ -503,7 +537,7 @@ '012345678901234567890' -async def test_connection_header(loop, conn): +async def test_connection_header(loop, conn) -> None: req = ClientRequest('get', URL('http://python.org'), loop=loop) req.keep_alive = mock.Mock() req.headers.clear() @@ -526,7 +560,7 @@ assert req.headers.get('CONNECTION') == 'close' -async def test_no_content_length(loop, conn): +async def test_no_content_length(loop, conn) -> None: req = ClientRequest('get', URL('http://python.org'), loop=loop) resp = await req.send(conn) assert req.headers.get('CONTENT-LENGTH') is None @@ -534,7 +568,7 @@ resp.close() -async def test_no_content_length_head(loop, conn): +async def test_no_content_length_head(loop, conn) -> None: req = ClientRequest('head', URL('http://python.org'), loop=loop) resp = await req.send(conn) assert req.headers.get('CONTENT-LENGTH') is None @@ -542,14 +576,14 @@ resp.close() -async def test_content_type_auto_header_get(loop, conn): +async def test_content_type_auto_header_get(loop, conn) -> None: req = ClientRequest('get', URL('http://python.org'), loop=loop) resp = await req.send(conn) assert 'CONTENT-TYPE' not in req.headers resp.close() -async def test_content_type_auto_header_form(loop, conn): +async def test_content_type_auto_header_form(loop, conn) -> None: req = ClientRequest('post', URL('http://python.org'), data={'hey': 'you'}, loop=loop) resp = await req.send(conn) @@ -558,7 +592,7 @@ resp.close() -async def test_content_type_auto_header_bytes(loop, conn): +async def test_content_type_auto_header_bytes(loop, conn) -> None: req = ClientRequest('post', URL('http://python.org'), data=b'hey you', loop=loop) resp = await req.send(conn) @@ -566,7 +600,7 @@ resp.close() -async def test_content_type_skip_auto_header_bytes(loop, conn): +async def test_content_type_skip_auto_header_bytes(loop, conn) -> None: req = ClientRequest('post', URL('http://python.org'), data=b'hey you', skip_auto_headers={'Content-Type'}, loop=loop) @@ -575,7 +609,7 @@ resp.close() -async def test_content_type_skip_auto_header_form(loop, conn): +async def test_content_type_skip_auto_header_form(loop, conn) -> None: req = ClientRequest('post', URL('http://python.org'), data={'hey': 'you'}, loop=loop, skip_auto_headers={'Content-Type'}) @@ -584,7 +618,8 @@ resp.close() -async def test_content_type_auto_header_content_length_no_skip(loop, conn): +async def test_content_type_auto_header_content_length_no_skip(loop, + conn) -> None: req = ClientRequest('post', URL('http://python.org'), data=io.BytesIO(b'hey'), skip_auto_headers={'Content-Length'}, @@ -594,7 +629,7 @@ resp.close() -async def test_urlencoded_formdata_charset(loop, conn): +async def test_urlencoded_formdata_charset(loop, conn) -> None: req = ClientRequest( 'post', URL('http://python.org'), data=aiohttp.FormData({'hey': 'you'}, charset='koi8-r'), loop=loop) @@ -603,7 +638,7 @@ req.headers.get('CONTENT-TYPE') -async def test_post_data(loop, conn): +async def test_post_data(loop, conn) -> None: for meth in ClientRequest.POST_METHODS: req = ClientRequest( meth, URL('http://python.org/'), @@ -617,7 +652,7 @@ resp.close() -async def test_pass_falsy_data(loop): +async def test_pass_falsy_data(loop) -> None: with mock.patch( 'aiohttp.client_reqrep.ClientRequest.update_body_from_data'): req = ClientRequest( @@ -627,7 +662,7 @@ await req.close() -async def test_pass_falsy_data_file(loop, tmpdir): +async def test_pass_falsy_data_file(loop, tmpdir) -> None: testfile = tmpdir.join('tmpfile').open('w+b') testfile.write(b'data') testfile.seek(0) @@ -642,7 +677,7 @@ # Elasticsearch API requires to send request body with GET-requests -async def test_get_with_data(loop): +async def test_get_with_data(loop) -> None: for meth in ClientRequest.GET_METHODS: req = ClientRequest( meth, URL('http://python.org/'), data={'life': '42'}, @@ -652,7 +687,7 @@ await req.close() -async def test_bytes_data(loop, conn): +async def test_bytes_data(loop, conn) -> None: for meth in ClientRequest.POST_METHODS: req = ClientRequest( meth, URL('http://python.org/'), @@ -666,7 +701,7 @@ resp.close() -async def test_content_encoding(loop, conn): +async def test_content_encoding(loop, conn) -> None: req = ClientRequest('post', URL('http://python.org/'), data='foo', compress='deflate', loop=loop) with mock.patch('aiohttp.client_reqrep.StreamWriter') as m_writer: @@ -680,7 +715,8 @@ resp.close() -async def test_content_encoding_dont_set_headers_if_no_body(loop, conn): +async def test_content_encoding_dont_set_headers_if_no_body(loop, + conn) -> None: req = ClientRequest('post', URL('http://python.org/'), compress='deflate', loop=loop) with mock.patch('aiohttp.client_reqrep.http'): @@ -691,7 +727,7 @@ resp.close() -async def test_content_encoding_header(loop, conn): +async def test_content_encoding_header(loop, conn) -> None: req = ClientRequest( 'post', URL('http://python.org/'), data='foo', headers={'Content-Encoding': 'deflate'}, loop=loop) @@ -705,14 +741,14 @@ resp.close() -async def test_compress_and_content_encoding(loop, conn): +async def test_compress_and_content_encoding(loop, conn) -> None: with pytest.raises(ValueError): ClientRequest('post', URL('http://python.org/'), data='foo', headers={'content-encoding': 'deflate'}, compress='deflate', loop=loop) -async def test_chunked(loop, conn): +async def test_chunked(loop, conn) -> None: req = ClientRequest( 'post', URL('http://python.org/'), headers={'TRANSFER-ENCODING': 'gzip'}, loop=loop) @@ -722,7 +758,7 @@ resp.close() -async def test_chunked2(loop, conn): +async def test_chunked2(loop, conn) -> None: req = ClientRequest( 'post', URL('http://python.org/'), headers={'Transfer-encoding': 'chunked'}, loop=loop) @@ -732,7 +768,7 @@ resp.close() -async def test_chunked_explicit(loop, conn): +async def test_chunked_explicit(loop, conn) -> None: req = ClientRequest( 'post', URL('http://python.org/'), chunked=True, loop=loop) with mock.patch('aiohttp.client_reqrep.StreamWriter') as m_writer: @@ -745,21 +781,21 @@ resp.close() -async def test_chunked_length(loop, conn): +async def test_chunked_length(loop, conn) -> None: with pytest.raises(ValueError): ClientRequest( 'post', URL('http://python.org/'), headers={'CONTENT-LENGTH': '1000'}, chunked=True, loop=loop) -async def test_chunked_transfer_encoding(loop, conn): +async def test_chunked_transfer_encoding(loop, conn) -> None: with pytest.raises(ValueError): ClientRequest( 'post', URL('http://python.org/'), headers={'TRANSFER-ENCODING': 'chunked'}, chunked=True, loop=loop) -async def test_file_upload_not_chunked(loop): +async def test_file_upload_not_chunked(loop) -> None: here = os.path.dirname(__file__) fname = os.path.join(here, 'sample.key') with open(fname, 'rb') as f: @@ -772,7 +808,7 @@ await req.close() -async def test_precompressed_data_stays_intact(loop): +async def test_precompressed_data_stays_intact(loop) -> None: data = zlib.compress(b'foobar') req = ClientRequest( 'post', URL('http://python.org/'), @@ -786,7 +822,7 @@ await req.close() -async def test_file_upload_not_chunked_seek(loop): +async def test_file_upload_not_chunked_seek(loop) -> None: here = os.path.dirname(__file__) fname = os.path.join(here, 'sample.key') with open(fname, 'rb') as f: @@ -800,7 +836,7 @@ await req.close() -async def test_file_upload_force_chunked(loop): +async def test_file_upload_force_chunked(loop) -> None: here = os.path.dirname(__file__) fname = os.path.join(here, 'sample.key') with open(fname, 'rb') as f: @@ -814,7 +850,7 @@ await req.close() -async def test_expect100(loop, conn): +async def test_expect100(loop, conn) -> None: req = ClientRequest('get', URL('http://python.org/'), expect100=True, loop=loop) resp = await req.send(conn) @@ -824,7 +860,7 @@ resp.close() -async def test_expect_100_continue_header(loop, conn): +async def test_expect_100_continue_header(loop, conn) -> None: req = ClientRequest('get', URL('http://python.org/'), headers={'expect': '100-continue'}, loop=loop) resp = await req.send(conn) @@ -834,7 +870,7 @@ resp.close() -async def test_data_stream(loop, buf, conn): +async def test_data_stream(loop, buf, conn) -> None: @async_generator async def gen(): await yield_(b'binary data') @@ -854,7 +890,7 @@ await req.close() -async def test_data_stream_deprecated(loop, buf, conn): +async def test_data_stream_deprecated(loop, buf, conn) -> None: with pytest.warns(DeprecationWarning): @aiohttp.streamer async def gen(writer): @@ -875,7 +911,7 @@ await req.close() -async def test_data_file(loop, buf, conn): +async def test_data_file(loop, buf, conn) -> None: req = ClientRequest( 'POST', URL('http://python.org/'), data=io.BufferedReader(io.BytesIO(b'*' * 2)), @@ -893,7 +929,7 @@ await req.close() -async def test_data_stream_exc(loop, conn): +async def test_data_stream_exc(loop, conn) -> None: fut = loop.create_future() @async_generator @@ -919,7 +955,7 @@ await req.close() -async def test_data_stream_exc_deprecated(loop, conn): +async def test_data_stream_exc_deprecated(loop, conn) -> None: fut = loop.create_future() with pytest.warns(DeprecationWarning): @@ -946,7 +982,7 @@ await req.close() -async def test_data_stream_exc_chain(loop, conn): +async def test_data_stream_exc_chain(loop, conn) -> None: fut = loop.create_future() @async_generator @@ -975,7 +1011,7 @@ await req.close() -async def test_data_stream_exc_chain_deprecated(loop, conn): +async def test_data_stream_exc_chain_deprecated(loop, conn) -> None: fut = loop.create_future() with pytest.warns(DeprecationWarning): @@ -1005,7 +1041,7 @@ await req.close() -async def test_data_stream_continue(loop, buf, conn): +async def test_data_stream_continue(loop, buf, conn) -> None: @async_generator async def gen(): await yield_(b'binary data') @@ -1030,7 +1066,7 @@ resp.close() -async def test_data_stream_continue_deprecated(loop, buf, conn): +async def test_data_stream_continue_deprecated(loop, buf, conn) -> None: with pytest.warns(DeprecationWarning): @aiohttp.streamer async def gen(writer): @@ -1057,7 +1093,7 @@ resp.close() -async def test_data_continue(loop, buf, conn): +async def test_data_continue(loop, buf, conn) -> None: req = ClientRequest( 'POST', URL('http://python.org/'), data=b'data', expect100=True, loop=loop) @@ -1076,7 +1112,7 @@ resp.close() -async def test_close(loop, buf, conn): +async def test_close(loop, buf, conn) -> None: @async_generator async def gen(): await asyncio.sleep(0.00001) @@ -1091,7 +1127,7 @@ resp.close() -async def test_close_deprecated(loop, buf, conn): +async def test_close_deprecated(loop, buf, conn) -> None: with pytest.warns(DeprecationWarning): @aiohttp.streamer async def gen(writer): @@ -1107,7 +1143,7 @@ resp.close() -async def test_custom_response_class(loop, conn): +async def test_custom_response_class(loop, conn) -> None: class CustomResponse(ClientResponse): def read(self, decode=False): return 'customized!' @@ -1121,7 +1157,7 @@ resp.close() -async def test_oserror_on_write_bytes(loop, conn): +async def test_oserror_on_write_bytes(loop, conn) -> None: req = ClientRequest( 'POST', URL('http://python.org/'), loop=loop) @@ -1135,7 +1171,7 @@ assert isinstance(exc, aiohttp.ClientOSError) -async def test_terminate(loop, conn): +async def test_terminate(loop, conn) -> None: req = ClientRequest('get', URL('http://python.org'), loop=loop) resp = await req.send(conn) assert req._writer is not None @@ -1147,7 +1183,7 @@ resp.close() -def test_terminate_with_closed_loop(loop, conn): +def test_terminate_with_closed_loop(loop, conn) -> None: req = resp = writer = None async def go(): @@ -1168,7 +1204,7 @@ resp.close() -def test_terminate_without_writer(loop): +def test_terminate_without_writer(loop) -> None: req = ClientRequest('get', URL('http://python.org'), loop=loop) assert req._writer is None @@ -1176,7 +1212,7 @@ assert req._writer is None -async def test_custom_req_rep(loop): +async def test_custom_req_rep(loop) -> None: conn = None class CustomResponse(ClientResponse): @@ -1186,7 +1222,7 @@ conn = connection self.status = 123 self.reason = 'Test OK' - self.headers = CIMultiDictProxy(CIMultiDict()) + self._headers = CIMultiDictProxy(CIMultiDict()) self.cookies = SimpleCookie() return @@ -1201,7 +1237,6 @@ continue100=self._continue, timer=self._timer, request_info=self.request_info, - auto_decompress=self._auto_decompress, traces=self._traces, loop=self.loop, session=self._session) @@ -1210,7 +1245,7 @@ called = True return resp - async def create_connection(req, traces=None): + async def create_connection(req, traces, timeout): assert isinstance(req, CustomRequest) return mock.Mock() connector = BaseConnector(loop=loop) @@ -1231,23 +1266,23 @@ conn.close() -def test_verify_ssl_false_with_ssl_context(loop): +def test_verify_ssl_false_with_ssl_context(loop) -> None: with pytest.warns(DeprecationWarning): with pytest.raises(ValueError): _merge_ssl_params(None, verify_ssl=False, ssl_context=mock.Mock(), fingerprint=None) -def test_bad_fingerprint(loop): +def test_bad_fingerprint(loop) -> None: with pytest.raises(ValueError): Fingerprint(b'invalid') -def test_insecure_fingerprint_md5(loop): +def test_insecure_fingerprint_md5(loop) -> None: with pytest.raises(ValueError): Fingerprint(hashlib.md5(b"foo").digest()) -def test_insecure_fingerprint_sha1(loop): +def test_insecure_fingerprint_sha1(loop) -> None: with pytest.raises(ValueError): Fingerprint(hashlib.sha1(b"foo").digest()) diff -Nru python-aiohttp-3.1.3/tests/test_client_response.py python-aiohttp-3.5.1/tests/test_client_response.py --- python-aiohttp-3.1.3/tests/test_client_response.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_client_response.py 2018-12-24 20:58:54.000000000 +0000 @@ -6,6 +6,7 @@ from unittest import mock import pytest +from multidict import CIMultiDict from yarl import URL import aiohttp @@ -20,7 +21,7 @@ return mock.Mock() -async def test_http_processing_error(session): +async def test_http_processing_error(session) -> None: loop = mock.Mock() request_info = mock.Mock() response = ClientResponse( @@ -28,7 +29,6 @@ writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) @@ -36,7 +36,7 @@ loop.get_debug.return_value = True connection = mock.Mock() - connection.protocol = aiohttp.DataQueue(loop=loop) + connection.protocol = aiohttp.DataQueue(loop) connection.protocol.set_response_params = mock.Mock() connection.protocol.set_exception(http.HttpProcessingError()) @@ -46,14 +46,13 @@ assert info.value.request_info is request_info -def test_del(session): +def test_del(session) -> None: loop = mock.Mock() response = ClientResponse('get', URL('http://del-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) @@ -72,13 +71,12 @@ connection.release.assert_called_with() -def test_close(loop, session): +def test_close(loop, session) -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) @@ -90,13 +88,12 @@ response.close() -def test_wait_for_100_1(loop, session): +def test_wait_for_100_1(loop, session) -> None: response = ClientResponse( 'get', URL('http://python.org'), continue100=object(), request_info=mock.Mock(), writer=mock.Mock(), timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) @@ -104,14 +101,13 @@ response.close() -def test_wait_for_100_2(loop, session): +def test_wait_for_100_2(loop, session) -> None: response = ClientResponse( 'get', URL('http://python.org'), request_info=mock.Mock(), continue100=None, writer=mock.Mock(), timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) @@ -119,13 +115,12 @@ response.close() -def test_repr(loop, session): +def test_repr(loop, session) -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) @@ -135,13 +130,12 @@ in repr(response) -def test_repr_non_ascii_url(): +def test_repr_non_ascii_url() -> None: response = ClientResponse('get', URL('http://fake-host.org/\u03bb'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=mock.Mock(), session=mock.Mock()) @@ -149,13 +143,12 @@ in repr(response) -def test_repr_non_ascii_reason(): +def test_repr_non_ascii_reason() -> None: response = ClientResponse('get', URL('http://fake-host.org/path'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=mock.Mock(), session=mock.Mock()) @@ -164,13 +157,12 @@ in repr(response) -def test_url_obj_deprecated(): +def test_url_obj_deprecated() -> None: response = ClientResponse('get', URL('http://fake-host.org/'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=mock.Mock(), session=mock.Mock()) @@ -178,13 +170,12 @@ response.url_obj -async def test_read_and_release_connection(loop, session): +async def test_read_and_release_connection(loop, session) -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) @@ -201,13 +192,12 @@ assert response._connection is None -async def test_read_and_release_connection_with_error(loop, session): +async def test_read_and_release_connection_with_error(loop, session) -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) @@ -220,13 +210,12 @@ assert response._closed -async def test_release(loop, session): +async def test_release(loop, session) -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) @@ -241,7 +230,7 @@ @pytest.mark.skipif(sys.implementation.name != 'cpython', reason="Other implementations has different GC strategies") -async def test_release_on_del(loop, session): +async def test_release_on_del(loop, session) -> None: connection = mock.Mock() connection.protocol.upgraded = False @@ -251,7 +240,6 @@ writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) @@ -263,13 +251,12 @@ assert connection.release.called -async def test_response_eof(loop, session): +async def test_response_eof(loop, session) -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) @@ -282,13 +269,12 @@ assert response._connection is None -async def test_response_eof_upgraded(loop, session): +async def test_response_eof_upgraded(loop, session) -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) @@ -301,13 +287,12 @@ assert response._connection is conn -async def test_response_eof_after_connection_detach(loop, session): +async def test_response_eof_after_connection_detach(loop, session) -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) @@ -320,13 +305,12 @@ assert response._connection is None -async def test_text(loop, session): +async def test_text(loop, session) -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) @@ -336,7 +320,7 @@ fut.set_result('{"тест": "пройден"}'.encode('cp1251')) return fut - response.headers = { + response._headers = { 'Content-Type': 'application/json;charset=cp1251'} content = response.content = mock.Mock() content.read.side_effect = side_effect @@ -346,13 +330,12 @@ assert response._connection is None -async def test_text_bad_encoding(loop, session): +async def test_text_bad_encoding(loop, session) -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) @@ -363,7 +346,7 @@ return fut # lie about the encoding - response.headers = { + response._headers = { 'Content-Type': 'application/json;charset=utf-8'} content = response.content = mock.Mock() content.read.side_effect = side_effect @@ -375,13 +358,12 @@ assert response._connection is None -async def test_text_custom_encoding(loop, session): +async def test_text_custom_encoding(loop, session) -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) @@ -391,7 +373,7 @@ fut.set_result('{"тест": "пройден"}'.encode('cp1251')) return fut - response.headers = { + response._headers = { 'Content-Type': 'application/json'} content = response.content = mock.Mock() content.read.side_effect = side_effect @@ -403,13 +385,12 @@ assert not response.get_encoding.called -async def test_text_detect_encoding(loop, session): +async def test_text_detect_encoding(loop, session) -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) @@ -419,7 +400,7 @@ fut.set_result('{"тест": "пройден"}'.encode('cp1251')) return fut - response.headers = {'Content-Type': 'text/plain'} + response._headers = {'Content-Type': 'text/plain'} content = response.content = mock.Mock() content.read.side_effect = side_effect @@ -429,13 +410,12 @@ assert response._connection is None -async def test_text_detect_encoding_if_invalid_charset(loop, session): +async def test_text_detect_encoding_if_invalid_charset(loop, session) -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) @@ -445,7 +425,7 @@ fut.set_result('{"тест": "пройден"}'.encode('cp1251')) return fut - response.headers = {'Content-Type': 'text/plain;charset=invalid'} + response._headers = {'Content-Type': 'text/plain;charset=invalid'} content = response.content = mock.Mock() content.read.side_effect = side_effect @@ -456,13 +436,12 @@ assert response.get_encoding().lower() in ('windows-1251', 'maccyrillic') -async def test_text_after_read(loop, session): +async def test_text_after_read(loop, session) -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) @@ -472,7 +451,7 @@ fut.set_result('{"тест": "пройден"}'.encode('cp1251')) return fut - response.headers = { + response._headers = { 'Content-Type': 'application/json;charset=cp1251'} content = response.content = mock.Mock() content.read.side_effect = side_effect @@ -482,13 +461,12 @@ assert response._connection is None -async def test_json(loop, session): +async def test_json(loop, session) -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) @@ -498,7 +476,7 @@ fut.set_result('{"тест": "пройден"}'.encode('cp1251')) return fut - response.headers = { + response._headers = { 'Content-Type': 'application/json;charset=cp1251'} content = response.content = mock.Mock() content.read.side_effect = side_effect @@ -508,13 +486,12 @@ assert response._connection is None -async def test_json_extended_content_type(loop, session): +async def test_json_extended_content_type(loop, session) -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) @@ -524,7 +501,7 @@ fut.set_result('{"тест": "пройден"}'.encode('cp1251')) return fut - response.headers = { + response._headers = { 'Content-Type': 'application/this.is-1_content+subtype+json;charset=cp1251'} content = response.content = mock.Mock() @@ -535,13 +512,12 @@ assert response._connection is None -async def test_json_custom_content_type(loop, session): +async def test_json_custom_content_type(loop, session) -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) @@ -551,7 +527,7 @@ fut.set_result('{"тест": "пройден"}'.encode('cp1251')) return fut - response.headers = { + response._headers = { 'Content-Type': 'custom/type;charset=cp1251'} content = response.content = mock.Mock() content.read.side_effect = side_effect @@ -561,17 +537,16 @@ assert response._connection is None -async def test_json_custom_loader(loop, session): +async def test_json_custom_loader(loop, session) -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) - response.headers = { + response._headers = { 'Content-Type': 'application/json;charset=cp1251'} response._body = b'data' @@ -582,17 +557,16 @@ assert res == 'data-custom' -async def test_json_invalid_content_type(loop, session): +async def test_json_invalid_content_type(loop, session) -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) - response.headers = { + response._headers = { 'Content-Type': 'data/octet-stream'} response._body = b'' @@ -602,17 +576,16 @@ assert info.value.request_info == response.request_info -async def test_json_no_content(loop, session): +async def test_json_no_content(loop, session) -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) - response.headers = { + response._headers = { 'Content-Type': 'data/octet-stream'} response._body = b'' @@ -620,13 +593,12 @@ assert res is None -async def test_json_override_encoding(loop, session): +async def test_json_override_encoding(loop, session) -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) @@ -636,7 +608,7 @@ fut.set_result('{"тест": "пройден"}'.encode('cp1251')) return fut - response.headers = { + response._headers = { 'Content-Type': 'application/json;charset=utf8'} content = response.content = mock.Mock() content.read.side_effect = side_effect @@ -648,30 +620,28 @@ assert not response.get_encoding.called -def test_get_encoding_unknown(loop, session): +def test_get_encoding_unknown(loop, session) -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=loop, session=session) - response.headers = {'Content-Type': 'application/json'} + response._headers = {'Content-Type': 'application/json'} with mock.patch('aiohttp.client_reqrep.chardet') as m_chardet: m_chardet.detect.return_value = {'encoding': None} assert response.get_encoding() == 'utf-8' -def test_raise_for_status_2xx(): +def test_raise_for_status_2xx() -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=mock.Mock(), session=mock.Mock()) @@ -680,13 +650,12 @@ response.raise_for_status() # should not raise -def test_raise_for_status_4xx(): +def test_raise_for_status_4xx() -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=mock.Mock(), session=mock.Mock()) @@ -696,108 +665,102 @@ response.raise_for_status() assert str(cm.value.status) == '409' assert str(cm.value.message) == "CONFLICT" + assert response.closed -def test_resp_host(): +def test_resp_host() -> None: response = ClientResponse('get', URL('http://del-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=mock.Mock(), session=mock.Mock()) assert 'del-cl-resp.org' == response.host -def test_content_type(): +def test_content_type() -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=mock.Mock(), session=mock.Mock()) - response.headers = {'Content-Type': 'application/json;charset=cp1251'} + response._headers = {'Content-Type': 'application/json;charset=cp1251'} assert 'application/json' == response.content_type -def test_content_type_no_header(): +def test_content_type_no_header() -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=mock.Mock(), session=mock.Mock()) - response.headers = {} + response._headers = {} assert 'application/octet-stream' == response.content_type -def test_charset(): +def test_charset() -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=mock.Mock(), session=mock.Mock()) - response.headers = {'Content-Type': 'application/json;charset=cp1251'} + response._headers = {'Content-Type': 'application/json;charset=cp1251'} assert 'cp1251' == response.charset -def test_charset_no_header(): +def test_charset_no_header() -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=mock.Mock(), session=mock.Mock()) - response.headers = {} + response._headers = {} assert response.charset is None -def test_charset_no_charset(): +def test_charset_no_charset() -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=mock.Mock(), session=mock.Mock()) - response.headers = {'Content-Type': 'application/json'} + response._headers = {'Content-Type': 'application/json'} assert response.charset is None -def test_content_disposition_full(): +def test_content_disposition_full() -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=mock.Mock(), session=mock.Mock()) - response.headers = {'Content-Disposition': - 'attachment; filename="archive.tar.gz"; foo=bar'} + response._headers = {'Content-Disposition': + 'attachment; filename="archive.tar.gz"; foo=bar'} assert 'attachment' == response.content_disposition.type assert 'bar' == response.content_disposition.parameters["foo"] @@ -806,55 +769,37 @@ response.content_disposition.parameters["foo"] = "baz" -def test_content_disposition_no_parameters(): +def test_content_disposition_no_parameters() -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=mock.Mock(), session=mock.Mock()) - response.headers = {'Content-Disposition': 'attachment'} + response._headers = {'Content-Disposition': 'attachment'} assert 'attachment' == response.content_disposition.type assert response.content_disposition.filename is None assert {} == response.content_disposition.parameters -def test_content_disposition_no_header(): +def test_content_disposition_no_header() -> None: response = ClientResponse('get', URL('http://def-cl-resp.org'), request_info=mock.Mock(), writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=mock.Mock(), session=mock.Mock()) - response.headers = {} + response._headers = {} assert response.content_disposition is None -def test_content_disposition_cache(): - response = ClientResponse('get', URL('http://def-cl-resp.org'), - request_info=mock.Mock(), - writer=mock.Mock(), - continue100=None, - timer=TimerNoop(), - auto_decompress=True, - traces=[], - loop=mock.Mock(), - session=mock.Mock()) - response.headers = {'Content-Disposition': 'attachment'} - cd = response.content_disposition - ClientResponse.headers = {'Content-Disposition': 'spam'} - assert cd is response.content_disposition - - -def test_response_request_info(): +def test_response_request_info() -> None: url = 'http://def-cl-resp.org' headers = {'Content-Type': 'application/json;charset=cp1251'} response = ClientResponse( @@ -867,7 +812,6 @@ writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=mock.Mock(), session=mock.Mock() @@ -877,7 +821,7 @@ assert headers == response.request_info.headers -def test_request_info_in_exception(): +def test_request_info_in_exception() -> None: url = 'http://def-cl-resp.org' headers = {'Content-Type': 'application/json;charset=cp1251'} response = ClientResponse( @@ -891,7 +835,6 @@ writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=mock.Mock(), session=mock.Mock() @@ -903,7 +846,7 @@ assert cm.value.request_info == response.request_info -def test_no_redirect_history_in_exception(): +def test_no_redirect_history_in_exception() -> None: url = 'http://def-cl-resp.org' headers = {'Content-Type': 'application/json;charset=cp1251'} response = ClientResponse( @@ -917,7 +860,6 @@ writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=mock.Mock(), session=mock.Mock() @@ -929,7 +871,7 @@ assert () == cm.value.history -def test_redirect_history_in_exception(): +def test_redirect_history_in_exception() -> None: hist_url = 'http://def-cl-resp.org' url = 'http://def-cl-resp.org/index.htm' hist_headers = {'Content-Type': 'application/json;charset=cp1251', @@ -947,7 +889,6 @@ writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=mock.Mock(), session=mock.Mock() @@ -966,13 +907,12 @@ writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=mock.Mock(), session=mock.Mock() ) - hist_response.headers = hist_headers + hist_response._headers = hist_headers hist_response.status = 301 hist_response.reason = 'REDIRECT' @@ -982,7 +922,7 @@ assert [hist_response] == cm.value.history -async def test_response_read_triggers_callback(loop, session): +async def test_response_read_triggers_callback(loop, session) -> None: trace = mock.Mock() trace.send_response_chunk_received = make_mocked_coro() response_body = b'This is response' @@ -993,7 +933,6 @@ writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, loop=loop, session=session, traces=[trace] @@ -1004,7 +943,7 @@ fut.set_result(response_body) return fut - response.headers = { + response._headers = { 'Content-Type': 'application/json;charset=cp1251'} content = response.content = mock.Mock() content.read.side_effect = side_effect @@ -1018,3 +957,167 @@ trace.send_response_chunk_received.call_args == mock.call(response_body) ) + + +def test_response_real_url(loop, session) -> None: + url = URL('http://def-cl-resp.org/#urlfragment') + response = ClientResponse('get', url, + request_info=mock.Mock(), + writer=mock.Mock(), + continue100=None, + timer=TimerNoop(), + traces=[], + loop=loop, + session=session) + assert response.url == url.with_fragment(None) + assert response.real_url == url + + +def test_response_links_comma_separated(loop, session) -> None: + url = URL('http://def-cl-resp.org/') + response = ClientResponse('get', url, + request_info=mock.Mock(), + writer=mock.Mock(), + continue100=None, + timer=TimerNoop(), + traces=[], + loop=loop, + session=session) + response._headers = CIMultiDict([ + ( + "Link", + ('; rel=next, ' + '; rel=home') + ) + ]) + assert ( + response.links == + {'next': + {'url': URL('http://example.com/page/1.html'), + 'rel': 'next'}, + 'home': + {'url': URL('http://example.com/'), + 'rel': 'home'} + } + ) + + +def test_response_links_multiple_headers(loop, session) -> None: + url = URL('http://def-cl-resp.org/') + response = ClientResponse('get', url, + request_info=mock.Mock(), + writer=mock.Mock(), + continue100=None, + timer=TimerNoop(), + traces=[], + loop=loop, + session=session) + response._headers = CIMultiDict([ + ( + "Link", + '; rel=next' + ), + ( + "Link", + '; rel=home' + ) + ]) + assert ( + response.links == + {'next': + {'url': URL('http://example.com/page/1.html'), + 'rel': 'next'}, + 'home': + {'url': URL('http://example.com/'), + 'rel': 'home'} + } + ) + + +def test_response_links_no_rel(loop, session) -> None: + url = URL('http://def-cl-resp.org/') + response = ClientResponse('get', url, + request_info=mock.Mock(), + writer=mock.Mock(), + continue100=None, + timer=TimerNoop(), + traces=[], + loop=loop, + session=session) + response._headers = CIMultiDict([ + ( + "Link", + '' + ) + ]) + assert ( + response.links == + { + 'http://example.com/': + {'url': URL('http://example.com/')} + } + ) + + +def test_response_links_quoted(loop, session) -> None: + url = URL('http://def-cl-resp.org/') + response = ClientResponse('get', url, + request_info=mock.Mock(), + writer=mock.Mock(), + continue100=None, + timer=TimerNoop(), + traces=[], + loop=loop, + session=session) + response._headers = CIMultiDict([ + ( + "Link", + '; rel="home-page"' + ), + ]) + assert ( + response.links == + {'home-page': + {'url': URL('http://example.com/'), + 'rel': 'home-page'} + } + ) + + +def test_response_links_relative(loop, session) -> None: + url = URL('http://def-cl-resp.org/') + response = ClientResponse('get', url, + request_info=mock.Mock(), + writer=mock.Mock(), + continue100=None, + timer=TimerNoop(), + traces=[], + loop=loop, + session=session) + response._headers = CIMultiDict([ + ( + "Link", + '; rel=rel' + ), + ]) + assert ( + response.links == + {'rel': + {'url': URL('http://def-cl-resp.org/relative/path'), + 'rel': 'rel'} + } + ) + + +def test_response_links_empty(loop, session) -> None: + url = URL('http://def-cl-resp.org/') + response = ClientResponse('get', url, + request_info=mock.Mock(), + writer=mock.Mock(), + continue100=None, + timer=TimerNoop(), + traces=[], + loop=loop, + session=session) + response._headers = CIMultiDict() + assert response.links == {} diff -Nru python-aiohttp-3.1.3/tests/test_client_session.py python-aiohttp-3.5.1/tests/test_client_session.py --- python-aiohttp-3.1.3/tests/test_client_session.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_client_session.py 2018-12-24 20:58:54.000000000 +0000 @@ -12,7 +12,7 @@ from yarl import URL import aiohttp -from aiohttp import hdrs, web +from aiohttp import client, hdrs, web from aiohttp.client import ClientSession from aiohttp.client_reqrep import ClientRequest from aiohttp.connector import BaseConnector, TCPConnector @@ -21,7 +21,9 @@ @pytest.fixture def connector(loop): - conn = BaseConnector(loop=loop) + async def make_conn(): + return BaseConnector(loop=loop) + conn = loop.run_until_complete(make_conn()) proto = mock.Mock() conn._conns['a'] = [(proto, 123)] yield conn @@ -32,7 +34,7 @@ def create_session(loop): session = None - def maker(*args, **kwargs): + async def maker(*args, **kwargs): nonlocal session session = ClientSession(*args, loop=loop, **kwargs) return session @@ -42,8 +44,8 @@ @pytest.fixture -def session(create_session): - return create_session() +def session(create_session, loop): + return loop.run_until_complete(create_session()) @pytest.fixture @@ -59,60 +61,61 @@ read_until_eof=False) -def test_close_coro(create_session, loop): - session = create_session() - loop.run_until_complete(session.close()) +async def test_close_coro(create_session) -> None: + session = await create_session() + await session.close() -def test_init_headers_simple_dict(create_session): - session = create_session(headers={"h1": "header1", - "h2": "header2"}) +async def test_init_headers_simple_dict(create_session) -> None: + session = await create_session(headers={"h1": "header1", + "h2": "header2"}) assert (sorted(session._default_headers.items()) == ([("h1", "header1"), ("h2", "header2")])) -def test_init_headers_list_of_tuples(create_session): - session = create_session(headers=[("h1", "header1"), - ("h2", "header2"), - ("h3", "header3")]) +async def test_init_headers_list_of_tuples(create_session) -> None: + session = await create_session(headers=[("h1", "header1"), + ("h2", "header2"), + ("h3", "header3")]) assert (session._default_headers == CIMultiDict([("h1", "header1"), ("h2", "header2"), ("h3", "header3")])) -def test_init_headers_MultiDict(create_session): - session = create_session(headers=MultiDict([("h1", "header1"), - ("h2", "header2"), - ("h3", "header3")])) +async def test_init_headers_MultiDict(create_session) -> None: + session = await create_session(headers=MultiDict([("h1", "header1"), + ("h2", "header2"), + ("h3", "header3")])) assert (session._default_headers == CIMultiDict([("H1", "header1"), ("H2", "header2"), ("H3", "header3")])) -def test_init_headers_list_of_tuples_with_duplicates(create_session): - session = create_session(headers=[("h1", "header11"), - ("h2", "header21"), - ("h1", "header12")]) +async def test_init_headers_list_of_tuples_with_duplicates( + create_session) -> None: + session = await create_session(headers=[("h1", "header11"), + ("h2", "header21"), + ("h1", "header12")]) assert (session._default_headers == CIMultiDict([("H1", "header11"), ("H2", "header21"), ("H1", "header12")])) -def test_init_cookies_with_simple_dict(create_session): - session = create_session(cookies={"c1": "cookie1", - "c2": "cookie2"}) +async def test_init_cookies_with_simple_dict(create_session) -> None: + session = await create_session(cookies={"c1": "cookie1", + "c2": "cookie2"}) cookies = session.cookie_jar.filter_cookies() assert set(cookies) == {'c1', 'c2'} assert cookies['c1'].value == 'cookie1' assert cookies['c2'].value == 'cookie2' -def test_init_cookies_with_list_of_tuples(create_session): - session = create_session(cookies=[("c1", "cookie1"), - ("c2", "cookie2")]) +async def test_init_cookies_with_list_of_tuples(create_session) -> None: + session = await create_session(cookies=[("c1", "cookie1"), + ("c2", "cookie2")]) cookies = session.cookie_jar.filter_cookies() assert set(cookies) == {'c1', 'c2'} @@ -120,35 +123,36 @@ assert cookies['c2'].value == 'cookie2' -def test_merge_headers(create_session): +async def test_merge_headers(create_session) -> None: # Check incoming simple dict - session = create_session(headers={"h1": "header1", - "h2": "header2"}) + session = await create_session(headers={"h1": "header1", + "h2": "header2"}) headers = session._prepare_headers({"h1": "h1"}) assert isinstance(headers, CIMultiDict) assert headers == {"h1": "h1", "h2": "header2"} -def test_merge_headers_with_multi_dict(create_session): - session = create_session(headers={"h1": "header1", - "h2": "header2"}) +async def test_merge_headers_with_multi_dict(create_session) -> None: + session = await create_session(headers={"h1": "header1", + "h2": "header2"}) headers = session._prepare_headers(MultiDict([("h1", "h1")])) assert isinstance(headers, CIMultiDict) assert headers == {"h1": "h1", "h2": "header2"} -def test_merge_headers_with_list_of_tuples(create_session): - session = create_session(headers={"h1": "header1", - "h2": "header2"}) +async def test_merge_headers_with_list_of_tuples(create_session) -> None: + session = await create_session(headers={"h1": "header1", + "h2": "header2"}) headers = session._prepare_headers([("h1", "h1")]) assert isinstance(headers, CIMultiDict) assert headers == {"h1": "h1", "h2": "header2"} -def test_merge_headers_with_list_of_tuples_duplicated_names(create_session): - session = create_session(headers={"h1": "header1", - "h2": "header2"}) +async def test_merge_headers_with_list_of_tuples_duplicated_names( + create_session) -> None: + session = await create_session(headers={"h1": "header1", + "h2": "header2"}) headers = session._prepare_headers([("h1", "v1"), ("h1", "v2")]) @@ -159,7 +163,7 @@ ("h2", "header2")] -def test_http_GET(session, params): +def test_http_GET(session, params) -> None: with mock.patch("aiohttp.client.ClientSession._request") as patched: session.get("http://test.example.com", params={"x": 1}, @@ -172,7 +176,7 @@ **params)] -def test_http_OPTIONS(session, params): +def test_http_OPTIONS(session, params) -> None: with mock.patch("aiohttp.client.ClientSession._request") as patched: session.options("http://opt.example.com", params={"x": 2}, @@ -185,7 +189,7 @@ **params)] -def test_http_HEAD(session, params): +def test_http_HEAD(session, params) -> None: with mock.patch("aiohttp.client.ClientSession._request") as patched: session.head("http://head.example.com", params={"x": 2}, @@ -198,7 +202,7 @@ **params)] -def test_http_POST(session, params): +def test_http_POST(session, params) -> None: with mock.patch("aiohttp.client.ClientSession._request") as patched: session.post("http://post.example.com", params={"x": 2}, @@ -212,7 +216,7 @@ **params)] -def test_http_PUT(session, params): +def test_http_PUT(session, params) -> None: with mock.patch("aiohttp.client.ClientSession._request") as patched: session.put("http://put.example.com", params={"x": 2}, @@ -226,7 +230,7 @@ **params)] -def test_http_PATCH(session, params): +def test_http_PATCH(session, params) -> None: with mock.patch("aiohttp.client.ClientSession._request") as patched: session.patch("http://patch.example.com", params={"x": 2}, @@ -240,7 +244,7 @@ **params)] -def test_http_DELETE(session, params): +def test_http_DELETE(session, params) -> None: with mock.patch("aiohttp.client.ClientSession._request") as patched: session.delete("http://delete.example.com", params={"x": 2}, @@ -253,24 +257,24 @@ **params)] -async def test_close(create_session, connector): - session = create_session(connector=connector) +async def test_close(create_session, connector) -> None: + session = await create_session(connector=connector) await session.close() assert session.connector is None assert connector.closed -async def test_closed(session): +async def test_closed(session) -> None: assert not session.closed await session.close() assert session.closed -async def test_connector(create_session, loop, mocker): +async def test_connector(create_session, loop, mocker) -> None: connector = TCPConnector(loop=loop) mocker.spy(connector, 'close') - session = create_session(connector=connector) + session = await create_session(connector=connector) assert session.connector is connector await session.close() @@ -278,8 +282,8 @@ connector.close() -async def test_create_connector(create_session, loop, mocker): - session = create_session() +async def test_create_connector(create_session, loop, mocker) -> None: + session = await create_session() connector = session.connector mocker.spy(session.connector, 'close') @@ -287,19 +291,25 @@ assert connector.close.called -def test_connector_loop(loop): +def test_connector_loop(loop) -> None: with contextlib.ExitStack() as stack: another_loop = asyncio.new_event_loop() stack.enter_context(contextlib.closing(another_loop)) - connector = TCPConnector(loop=another_loop) + + async def make_connector(): + return TCPConnector() + connector = another_loop.run_until_complete(make_connector()) + stack.enter_context(contextlib.closing(connector)) with pytest.raises(RuntimeError) as ctx: - ClientSession(connector=connector, loop=loop) + async def make_sess(): + return ClientSession(connector=connector, loop=loop) + loop.run_until_complete(make_sess()) assert re.match("Session and connector has to use same event loop", str(ctx.value)) -def test_detach(session): +def test_detach(session) -> None: conn = session.connector try: assert not conn.closed @@ -311,21 +321,21 @@ conn.close() -async def test_request_closed_session(session): +async def test_request_closed_session(session) -> None: await session.close() with pytest.raises(RuntimeError): await session.request('get', '/') -def test_close_flag_for_closed_connector(session): +def test_close_flag_for_closed_connector(session) -> None: conn = session.connector assert not session.closed conn.close() assert session.closed -async def test_double_close(connector, create_session): - session = create_session(connector=connector) +async def test_double_close(connector, create_session) -> None: + session = await create_session(connector=connector) await session.close() assert session.connector is None @@ -334,17 +344,42 @@ assert connector.closed -def test_del(connector, loop): +async def test_del(connector, loop) -> None: + loop.set_debug(False) + # N.B. don't use session fixture, it stores extra reference internally + session = ClientSession(connector=connector, loop=loop) + logs = [] + loop.set_exception_handler(lambda loop, ctx: logs.append(ctx)) + + with pytest.warns(ResourceWarning): + del session + gc.collect() + + assert len(logs) == 1 + expected = {'client_session': mock.ANY, + 'message': 'Unclosed client session'} + assert logs[0] == expected + + +async def test_del_debug(connector, loop) -> None: + loop.set_debug(True) # N.B. don't use session fixture, it stores extra reference internally session = ClientSession(connector=connector, loop=loop) - loop.set_exception_handler(lambda loop, ctx: None) + logs = [] + loop.set_exception_handler(lambda loop, ctx: logs.append(ctx)) with pytest.warns(ResourceWarning): del session gc.collect() + assert len(logs) == 1 + expected = {'client_session': mock.ANY, + 'message': 'Unclosed client session', + 'source_traceback': mock.ANY} + assert logs[0] == expected -def test_context_manager(connector, loop): + +async def test_context_manager(connector, loop) -> None: with pytest.raises(TypeError): with ClientSession(loop=loop, connector=connector) as session: pass @@ -352,7 +387,7 @@ assert session.closed -async def test_borrow_connector_loop(connector, create_session, loop): +async def test_borrow_connector_loop(connector, create_session, loop) -> None: session = ClientSession(connector=connector, loop=None) try: assert session._loop, loop @@ -360,14 +395,14 @@ await session.close() -async def test_reraise_os_error(create_session): +async def test_reraise_os_error(create_session) -> None: err = OSError(1, "permission error") req = mock.Mock() req_factory = mock.Mock(return_value=req) req.send = mock.Mock(side_effect=err) - session = create_session(request_class=req_factory) + session = await create_session(request_class=req_factory) - async def create_connection(req, traces=None): + async def create_connection(req, traces, timeout): # return self.transport, self.protocol return mock.Mock() session._connector._create_connection = create_connection @@ -380,7 +415,7 @@ assert e.strerror == err.strerror -async def test_close_conn_on_error(create_session): +async def test_close_conn_on_error(create_session) -> None: class UnexpectedException(BaseException): pass @@ -388,17 +423,17 @@ req = mock.Mock() req_factory = mock.Mock(return_value=req) req.send = mock.Mock(side_effect=err) - session = create_session(request_class=req_factory) + session = await create_session(request_class=req_factory) connections = [] original_connect = session._connector.connect - async def connect(req, traces=None): - conn = await original_connect(req, traces=traces) + async def connect(req, traces, timeout): + conn = await original_connect(req, traces, timeout) connections.append(conn) return conn - async def create_connection(req, traces=None): + async def create_connection(req, traces, timeout): # return self.transport, self.protocol conn = mock.Mock() return conn @@ -417,7 +452,7 @@ c.__del__() -async def test_cookie_jar_usage(loop, aiohttp_client): +async def test_cookie_jar_usage(loop, aiohttp_client) -> None: req_url = None jar = mock.Mock() @@ -458,18 +493,19 @@ assert resp_cookies["response"].value == "resp_value" -def test_session_default_version(loop): +async def test_session_default_version(loop) -> None: session = aiohttp.ClientSession(loop=loop) assert session.version == aiohttp.HttpVersion11 -async def test_session_loop(loop): +async def test_session_loop(loop) -> None: session = aiohttp.ClientSession(loop=loop) - assert session.loop is loop + with pytest.warns(DeprecationWarning): + assert session.loop is loop await session.close() -def test_proxy_str(session, params): +def test_proxy_str(session, params) -> None: with mock.patch("aiohttp.client.ClientSession._request") as patched: session.get("http://test.example.com", proxy='http://proxy.com', @@ -482,20 +518,7 @@ **params)] -def test_client_session_implicit_loop_warn(): - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - - with pytest.warns(UserWarning): - session = aiohttp.ClientSession() - assert session._loop is loop - loop.run_until_complete(session.close()) - - asyncio.set_event_loop(None) - loop.close() - - -async def test_request_tracing(loop, aiohttp_client): +async def test_request_tracing(loop, aiohttp_client) -> None: async def handler(request): return web.json_response({'ok': True}) @@ -559,7 +582,7 @@ {'ok': True}).encode('utf8') -async def test_request_tracing_exception(loop): +async def test_request_tracing_exception(loop) -> None: on_request_end = mock.Mock(side_effect=asyncio.coroutine(mock.Mock())) on_request_exception = mock.Mock( side_effect=asyncio.coroutine(mock.Mock()) @@ -598,7 +621,7 @@ assert not on_request_end.called -async def test_request_tracing_interpose_headers(loop, aiohttp_client): +async def test_request_tracing_interpose_headers(loop, aiohttp_client) -> None: async def handler(request): return web.Response() @@ -634,7 +657,7 @@ @pytest.mark.skipif(not PY_36, reason="Python 3.6+ required") -def test_client_session_inheritance(): +def test_client_session_inheritance() -> None: with pytest.warns(DeprecationWarning): class A(ClientSession): pass @@ -642,7 +665,47 @@ @pytest.mark.skipif(not DEBUG, reason="The check is applied in DEBUG mode only") -def test_client_session_custom_attr(loop): +async def test_client_session_custom_attr(loop) -> None: session = ClientSession(loop=loop) with pytest.warns(DeprecationWarning): session.custom = None + + +async def test_client_session_timeout_args(loop) -> None: + session1 = ClientSession(loop=loop) + assert session1._timeout == client.DEFAULT_TIMEOUT + + with pytest.warns(DeprecationWarning): + session2 = ClientSession(loop=loop, + read_timeout=20*60, + conn_timeout=30*60) + assert session2._timeout == client.ClientTimeout(total=20*60, + connect=30*60) + + with pytest.raises(ValueError): + ClientSession(loop=loop, + timeout=client.ClientTimeout(total=10*60), + read_timeout=20*60) + + with pytest.raises(ValueError): + ClientSession(loop=loop, + timeout=client.ClientTimeout(total=10 * 60), + conn_timeout=30 * 60) + + +async def test_requote_redirect_url_default() -> None: + session = ClientSession() + assert session.requote_redirect_url + + +async def test_requote_redirect_url_default_disable() -> None: + session = ClientSession(requote_redirect_url=False) + assert not session.requote_redirect_url + + +async def test_requote_redirect_setter() -> None: + session = ClientSession() + assert session.requote_redirect_url + with pytest.warns(DeprecationWarning): + session.requote_redirect_url = False + assert not session.requote_redirect_url diff -Nru python-aiohttp-3.1.3/tests/test_client_ws_functional.py python-aiohttp-3.5.1/tests/test_client_ws_functional.py --- python-aiohttp-3.1.3/tests/test_client_ws_functional.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_client_ws_functional.py 2018-12-24 20:58:54.000000000 +0000 @@ -15,7 +15,7 @@ mocker.patch('aiohttp.helpers.ceil').side_effect = ceil -async def test_send_recv_text(loop, aiohttp_client): +async def test_send_recv_text(aiohttp_client) -> None: async def handler(request): ws = web.WebSocketResponse() @@ -41,7 +41,7 @@ assert resp.get_extra_info('socket') is None -async def test_send_recv_bytes_bad_type(loop, aiohttp_client): +async def test_send_recv_bytes_bad_type(aiohttp_client) -> None: async def handler(request): ws = web.WebSocketResponse() @@ -63,7 +63,7 @@ await resp.close() -async def test_send_recv_bytes(loop, aiohttp_client): +async def test_send_recv_bytes(aiohttp_client) -> None: async def handler(request): ws = web.WebSocketResponse() @@ -87,7 +87,7 @@ await resp.close() -async def test_send_recv_text_bad_type(loop, aiohttp_client): +async def test_send_recv_text_bad_type(aiohttp_client) -> None: async def handler(request): ws = web.WebSocketResponse() @@ -111,7 +111,7 @@ await resp.close() -async def test_send_recv_json(loop, aiohttp_client): +async def test_send_recv_json(aiohttp_client) -> None: async def handler(request): ws = web.WebSocketResponse() @@ -134,8 +134,8 @@ await resp.close() -async def test_ping_pong(loop, aiohttp_client): - +async def test_ping_pong(aiohttp_client) -> None: + loop = asyncio.get_event_loop() closed = loop.create_future() async def handler(request): @@ -170,8 +170,8 @@ await closed -async def test_ping_pong_manual(loop, aiohttp_client): - +async def test_ping_pong_manual(aiohttp_client) -> None: + loop = asyncio.get_event_loop() closed = loop.create_future() async def handler(request): @@ -211,7 +211,7 @@ await closed -async def test_close(loop, aiohttp_client): +async def test_close(aiohttp_client) -> None: async def handler(request): ws = web.WebSocketResponse() @@ -239,7 +239,7 @@ assert msg.type == aiohttp.WSMsgType.CLOSED -async def test_concurrent_close(loop, aiohttp_client): +async def test_concurrent_close(aiohttp_client) -> None: client_ws = None async def handler(request): @@ -266,13 +266,13 @@ msg = await ws.receive() assert msg.type == aiohttp.WSMsgType.CLOSING - await asyncio.sleep(0.01, loop=loop) + await asyncio.sleep(0.01) msg = await ws.receive() assert msg.type == aiohttp.WSMsgType.CLOSED -async def test_close_from_server(loop, aiohttp_client): - +async def test_close_from_server(aiohttp_client) -> None: + loop = asyncio.get_event_loop() closed = loop.create_future() async def handler(request): @@ -303,8 +303,8 @@ await closed -async def test_close_manual(loop, aiohttp_client): - +async def test_close_manual(aiohttp_client) -> None: + loop = asyncio.get_event_loop() closed = loop.create_future() async def handler(request): @@ -340,14 +340,14 @@ assert resp.closed -async def test_close_timeout(loop, aiohttp_client): +async def test_close_timeout(aiohttp_client) -> None: async def handler(request): ws = web.WebSocketResponse() await ws.prepare(request) await ws.receive_bytes() await ws.send_str('test') - await asyncio.sleep(1, loop=loop) + await asyncio.sleep(1) return ws app = web.Application() @@ -366,14 +366,15 @@ assert isinstance(resp.exception(), asyncio.TimeoutError) -async def test_close_cancel(loop, aiohttp_client): +async def test_close_cancel(aiohttp_client) -> None: + loop = asyncio.get_event_loop() async def handler(request): ws = web.WebSocketResponse() await ws.prepare(request) await ws.receive_bytes() await ws.send_str('test') - await asyncio.sleep(10, loop=loop) + await asyncio.sleep(10) app = web.Application() app.router.add_route('GET', '/', handler) @@ -386,14 +387,14 @@ assert text.data == 'test' t = loop.create_task(resp.close()) - await asyncio.sleep(0.1, loop=loop) + await asyncio.sleep(0.1) t.cancel() - await asyncio.sleep(0.1, loop=loop) + await asyncio.sleep(0.1) assert resp.closed assert resp.exception() is None -async def test_override_default_headers(loop, aiohttp_client): +async def test_override_default_headers(aiohttp_client) -> None: async def handler(request): assert request.headers[hdrs.SEC_WEBSOCKET_VERSION] == '8' @@ -413,7 +414,7 @@ await resp.close() -async def test_additional_headers(loop, aiohttp_client): +async def test_additional_headers(aiohttp_client) -> None: async def handler(request): assert request.headers['x-hdr'] == 'xtra' @@ -433,7 +434,7 @@ await resp.close() -async def test_recv_protocol_error(loop, aiohttp_client): +async def test_recv_protocol_error(aiohttp_client) -> None: async def handler(request): ws = web.WebSocketResponse() @@ -458,7 +459,7 @@ await resp.close() -async def test_recv_timeout(loop, aiohttp_client): +async def test_recv_timeout(aiohttp_client) -> None: async def handler(request): ws = web.WebSocketResponse() @@ -466,7 +467,7 @@ await ws.receive_str() - await asyncio.sleep(0.1, loop=request.app.loop) + await asyncio.sleep(0.1) await ws.close() return ws @@ -478,13 +479,13 @@ await resp.send_str('ask') with pytest.raises(asyncio.TimeoutError): - with async_timeout.timeout(0.01, loop=app.loop): + with async_timeout.timeout(0.01): await resp.receive() await resp.close() -async def test_receive_timeout(loop, aiohttp_client): +async def test_receive_timeout(aiohttp_client) -> None: async def handler(request): ws = web.WebSocketResponse() @@ -505,7 +506,7 @@ await resp.close() -async def test_custom_receive_timeout(loop, aiohttp_client): +async def test_custom_receive_timeout(aiohttp_client) -> None: async def handler(request): ws = web.WebSocketResponse() @@ -526,7 +527,7 @@ await resp.close() -async def test_heartbeat(loop, aiohttp_client, ceil): +async def test_heartbeat(aiohttp_client, ceil) -> None: ping_received = False async def handler(request): @@ -551,7 +552,7 @@ assert ping_received -async def test_heartbeat_no_pong(loop, aiohttp_client, ceil): +async def test_heartbeat_no_pong(aiohttp_client, ceil) -> None: ping_received = False async def handler(request): @@ -576,7 +577,7 @@ assert ping_received -async def test_send_recv_compress(loop, aiohttp_client): +async def test_send_recv_compress(aiohttp_client) -> None: async def handler(request): ws = web.WebSocketResponse() @@ -602,7 +603,7 @@ assert resp.get_extra_info('socket') is None -async def test_send_recv_compress_wbits(loop, aiohttp_client): +async def test_send_recv_compress_wbits(aiohttp_client) -> None: async def handler(request): ws = web.WebSocketResponse() @@ -630,7 +631,7 @@ assert resp.get_extra_info('socket') is None -async def test_send_recv_compress_wbit_error(loop, aiohttp_client): +async def test_send_recv_compress_wbit_error(aiohttp_client) -> None: async def handler(request): ws = web.WebSocketResponse() @@ -648,7 +649,7 @@ await client.ws_connect('/', compress=1) -async def test_ws_client_async_for(loop, aiohttp_client): +async def test_ws_client_async_for(aiohttp_client) -> None: items = ['q1', 'q2', 'q3'] async def handler(request): @@ -674,7 +675,7 @@ assert resp.closed -async def test_ws_async_with(loop, aiohttp_server): +async def test_ws_async_with(aiohttp_server) -> None: async def handler(request): ws = web.WebSocketResponse() @@ -689,7 +690,7 @@ server = await aiohttp_server(app) - async with aiohttp.ClientSession(loop=loop) as client: + async with aiohttp.ClientSession() as client: async with client.ws_connect(server.make_url('/')) as ws: await ws.send_str('request') msg = await ws.receive() @@ -698,7 +699,7 @@ assert ws.closed -async def test_ws_async_with_send(loop, aiohttp_server): +async def test_ws_async_with_send(aiohttp_server) -> None: # send_xxx methods have to return awaitable objects async def handler(request): @@ -714,7 +715,7 @@ server = await aiohttp_server(app) - async with aiohttp.ClientSession(loop=loop) as client: + async with aiohttp.ClientSession() as client: async with client.ws_connect(server.make_url('/')) as ws: await ws.send_str('request') msg = await ws.receive() @@ -723,7 +724,7 @@ assert ws.closed -async def test_ws_async_with_shortcut(loop, aiohttp_server): +async def test_ws_async_with_shortcut(aiohttp_server) -> None: async def handler(request): ws = web.WebSocketResponse() @@ -737,7 +738,7 @@ app.router.add_route('GET', '/', handler) server = await aiohttp_server(app) - async with aiohttp.ClientSession(loop=loop) as client: + async with aiohttp.ClientSession() as client: async with client.ws_connect(server.make_url('/')) as ws: await ws.send_str('request') msg = await ws.receive() @@ -746,8 +747,8 @@ assert ws.closed -async def test_closed_async_for(loop, aiohttp_client): - +async def test_closed_async_for(aiohttp_client) -> None: + loop = asyncio.get_event_loop() closed = loop.create_future() async def handler(request): @@ -779,3 +780,52 @@ assert resp.closed await closed + + +async def test_peer_connection_lost(aiohttp_client) -> None: + + async def handler(request): + ws = web.WebSocketResponse() + await ws.prepare(request) + + msg = await ws.receive_str() + assert msg == 'ask' + await ws.send_str('answer') + request.transport.close() + await asyncio.sleep(10) + return ws + + app = web.Application() + app.router.add_route('GET', '/', handler) + client = await aiohttp_client(app) + resp = await client.ws_connect('/') + await resp.send_str('ask') + assert 'answer' == await resp.receive_str() + + msg = await resp.receive() + assert msg.type == aiohttp.WSMsgType.CLOSED + await resp.close() + + +async def test_peer_connection_lost_iter(aiohttp_client) -> None: + + async def handler(request): + ws = web.WebSocketResponse() + await ws.prepare(request) + + msg = await ws.receive_str() + assert msg == 'ask' + await ws.send_str('answer') + request.transport.close() + await asyncio.sleep(100) + return ws + + app = web.Application() + app.router.add_route('GET', '/', handler) + client = await aiohttp_client(app) + resp = await client.ws_connect('/') + await resp.send_str('ask') + async for msg in resp: + assert 'answer' == msg.data + + await resp.close() diff -Nru python-aiohttp-3.1.3/tests/test_client_ws.py python-aiohttp-3.5.1/tests/test_client_ws.py --- python-aiohttp-3.1.3/tests/test_client_ws.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_client_ws.py 2018-12-24 20:58:54.000000000 +0000 @@ -29,7 +29,7 @@ return base64.b64encode(hashlib.sha1(key + WS_KEY).digest()).decode() -async def test_ws_connect(ws_key, loop, key_data): +async def test_ws_connect(ws_key, loop, key_data) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -39,7 +39,7 @@ hdrs.SEC_WEBSOCKET_PROTOCOL: 'chat' } with mock.patch('aiohttp.client.os') as m_os: - with mock.patch('aiohttp.client.ClientSession.get') as m_req: + with mock.patch('aiohttp.client.ClientSession.request') as m_req: m_os.urandom.return_value = key_data m_req.return_value = loop.create_future() m_req.return_value.set_result(resp) @@ -53,11 +53,11 @@ assert hdrs.ORIGIN not in m_req.call_args[1]["headers"] -async def test_ws_connect_with_origin(key_data, loop): +async def test_ws_connect_with_origin(key_data, loop) -> None: resp = mock.Mock() resp.status = 403 with mock.patch('aiohttp.client.os') as m_os: - with mock.patch('aiohttp.client.ClientSession.get') as m_req: + with mock.patch('aiohttp.client.ClientSession.request') as m_req: m_os.urandom.return_value = key_data m_req.return_value = loop.create_future() m_req.return_value.set_result(resp) @@ -71,7 +71,7 @@ assert m_req.call_args[1]["headers"][hdrs.ORIGIN] == origin -async def test_ws_connect_custom_response(loop, ws_key, key_data): +async def test_ws_connect_custom_response(loop, ws_key, key_data) -> None: class CustomResponse(client.ClientWebSocketResponse): def read(self, decode=False): @@ -85,7 +85,7 @@ hdrs.SEC_WEBSOCKET_ACCEPT: ws_key, } with mock.patch('aiohttp.client.os') as m_os: - with mock.patch('aiohttp.client.ClientSession.get') as m_req: + with mock.patch('aiohttp.client.ClientSession.request') as m_req: m_os.urandom.return_value = key_data m_req.return_value = loop.create_future() m_req.return_value.set_result(resp) @@ -97,7 +97,7 @@ assert res.read() == 'customized!' -async def test_ws_connect_err_status(loop, ws_key, key_data): +async def test_ws_connect_err_status(loop, ws_key, key_data) -> None: resp = mock.Mock() resp.status = 500 resp.headers = { @@ -106,7 +106,7 @@ hdrs.SEC_WEBSOCKET_ACCEPT: ws_key } with mock.patch('aiohttp.client.os') as m_os: - with mock.patch('aiohttp.client.ClientSession.get') as m_req: + with mock.patch('aiohttp.client.ClientSession.request') as m_req: m_os.urandom.return_value = key_data m_req.return_value = loop.create_future() m_req.return_value.set_result(resp) @@ -119,7 +119,7 @@ assert ctx.value.message == 'Invalid response status' -async def test_ws_connect_err_upgrade(loop, ws_key, key_data): +async def test_ws_connect_err_upgrade(loop, ws_key, key_data) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -128,7 +128,7 @@ hdrs.SEC_WEBSOCKET_ACCEPT: ws_key } with mock.patch('aiohttp.client.os') as m_os: - with mock.patch('aiohttp.client.ClientSession.get') as m_req: + with mock.patch('aiohttp.client.ClientSession.request') as m_req: m_os.urandom.return_value = key_data m_req.return_value = loop.create_future() m_req.return_value.set_result(resp) @@ -141,7 +141,7 @@ assert ctx.value.message == 'Invalid upgrade header' -async def test_ws_connect_err_conn(loop, ws_key, key_data): +async def test_ws_connect_err_conn(loop, ws_key, key_data) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -150,7 +150,7 @@ hdrs.SEC_WEBSOCKET_ACCEPT: ws_key } with mock.patch('aiohttp.client.os') as m_os: - with mock.patch('aiohttp.client.ClientSession.get') as m_req: + with mock.patch('aiohttp.client.ClientSession.request') as m_req: m_os.urandom.return_value = key_data m_req.return_value = loop.create_future() m_req.return_value.set_result(resp) @@ -163,7 +163,7 @@ assert ctx.value.message == 'Invalid connection header' -async def test_ws_connect_err_challenge(loop, ws_key, key_data): +async def test_ws_connect_err_challenge(loop, ws_key, key_data) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -172,7 +172,7 @@ hdrs.SEC_WEBSOCKET_ACCEPT: 'asdfasdfasdfasdfasdfasdf' } with mock.patch('aiohttp.client.os') as m_os: - with mock.patch('aiohttp.client.ClientSession.get') as m_req: + with mock.patch('aiohttp.client.ClientSession.request') as m_req: m_os.urandom.return_value = key_data m_req.return_value = loop.create_future() m_req.return_value.set_result(resp) @@ -185,7 +185,7 @@ assert ctx.value.message == 'Invalid challenge response' -async def test_ws_connect_common_headers(ws_key, loop, key_data): +async def test_ws_connect_common_headers(ws_key, loop, key_data) -> None: """Emulate a headers dict being reused for a second ws_connect. In this scenario, we need to ensure that the newly generated secret key @@ -193,7 +193,7 @@ """ headers = {} - async def test_connection(): + async def test_connection() -> None: async def mock_get(*args, **kwargs): resp = mock.Mock() @@ -210,7 +210,7 @@ } return resp with mock.patch('aiohttp.client.os') as m_os: - with mock.patch('aiohttp.client.ClientSession.get', + with mock.patch('aiohttp.client.ClientSession.request', side_effect=mock_get) as m_req: m_os.urandom.return_value = key_data @@ -229,7 +229,7 @@ await test_connection() -async def test_close(loop, ws_key, key_data): +async def test_close(loop, ws_key, key_data) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -239,7 +239,7 @@ } with mock.patch('aiohttp.client.WebSocketWriter') as WebSocketWriter: with mock.patch('aiohttp.client.os') as m_os: - with mock.patch('aiohttp.client.ClientSession.get') as m_req: + with mock.patch('aiohttp.client.ClientSession.request') as m_req: m_os.urandom.return_value = key_data m_req.return_value = loop.create_future() m_req.return_value.set_result(resp) @@ -269,7 +269,7 @@ await session.close() -async def test_close_eofstream(loop, ws_key, key_data): +async def test_close_eofstream(loop, ws_key, key_data) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -279,7 +279,7 @@ } with mock.patch('aiohttp.client.WebSocketWriter') as WebSocketWriter: with mock.patch('aiohttp.client.os') as m_os: - with mock.patch('aiohttp.client.ClientSession.get') as m_req: + with mock.patch('aiohttp.client.ClientSession.request') as m_req: m_os.urandom.return_value = key_data m_req.return_value = loop.create_future() m_req.return_value.set_result(resp) @@ -299,7 +299,7 @@ await session.close() -async def test_close_exc(loop, ws_key, key_data): +async def test_close_exc(loop, ws_key, key_data) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -309,7 +309,7 @@ } with mock.patch('aiohttp.client.WebSocketWriter') as WebSocketWriter: with mock.patch('aiohttp.client.os') as m_os: - with mock.patch('aiohttp.client.ClientSession.get') as m_req: + with mock.patch('aiohttp.client.ClientSession.request') as m_req: m_os.urandom.return_value = key_data m_req.return_value = loop.create_future() m_req.return_value.set_result(resp) @@ -331,7 +331,7 @@ await session.close() -async def test_close_exc2(loop, ws_key, key_data): +async def test_close_exc2(loop, ws_key, key_data) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -341,7 +341,7 @@ } with mock.patch('aiohttp.client.WebSocketWriter') as WebSocketWriter: with mock.patch('aiohttp.client.os') as m_os: - with mock.patch('aiohttp.client.ClientSession.get') as m_req: + with mock.patch('aiohttp.client.ClientSession.request') as m_req: m_os.urandom.return_value = key_data m_req.return_value = loop.create_future() m_req.return_value.set_result(resp) @@ -364,7 +364,7 @@ await resp.close() -async def test_send_data_after_close(ws_key, key_data, loop, mocker): +async def test_send_data_after_close(ws_key, key_data, loop, mocker) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -373,7 +373,7 @@ hdrs.SEC_WEBSOCKET_ACCEPT: ws_key, } with mock.patch('aiohttp.client.os') as m_os: - with mock.patch('aiohttp.client.ClientSession.get') as m_req: + with mock.patch('aiohttp.client.ClientSession.request') as m_req: m_os.urandom.return_value = key_data m_req.return_value = loop.create_future() m_req.return_value.set_result(resp) @@ -394,7 +394,7 @@ ws_logger.warning.reset_mock() -async def test_send_data_type_errors(ws_key, key_data, loop): +async def test_send_data_type_errors(ws_key, key_data, loop) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -404,7 +404,7 @@ } with mock.patch('aiohttp.client.WebSocketWriter') as WebSocketWriter: with mock.patch('aiohttp.client.os') as m_os: - with mock.patch('aiohttp.client.ClientSession.get') as m_req: + with mock.patch('aiohttp.client.ClientSession.request') as m_req: m_os.urandom.return_value = key_data m_req.return_value = loop.create_future() m_req.return_value.set_result(resp) @@ -421,7 +421,7 @@ await resp.send_json(set()) -async def test_reader_read_exception(ws_key, key_data, loop): +async def test_reader_read_exception(ws_key, key_data, loop) -> None: hresp = mock.Mock() hresp.status = 101 hresp.headers = { @@ -431,7 +431,7 @@ } with mock.patch('aiohttp.client.WebSocketWriter') as WebSocketWriter: with mock.patch('aiohttp.client.os') as m_os: - with mock.patch('aiohttp.client.ClientSession.get') as m_req: + with mock.patch('aiohttp.client.ClientSession.request') as m_req: m_os.urandom.return_value = key_data m_req.return_value = loop.create_future() m_req.return_value.set_result(hresp) @@ -453,7 +453,7 @@ await session.close() -async def test_receive_runtime_err(loop): +async def test_receive_runtime_err(loop) -> None: resp = client.ClientWebSocketResponse( mock.Mock(), mock.Mock(), mock.Mock(), mock.Mock(), 10.0, True, True, loop) @@ -463,7 +463,7 @@ await resp.receive() -async def test_ws_connect_close_resp_on_err(loop, ws_key, key_data): +async def test_ws_connect_close_resp_on_err(loop, ws_key, key_data) -> None: resp = mock.Mock() resp.status = 500 resp.headers = { @@ -472,7 +472,7 @@ hdrs.SEC_WEBSOCKET_ACCEPT: ws_key } with mock.patch('aiohttp.client.os') as m_os: - with mock.patch('aiohttp.client.ClientSession.get') as m_req: + with mock.patch('aiohttp.client.ClientSession.request') as m_req: m_os.urandom.return_value = key_data m_req.return_value = loop.create_future() m_req.return_value.set_result(resp) @@ -484,7 +484,8 @@ resp.close.assert_called_with() -async def test_ws_connect_non_overlapped_protocols(ws_key, loop, key_data): +async def test_ws_connect_non_overlapped_protocols(ws_key, + loop, key_data) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -494,7 +495,7 @@ hdrs.SEC_WEBSOCKET_PROTOCOL: 'other,another' } with mock.patch('aiohttp.client.os') as m_os: - with mock.patch('aiohttp.client.ClientSession.get') as m_req: + with mock.patch('aiohttp.client.ClientSession.request') as m_req: m_os.urandom.return_value = key_data m_req.return_value = loop.create_future() m_req.return_value.set_result(resp) @@ -506,7 +507,8 @@ assert res.protocol is None -async def test_ws_connect_non_overlapped_protocols_2(ws_key, loop, key_data): +async def test_ws_connect_non_overlapped_protocols_2(ws_key, + loop, key_data) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -516,7 +518,7 @@ hdrs.SEC_WEBSOCKET_PROTOCOL: 'other,another' } with mock.patch('aiohttp.client.os') as m_os: - with mock.patch('aiohttp.client.ClientSession.get') as m_req: + with mock.patch('aiohttp.client.ClientSession.request') as m_req: m_os.urandom.return_value = key_data m_req.return_value = loop.create_future() m_req.return_value.set_result(resp) @@ -531,7 +533,7 @@ del res -async def test_ws_connect_deflate(loop, ws_key, key_data): +async def test_ws_connect_deflate(loop, ws_key, key_data) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -541,7 +543,7 @@ hdrs.SEC_WEBSOCKET_EXTENSIONS: 'permessage-deflate', } with mock.patch('aiohttp.client.os') as m_os: - with mock.patch('aiohttp.client.ClientSession.get') as m_req: + with mock.patch('aiohttp.client.ClientSession.request') as m_req: m_os.urandom.return_value = key_data m_req.return_value = loop.create_future() m_req.return_value.set_result(resp) @@ -553,7 +555,7 @@ assert res.client_notakeover is False -async def test_ws_connect_deflate_per_message(loop, ws_key, key_data): +async def test_ws_connect_deflate_per_message(loop, ws_key, key_data) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -564,7 +566,7 @@ } with mock.patch('aiohttp.client.WebSocketWriter') as WebSocketWriter: with mock.patch('aiohttp.client.os') as m_os: - with mock.patch('aiohttp.client.ClientSession.get') as m_req: + with mock.patch('aiohttp.client.ClientSession.request') as m_req: m_os.urandom.return_value = key_data m_req.return_value = loop.create_future() m_req.return_value.set_result(resp) @@ -586,7 +588,8 @@ await session.close() -async def test_ws_connect_deflate_server_not_support(loop, ws_key, key_data): +async def test_ws_connect_deflate_server_not_support(loop, + ws_key, key_data) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -595,7 +598,7 @@ hdrs.SEC_WEBSOCKET_ACCEPT: ws_key, } with mock.patch('aiohttp.client.os') as m_os: - with mock.patch('aiohttp.client.ClientSession.get') as m_req: + with mock.patch('aiohttp.client.ClientSession.request') as m_req: m_os.urandom.return_value = key_data m_req.return_value = loop.create_future() m_req.return_value.set_result(resp) @@ -607,7 +610,7 @@ assert res.client_notakeover is False -async def test_ws_connect_deflate_notakeover(loop, ws_key, key_data): +async def test_ws_connect_deflate_notakeover(loop, ws_key, key_data) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -618,7 +621,7 @@ 'client_no_context_takeover', } with mock.patch('aiohttp.client.os') as m_os: - with mock.patch('aiohttp.client.ClientSession.get') as m_req: + with mock.patch('aiohttp.client.ClientSession.request') as m_req: m_os.urandom.return_value = key_data m_req.return_value = loop.create_future() m_req.return_value.set_result(resp) @@ -630,7 +633,7 @@ assert res.client_notakeover is True -async def test_ws_connect_deflate_client_wbits(loop, ws_key, key_data): +async def test_ws_connect_deflate_client_wbits(loop, ws_key, key_data) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -641,7 +644,7 @@ 'client_max_window_bits=10', } with mock.patch('aiohttp.client.os') as m_os: - with mock.patch('aiohttp.client.ClientSession.get') as m_req: + with mock.patch('aiohttp.client.ClientSession.request') as m_req: m_os.urandom.return_value = key_data m_req.return_value = loop.create_future() m_req.return_value.set_result(resp) @@ -653,7 +656,8 @@ assert res.client_notakeover is False -async def test_ws_connect_deflate_client_wbits_bad(loop, ws_key, key_data): +async def test_ws_connect_deflate_client_wbits_bad(loop, + ws_key, key_data) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -664,7 +668,7 @@ 'client_max_window_bits=6', } with mock.patch('aiohttp.client.os') as m_os: - with mock.patch('aiohttp.client.ClientSession.get') as m_req: + with mock.patch('aiohttp.client.ClientSession.request') as m_req: m_os.urandom.return_value = key_data m_req.return_value = loop.create_future() m_req.return_value.set_result(resp) @@ -674,7 +678,8 @@ 'http://test.org', compress=15) -async def test_ws_connect_deflate_server_ext_bad(loop, ws_key, key_data): +async def test_ws_connect_deflate_server_ext_bad(loop, + ws_key, key_data) -> None: resp = mock.Mock() resp.status = 101 resp.headers = { @@ -684,7 +689,7 @@ hdrs.SEC_WEBSOCKET_EXTENSIONS: 'permessage-deflate; bad', } with mock.patch('aiohttp.client.os') as m_os: - with mock.patch('aiohttp.client.ClientSession.get') as m_req: + with mock.patch('aiohttp.client.ClientSession.request') as m_req: m_os.urandom.return_value = key_data m_req.return_value = loop.create_future() m_req.return_value.set_result(resp) diff -Nru python-aiohttp-3.1.3/tests/test_connector.py python-aiohttp-3.5.1/tests/test_connector.py --- python-aiohttp-3.1.3/tests/test_connector.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_connector.py 2018-12-24 20:58:54.000000000 +0000 @@ -7,7 +7,9 @@ import platform import socket import ssl +import sys import uuid +from collections import deque from unittest import mock import pytest @@ -15,8 +17,10 @@ import aiohttp from aiohttp import client, web -from aiohttp.client import ClientRequest +from aiohttp.client import ClientRequest, ClientTimeout +from aiohttp.client_reqrep import ConnectionKey from aiohttp.connector import Connection, _DNSCacheTable +from aiohttp.helpers import PY_37 from aiohttp.test_utils import make_mocked_coro, unused_port from aiohttp.tracing import Trace @@ -24,24 +28,24 @@ @pytest.fixture() def key(): """Connection key""" - return ('localhost1', 80, False) + return ConnectionKey('localhost', 80, False, None, None, None, None) @pytest.fixture def key2(): """Connection key""" - return ('localhost2', 80, False) + return ConnectionKey('localhost', 80, False, None, None, None, None) @pytest.fixture def ssl_key(): """Connection key""" - return ('localhost', 80, True) + return ConnectionKey('localhost', 80, True, None, None, None, None) @pytest.fixture -def unix_sockname(tmpdir): - sock_path = tmpdir / 'socket.sock' +def unix_sockname(shorttmpdir): + sock_path = shorttmpdir / 'socket.sock' return str(sock_path) @@ -62,8 +66,72 @@ loop.run_until_complete(runner.cleanup()) -def test_del(loop): - conn = aiohttp.BaseConnector(loop=loop) +def test_connection_del(loop) -> None: + connector = mock.Mock() + key = mock.Mock() + protocol = mock.Mock() + loop.set_debug(0) + conn = Connection(connector, key, protocol, loop=loop) + exc_handler = mock.Mock() + loop.set_exception_handler(exc_handler) + + with pytest.warns(ResourceWarning): + del conn + gc.collect() + + connector._release.assert_called_with( + key, + protocol, + should_close=True + ) + msg = { + 'message': mock.ANY, + 'client_connection': mock.ANY, + } + exc_handler.assert_called_with(loop, msg) + + +def test_connection_del_loop_debug(loop) -> None: + connector = mock.Mock() + key = mock.Mock() + protocol = mock.Mock() + loop.set_debug(1) + conn = Connection(connector, key, protocol, loop=loop) + exc_handler = mock.Mock() + loop.set_exception_handler(exc_handler) + + with pytest.warns(ResourceWarning): + del conn + gc.collect() + + msg = { + 'message': mock.ANY, + 'client_connection': mock.ANY, + 'source_traceback': mock.ANY + } + exc_handler.assert_called_with(loop, msg) + + +def test_connection_del_loop_closed(loop) -> None: + connector = mock.Mock() + key = mock.Mock() + protocol = mock.Mock() + loop.set_debug(1) + conn = Connection(connector, key, protocol, loop=loop) + exc_handler = mock.Mock() + loop.set_exception_handler(exc_handler) + loop.close() + + with pytest.warns(ResourceWarning): + del conn + gc.collect() + + assert not connector._release.called + assert not exc_handler.called + + +async def test_del(loop) -> None: + conn = aiohttp.BaseConnector() proto = mock.Mock(should_close=False) conn._release('a', proto) conns_impl = conn._conns @@ -86,11 +154,11 @@ @pytest.mark.xfail -async def test_del_with_scheduled_cleanup(loop): +async def test_del_with_scheduled_cleanup(loop) -> None: loop.set_debug(True) conn = aiohttp.BaseConnector(loop=loop, keepalive_timeout=0.01) transp = mock.Mock() - conn._conns['a'] = [(transp, 'proto', 123)] + conn._conns['a'] = [(transp, 123)] conns_impl = conn._conns exc_handler = mock.Mock() @@ -112,10 +180,14 @@ exc_handler.assert_called_with(loop, msg) -def test_del_with_closed_loop(loop): - conn = aiohttp.BaseConnector(loop=loop) +@pytest.mark.skipif(sys.implementation.name != 'cpython', + reason="CPython GC is required for the test") +def test_del_with_closed_loop(loop) -> None: + async def make_conn(): + return aiohttp.BaseConnector() + conn = loop.run_until_complete(make_conn()) transp = mock.Mock() - conn._conns['a'] = [(transp, 'proto', 123)] + conn._conns['a'] = [(transp, 123)] conns_impl = conn._conns exc_handler = mock.Mock() @@ -131,7 +203,7 @@ assert exc_handler.called -def test_del_empty_conector(loop): +async def test_del_empty_connector(loop) -> None: conn = aiohttp.BaseConnector(loop=loop) exc_handler = mock.Mock() @@ -142,30 +214,32 @@ assert not exc_handler.called -async def test_create_conn(loop): +async def test_create_conn(loop) -> None: conn = aiohttp.BaseConnector(loop=loop) with pytest.raises(NotImplementedError): - await conn._create_connection(object()) + await conn._create_connection(object(), [], object()) -def test_context_manager(loop): +async def test_context_manager(loop) -> None: conn = aiohttp.BaseConnector(loop=loop) - conn.close = mock.Mock() - with conn as c: - assert conn is c + with pytest.warns(DeprecationWarning): + with conn as c: + assert conn is c + + assert conn.closed - assert conn.close.called +async def test_async_context_manager(loop) -> None: + conn = aiohttp.BaseConnector(loop=loop) -def test_ctor_loop(): - with mock.patch('aiohttp.connector.asyncio') as m_asyncio: - session = aiohttp.BaseConnector() + async with conn as c: + assert conn is c - assert session._loop is m_asyncio.get_event_loop.return_value + assert conn.closed -def test_close(loop): +async def test_close(loop) -> None: proto = mock.Mock() conn = aiohttp.BaseConnector(loop=loop) @@ -178,7 +252,7 @@ assert conn.closed -def test_get(loop): +async def test_get(loop) -> None: conn = aiohttp.BaseConnector(loop=loop) assert conn._get(1) is None @@ -188,30 +262,33 @@ conn.close() -def test_get_expired(loop): +async def test_get_expired(loop) -> None: conn = aiohttp.BaseConnector(loop=loop) - assert conn._get(('localhost', 80, False)) is None + key = ConnectionKey('localhost', 80, False, None, None, None, None) + assert conn._get(key) is None proto = mock.Mock() - conn._conns[('localhost', 80, False)] = [(proto, loop.time() - 1000)] - assert conn._get(('localhost', 80, False)) is None + conn._conns[key] = [(proto, loop.time() - 1000)] + assert conn._get(key) is None assert not conn._conns conn.close() -def test_get_expired_ssl(loop): +async def test_get_expired_ssl(loop) -> None: conn = aiohttp.BaseConnector(loop=loop, enable_cleanup_closed=True) - assert conn._get(('localhost', 80, True)) is None + key = ConnectionKey('localhost', 80, True, None, None, None, None) + assert conn._get(key) is None proto = mock.Mock() - conn._conns[('localhost', 80, True)] = [(proto, loop.time() - 1000)] - assert conn._get(('localhost', 80, True)) is None + transport = proto.transport + conn._conns[key] = [(proto, loop.time() - 1000)] + assert conn._get(key) is None assert not conn._conns - assert conn._cleanup_closed_transports == [proto.close.return_value] + assert conn._cleanup_closed_transports == [transport] conn.close() -def test_release_acquired(loop, key): +async def test_release_acquired(loop, key) -> None: proto = mock.Mock() conn = aiohttp.BaseConnector(loop=loop, limit=5) conn._release_waiter = mock.Mock() @@ -230,7 +307,7 @@ conn.close() -def test_release_acquired_closed(loop, key): +async def test_release_acquired_closed(loop, key) -> None: proto = mock.Mock() conn = aiohttp.BaseConnector(loop=loop, limit=5) conn._release_waiter = mock.Mock() @@ -245,7 +322,7 @@ conn.close() -def test_release(loop, key): +async def test_release(loop, key) -> None: conn = aiohttp.BaseConnector(loop=loop) conn._release_waiter = mock.Mock() @@ -262,20 +339,21 @@ conn.close() -def test_release_ssl_transport(loop, ssl_key): +async def test_release_ssl_transport(loop, ssl_key) -> None: conn = aiohttp.BaseConnector(loop=loop, enable_cleanup_closed=True) conn._release_waiter = mock.Mock() proto = mock.Mock() + transport = proto.transport conn._acquired.add(proto) conn._acquired_per_host[ssl_key].add(proto) conn._release(ssl_key, proto, should_close=True) - assert conn._cleanup_closed_transports == [proto.close.return_value] + assert conn._cleanup_closed_transports == [transport] conn.close() -def test_release_already_closed(loop): +async def test_release_already_closed(loop) -> None: conn = aiohttp.BaseConnector(loop=loop) proto = mock.Mock() @@ -291,18 +369,19 @@ assert not conn._release_acquired.called -def test_release_waiter(loop, key, key2): +async def test_release_waiter_no_limit(loop, key, key2) -> None: # limit is 0 conn = aiohttp.BaseConnector(limit=0, loop=loop) w = mock.Mock() w.done.return_value = False conn._waiters[key].append(w) conn._release_waiter() - assert len(conn._waiters) == 1 - assert not w.done.called + assert len(conn._waiters[key]) == 0 + assert w.done.called conn.close() - # release first available + +async def test_release_waiter_first_available(loop, key, key2) -> None: conn = aiohttp.BaseConnector(loop=loop) w1, w2 = mock.Mock(), mock.Mock() w1.done.return_value = False @@ -314,68 +393,82 @@ not w1.set_result.called and w2.set_result.called) conn.close() - # limited available + +async def test_release_waiter_release_first(loop, key, key2) -> None: conn = aiohttp.BaseConnector(loop=loop, limit=1) w1, w2 = mock.Mock(), mock.Mock() w1.done.return_value = False w2.done.return_value = False - conn._waiters[key] = [w1, w2] + conn._waiters[key] = deque([w1, w2]) conn._release_waiter() assert w1.set_result.called assert not w2.set_result.called conn.close() - # limited available + +async def test_release_waiter_skip_done_waiter(loop, key, key2) -> None: conn = aiohttp.BaseConnector(loop=loop, limit=1) w1, w2 = mock.Mock(), mock.Mock() w1.done.return_value = True w2.done.return_value = False - conn._waiters[key] = [w1, w2] + conn._waiters[key] = deque([w1, w2]) conn._release_waiter() assert not w1.set_result.called - assert not w2.set_result.called + assert w2.set_result.called conn.close() -def test_release_waiter_per_host(loop, key, key2): +async def test_release_waiter_per_host(loop, key, key2) -> None: # no limit conn = aiohttp.BaseConnector(loop=loop, limit=0, limit_per_host=2) w1, w2 = mock.Mock(), mock.Mock() w1.done.return_value = False w2.done.return_value = False - conn._waiters[key] = [w1] - conn._waiters[key2] = [w2] + conn._waiters[key] = deque([w1]) + conn._waiters[key2] = deque([w2]) conn._release_waiter() assert ((w1.set_result.called and not w2.set_result.called) or (not w1.set_result.called and w2.set_result.called)) conn.close() -def test_release_close(loop): +async def test_release_waiter_no_available(loop, key, key2) -> None: + # limit is 0 + conn = aiohttp.BaseConnector(limit=0, loop=loop) + w = mock.Mock() + w.done.return_value = False + conn._waiters[key].append(w) + conn._available_connections = mock.Mock(return_value=0) + conn._release_waiter() + assert len(conn._waiters) == 1 + assert not w.done.called + conn.close() + + +async def test_release_close(loop, key) -> None: conn = aiohttp.BaseConnector(loop=loop) proto = mock.Mock(should_close=True) - key = ('localhost', 80, False) conn._acquired.add(proto) conn._release(key, proto) assert not conn._conns assert proto.close.called -def test__drop_acquire_per_host1(loop): +async def test__drop_acquire_per_host1(loop) -> None: conn = aiohttp.BaseConnector(loop=loop) conn._drop_acquired_per_host(123, 456) assert len(conn._acquired_per_host) == 0 -def test__drop_acquire_per_host2(loop): +async def test__drop_acquire_per_host2(loop) -> None: conn = aiohttp.BaseConnector(loop=loop) conn._acquired_per_host[123].add(456) conn._drop_acquired_per_host(123, 456) assert len(conn._acquired_per_host) == 0 -def test__drop_acquire_per_host3(loop): +async def test__drop_acquire_per_host3(loop) -> None: conn = aiohttp.BaseConnector(loop=loop) conn._acquired_per_host[123].add(456) conn._acquired_per_host[123].add(789) @@ -384,7 +477,7 @@ assert conn._acquired_per_host[123] == {789} -async def test_tcp_connector_certificate_error(loop): +async def test_tcp_connector_certificate_error(loop) -> None: req = ClientRequest('GET', URL('https://127.0.0.1:443'), loop=loop) async def certificate_error(*args, **kwargs): @@ -394,16 +487,14 @@ conn._loop.create_connection = certificate_error with pytest.raises(aiohttp.ClientConnectorCertificateError) as ctx: - await conn.connect(req) + await conn.connect(req, [], ClientTimeout()) assert isinstance(ctx.value, ssl.CertificateError) assert isinstance(ctx.value.certificate_error, ssl.CertificateError) assert isinstance(ctx.value, aiohttp.ClientSSLError) - assert str(ctx.value) == ('Cannot connect to host 127.0.0.1:443 ssl:True ' - '[CertificateError: ()]') -async def test_tcp_connector_multiple_hosts_errors(loop): +async def test_tcp_connector_multiple_hosts_errors(loop) -> None: conn = aiohttp.TCPConnector(loop=loop) ip1 = '192.168.1.1' @@ -457,7 +548,7 @@ if ip == ip4: fingerprint_error = True - tr, pr = mock.Mock(), None + tr, pr = mock.Mock(), mock.Mock() def get_extra_info(param): if param == 'sslcontext': @@ -478,7 +569,7 @@ if ip == ip5: connected = True - tr, pr = mock.Mock(), None + tr, pr = mock.Mock(), mock.Mock() def get_extra_info(param): if param == 'sslcontext': @@ -498,7 +589,7 @@ conn._loop.create_connection = create_connection - await conn.connect(req) + await conn.connect(req, [], ClientTimeout()) assert ips == ips_tried assert os_error @@ -508,7 +599,7 @@ assert connected -async def test_tcp_connector_resolve_host(loop): +async def test_tcp_connector_resolve_host(loop) -> None: conn = aiohttp.TCPConnector(loop=loop, use_dns_cache=True) res = await conn._resolve_host('localhost', 8080) @@ -536,7 +627,7 @@ return coro -async def test_tcp_connector_dns_cache_not_expired(loop, dns_response): +async def test_tcp_connector_dns_cache_not_expired(loop, dns_response) -> None: with mock.patch('aiohttp.connector.DefaultResolver') as m_resolver: conn = aiohttp.TCPConnector( loop=loop, @@ -553,7 +644,7 @@ ) -async def test_tcp_connector_dns_cache_forever(loop, dns_response): +async def test_tcp_connector_dns_cache_forever(loop, dns_response) -> None: with mock.patch('aiohttp.connector.DefaultResolver') as m_resolver: conn = aiohttp.TCPConnector( loop=loop, @@ -570,7 +661,8 @@ ) -async def test_tcp_connector_use_dns_cache_disabled(loop, dns_response): +async def test_tcp_connector_use_dns_cache_disabled(loop, + dns_response) -> None: with mock.patch('aiohttp.connector.DefaultResolver') as m_resolver: conn = aiohttp.TCPConnector(loop=loop, use_dns_cache=False) m_resolver().resolve.side_effect = [dns_response(), dns_response()] @@ -582,7 +674,7 @@ ]) -async def test_tcp_connector_dns_throttle_requests(loop, dns_response): +async def test_tcp_connector_dns_throttle_requests(loop, dns_response) -> None: with mock.patch('aiohttp.connector.DefaultResolver') as m_resolver: conn = aiohttp.TCPConnector( loop=loop, @@ -600,7 +692,8 @@ ) -async def test_tcp_connector_dns_throttle_requests_exception_spread(loop): +async def test_tcp_connector_dns_throttle_requests_exception_spread( + loop) -> None: with mock.patch('aiohttp.connector.DefaultResolver') as m_resolver: conn = aiohttp.TCPConnector( loop=loop, @@ -637,7 +730,7 @@ await f -async def test_tcp_connector_dns_tracing(loop, dns_response): +async def test_tcp_connector_dns_tracing(loop, dns_response) -> None: session = mock.Mock() trace_config_ctx = mock.Mock() on_dns_resolvehost_start = mock.Mock( @@ -712,7 +805,8 @@ ) -async def test_tcp_connector_dns_tracing_cache_disabled(loop, dns_response): +async def test_tcp_connector_dns_tracing_cache_disabled(loop, + dns_response) -> None: session = mock.Mock() trace_config_ctx = mock.Mock() on_dns_resolvehost_start = mock.Mock( @@ -785,7 +879,8 @@ ]) -async def test_tcp_connector_dns_tracing_throttle_requests(loop, dns_response): +async def test_tcp_connector_dns_tracing_throttle_requests( + loop, dns_response) -> None: session = mock.Mock() trace_config_ctx = mock.Mock() on_dns_cache_hit = mock.Mock( @@ -831,20 +926,20 @@ ) -def test_dns_error(loop): +async def test_dns_error(loop) -> None: connector = aiohttp.TCPConnector(loop=loop) connector._resolve_host = make_mocked_coro( raise_exception=OSError('dont take it serious')) req = ClientRequest( 'GET', URL('http://www.python.org'), - loop=loop, - ) + loop=loop) + with pytest.raises(aiohttp.ClientConnectorError): - loop.run_until_complete(connector.connect(req)) + await connector.connect(req, [], ClientTimeout()) -def test_get_pop_empty_conns(loop): +async def test_get_pop_empty_conns(loop) -> None: # see issue #473 conn = aiohttp.BaseConnector(loop=loop) key = ('127.0.0.1', 80, False) @@ -854,11 +949,10 @@ assert not conn._conns -def test_release_close_do_not_add_to_pool(loop): +async def test_release_close_do_not_add_to_pool(loop, key) -> None: # see issue #473 conn = aiohttp.BaseConnector(loop=loop) - key = ('127.0.0.1', 80, False) proto = mock.Mock(should_close=True) conn._acquired.add(proto) @@ -866,11 +960,10 @@ assert not conn._conns -def test_release_close_do_not_delete_existing_connections(loop): - key = ('127.0.0.1', 80, False) +async def test_release_close_do_not_delete_existing_connections(key) -> None: proto1 = mock.Mock() - conn = aiohttp.BaseConnector(loop=loop) + conn = aiohttp.BaseConnector() conn._conns[key] = [(proto1, 1)] proto = mock.Mock(should_close=True) @@ -881,7 +974,7 @@ conn.close() -def test_release_not_started(loop): +async def test_release_not_started(loop) -> None: conn = aiohttp.BaseConnector(loop=loop) proto = mock.Mock(should_close=False) key = 1 @@ -895,30 +988,28 @@ conn.close() -def test_release_not_opened(loop): +async def test_release_not_opened(loop, key) -> None: conn = aiohttp.BaseConnector(loop=loop) proto = mock.Mock() - key = ('localhost', 80, False) conn._acquired.add(proto) conn._release(key, proto) assert proto.close.called -async def test_connect(loop): +async def test_connect(loop, key) -> None: proto = mock.Mock() proto.is_connected.return_value = True - req = ClientRequest('GET', URL('http://host:80'), loop=loop) + req = ClientRequest('GET', URL('http://localhost:80'), loop=loop) conn = aiohttp.BaseConnector(loop=loop) - key = ('host', 80, False) conn._conns[key] = [(proto, loop.time())] conn._create_connection = mock.Mock() conn._create_connection.return_value = loop.create_future() conn._create_connection.return_value.set_result(proto) - connection = await conn.connect(req) + connection = await conn.connect(req, [], ClientTimeout()) assert not conn._create_connection.called assert connection._protocol is proto assert connection.transport is proto.transport @@ -926,7 +1017,7 @@ connection.close() -async def test_connect_tracing(loop): +async def test_connect_tracing(loop) -> None: session = mock.Mock() trace_config_ctx = mock.Mock() on_connection_create_start = mock.Mock( @@ -960,7 +1051,9 @@ conn._create_connection.return_value = loop.create_future() conn._create_connection.return_value.set_result(proto) - await conn.connect(req, traces=traces) + conn2 = await conn.connect(req, traces, ClientTimeout()) + conn2.release() + on_connection_create_start.assert_called_with( session, trace_config_ctx, @@ -973,7 +1066,7 @@ ) -async def test_close_during_connect(loop): +async def test_close_during_connect(loop) -> None: proto = mock.Mock() proto.is_connected.return_value = True @@ -984,7 +1077,7 @@ conn._create_connection = mock.Mock() conn._create_connection.return_value = fut - task = loop.create_task(conn.connect(req)) + task = loop.create_task(conn.connect(req, None, ClientTimeout())) await asyncio.sleep(0, loop=loop) conn.close() @@ -995,7 +1088,7 @@ assert proto.close.called -def test_ctor_cleanup(): +async def test_ctor_cleanup() -> None: loop = mock.Mock() loop.time.return_value = 1.5 conn = aiohttp.BaseConnector( @@ -1004,8 +1097,7 @@ assert conn._cleanup_closed_handle is not None -def test_cleanup(): - key = ('localhost', 80, False) +async def test_cleanup(key) -> None: testset = { key: [(mock.Mock(), 10), (mock.Mock(), 300)], @@ -1025,10 +1117,10 @@ assert conn._cleanup_handle is not None -def test_cleanup_close_ssl_transport(): +async def test_cleanup_close_ssl_transport(ssl_key) -> None: proto = mock.Mock() - key = ('localhost', 80, True) - testset = {key: [(proto, 10)]} + transport = proto.transport + testset = {ssl_key: [(proto, 10)]} loop = mock.Mock() loop.time.return_value = 300 @@ -1039,10 +1131,10 @@ conn._cleanup() assert existing_handle.cancel.called assert conn._conns == {} - assert conn._cleanup_closed_transports == [proto.close.return_value] + assert conn._cleanup_closed_transports == [transport] -def test_cleanup2(): +async def test_cleanup2() -> None: testset = {1: [(mock.Mock(), 300)]} testset[1][0][0].is_connected.return_value = True @@ -1059,8 +1151,7 @@ conn.close() -def test_cleanup3(): - key = ('localhost', 80, False) +async def test_cleanup3(key) -> None: testset = {key: [(mock.Mock(), 290.1), (mock.Mock(), 305.1)]} testset[key][0][0].is_connected.return_value = True @@ -1079,7 +1170,7 @@ conn.close() -def test_cleanup_closed(loop, mocker): +async def test_cleanup_closed(loop, mocker) -> None: if not hasattr(loop, '__dict__'): pytest.skip("can not override loop attributes") @@ -1096,7 +1187,7 @@ assert cleanup_closed_handle.cancel.called -def test_cleanup_closed_disabled(loop, mocker): +async def test_cleanup_closed_disabled(loop, mocker) -> None: conn = aiohttp.BaseConnector( loop=loop, enable_cleanup_closed=False) @@ -1107,7 +1198,7 @@ assert not conn._cleanup_closed_transports -def test_tcp_connector_ctor(loop): +async def test_tcp_connector_ctor(loop) -> None: conn = aiohttp.TCPConnector(loop=loop) assert conn._ssl is None @@ -1115,27 +1206,27 @@ assert conn.family == 0 -def test_tcp_connector_ctor_fingerprint_valid(loop): +async def test_tcp_connector_ctor_fingerprint_valid(loop) -> None: valid = aiohttp.Fingerprint(hashlib.sha256(b"foo").digest()) conn = aiohttp.TCPConnector(ssl=valid, loop=loop) assert conn._ssl is valid -def test_insecure_fingerprint_md5(loop): +async def test_insecure_fingerprint_md5(loop) -> None: with pytest.raises(ValueError): aiohttp.TCPConnector( ssl=aiohttp.Fingerprint(hashlib.md5(b"foo").digest()), loop=loop) -def test_insecure_fingerprint_sha1(loop): +async def test_insecure_fingerprint_sha1(loop) -> None: with pytest.raises(ValueError): aiohttp.TCPConnector( ssl=aiohttp.Fingerprint(hashlib.sha1(b"foo").digest()), loop=loop) -def test_tcp_connector_clear_dns_cache(loop): +async def test_tcp_connector_clear_dns_cache(loop) -> None: conn = aiohttp.TCPConnector(loop=loop) hosts = ['a', 'b'] conn._cached_hosts.add(('localhost', 123), hosts) @@ -1156,32 +1247,32 @@ conn._cached_hosts.next_addrs(('localhost', 124)) -def test_tcp_connector_clear_dns_cache_bad_args(loop): +async def test_tcp_connector_clear_dns_cache_bad_args(loop) -> None: conn = aiohttp.TCPConnector(loop=loop) with pytest.raises(ValueError): conn.clear_dns_cache('localhost') -def test_dont_recreate_ssl_context(loop): +async def test_dont_recreate_ssl_context(loop) -> None: conn = aiohttp.TCPConnector(loop=loop) ctx = conn._make_ssl_context(True) assert ctx is conn._make_ssl_context(True) -def test_dont_recreate_ssl_context2(loop): +async def test_dont_recreate_ssl_context2(loop) -> None: conn = aiohttp.TCPConnector(loop=loop) ctx = conn._make_ssl_context(False) assert ctx is conn._make_ssl_context(False) -def test___get_ssl_context1(loop): +async def test___get_ssl_context1(loop) -> None: conn = aiohttp.TCPConnector(loop=loop) req = mock.Mock() req.is_ssl.return_value = False assert conn._get_ssl_context(req) is None -def test___get_ssl_context2(loop): +async def test___get_ssl_context2(loop) -> None: ctx = ssl.SSLContext() conn = aiohttp.TCPConnector(loop=loop) req = mock.Mock() @@ -1190,7 +1281,7 @@ assert conn._get_ssl_context(req) is ctx -def test___get_ssl_context3(loop): +async def test___get_ssl_context3(loop) -> None: ctx = ssl.SSLContext() conn = aiohttp.TCPConnector(loop=loop, ssl=ctx) req = mock.Mock() @@ -1199,7 +1290,7 @@ assert conn._get_ssl_context(req) is ctx -def test___get_ssl_context4(loop): +async def test___get_ssl_context4(loop) -> None: ctx = ssl.SSLContext() conn = aiohttp.TCPConnector(loop=loop, ssl=ctx) req = mock.Mock() @@ -1208,7 +1299,7 @@ assert conn._get_ssl_context(req) is conn._make_ssl_context(False) -def test___get_ssl_context5(loop): +async def test___get_ssl_context5(loop) -> None: ctx = ssl.SSLContext() conn = aiohttp.TCPConnector(loop=loop, ssl=ctx) req = mock.Mock() @@ -1217,7 +1308,7 @@ assert conn._get_ssl_context(req) is conn._make_ssl_context(False) -def test___get_ssl_context6(loop): +async def test___get_ssl_context6(loop) -> None: conn = aiohttp.TCPConnector(loop=loop) req = mock.Mock() req.is_ssl.return_value = True @@ -1225,7 +1316,7 @@ assert conn._get_ssl_context(req) is conn._make_ssl_context(True) -def test_close_twice(loop): +async def test_close_twice(loop) -> None: proto = mock.Mock() conn = aiohttp.BaseConnector(loop=loop) @@ -1241,7 +1332,7 @@ assert conn.closed -def test_close_cancels_cleanup_handle(loop): +async def test_close_cancels_cleanup_handle(loop) -> None: conn = aiohttp.BaseConnector(loop=loop) conn._release(1, mock.Mock(should_close=False)) assert conn._cleanup_handle is not None @@ -1249,7 +1340,7 @@ assert conn._cleanup_handle is None -def test_close_abort_closed_transports(loop): +async def test_close_abort_closed_transports(loop) -> None: tr = mock.Mock() conn = aiohttp.BaseConnector(loop=loop) @@ -1261,26 +1352,23 @@ assert conn.closed -def test_close_cancels_cleanup_closed_handle(loop): +async def test_close_cancels_cleanup_closed_handle(loop) -> None: conn = aiohttp.BaseConnector(loop=loop, enable_cleanup_closed=True) assert conn._cleanup_closed_handle is not None conn.close() assert conn._cleanup_closed_handle is None -def test_ctor_with_default_loop(): - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) +async def test_ctor_with_default_loop(loop) -> None: conn = aiohttp.BaseConnector() assert loop is conn._loop - loop.close() -async def test_connect_with_limit(loop, key): +async def test_connect_with_limit(loop, key) -> None: proto = mock.Mock() proto.is_connected.return_value = True - req = ClientRequest('GET', URL('http://localhost1:80'), + req = ClientRequest('GET', URL('http://localhost:80'), loop=loop, response_class=mock.Mock()) @@ -1290,7 +1378,7 @@ conn._create_connection.return_value = loop.create_future() conn._create_connection.return_value.set_result(proto) - connection1 = await conn.connect(req) + connection1 = await conn.connect(req, None, ClientTimeout()) assert connection1._protocol == proto assert 1 == len(conn._acquired) @@ -1302,7 +1390,7 @@ async def f(): nonlocal acquired - connection2 = await conn.connect(req) + connection2 = await conn.connect(req, None, ClientTimeout()) acquired = True assert 1 == len(conn._acquired) assert 1 == len(conn._acquired_per_host[key]) @@ -1319,7 +1407,7 @@ conn.close() -async def test_connect_queued_operation_tracing(loop, key): +async def test_connect_queued_operation_tracing(loop, key) -> None: session = mock.Mock() trace_config_ctx = mock.Mock() on_connection_queued_start = mock.Mock( @@ -1356,13 +1444,10 @@ conn._create_connection.return_value = loop.create_future() conn._create_connection.return_value.set_result(proto) - connection1 = await conn.connect(req, traces=traces) + connection1 = await conn.connect(req, traces, ClientTimeout()) async def f(): - connection2 = await conn.connect( - req, - traces=traces - ) + connection2 = await conn.connect(req, traces, ClientTimeout()) on_connection_queued_start.assert_called_with( session, trace_config_ctx, @@ -1382,7 +1467,7 @@ conn.close() -async def test_connect_reuseconn_tracing(loop, key): +async def test_connect_reuseconn_tracing(loop, key) -> None: session = mock.Mock() trace_config_ctx = mock.Mock() on_connection_reuseconn = mock.Mock( @@ -1405,13 +1490,14 @@ proto = mock.Mock() proto.is_connected.return_value = True - req = ClientRequest('GET', URL('http://localhost1:80'), + req = ClientRequest('GET', URL('http://localhost:80'), loop=loop, response_class=mock.Mock()) conn = aiohttp.BaseConnector(loop=loop, limit=1) conn._conns[key] = [(proto, loop.time())] - await conn.connect(req, traces=traces) + conn2 = await conn.connect(req, traces, ClientTimeout()) + conn2.release() on_connection_reuseconn.assert_called_with( session, @@ -1421,11 +1507,11 @@ conn.close() -async def test_connect_with_limit_and_limit_per_host(loop, key): +async def test_connect_with_limit_and_limit_per_host(loop, key) -> None: proto = mock.Mock() proto.is_connected.return_value = True - req = ClientRequest('GET', URL('http://localhost1:80'), loop=loop) + req = ClientRequest('GET', URL('http://localhost:80'), loop=loop) conn = aiohttp.BaseConnector(loop=loop, limit=1000, limit_per_host=1) conn._conns[key] = [(proto, loop.time())] @@ -1434,11 +1520,11 @@ conn._create_connection.return_value.set_result(proto) acquired = False - connection1 = await conn.connect(req) + connection1 = await conn.connect(req, None, ClientTimeout()) async def f(): nonlocal acquired - connection2 = await conn.connect(req) + connection2 = await conn.connect(req, None, ClientTimeout()) acquired = True assert 1 == len(conn._acquired) assert 1 == len(conn._acquired_per_host[key]) @@ -1455,7 +1541,7 @@ conn.close() -async def test_connect_with_no_limit_and_limit_per_host(loop, key): +async def test_connect_with_no_limit_and_limit_per_host(loop, key) -> None: proto = mock.Mock() proto.is_connected.return_value = True @@ -1468,11 +1554,11 @@ conn._create_connection.return_value.set_result(proto) acquired = False - connection1 = await conn.connect(req) + connection1 = await conn.connect(req, None, ClientTimeout()) async def f(): nonlocal acquired - connection2 = await conn.connect(req) + connection2 = await conn.connect(req, None, ClientTimeout()) acquired = True connection2.release() @@ -1487,11 +1573,11 @@ conn.close() -async def test_connect_with_no_limits(loop, key): +async def test_connect_with_no_limits(loop, key) -> None: proto = mock.Mock() proto.is_connected.return_value = True - req = ClientRequest('GET', URL('http://localhost1:80'), loop=loop) + req = ClientRequest('GET', URL('http://localhost:80'), loop=loop) conn = aiohttp.BaseConnector(loop=loop, limit=0, limit_per_host=0) conn._conns[key] = [(proto, loop.time())] @@ -1500,11 +1586,11 @@ conn._create_connection.return_value.set_result(proto) acquired = False - connection1 = await conn.connect(req) + connection1 = await conn.connect(req, None, ClientTimeout()) async def f(): nonlocal acquired - connection2 = await conn.connect(req) + connection2 = await conn.connect(req, None, ClientTimeout()) acquired = True assert 1 == len(conn._acquired) assert 1 == len(conn._acquired_per_host[key]) @@ -1519,7 +1605,7 @@ conn.close() -async def test_connect_with_limit_cancelled(loop): +async def test_connect_with_limit_cancelled(loop) -> None: proto = mock.Mock() proto.is_connected.return_value = True @@ -1533,7 +1619,7 @@ conn._create_connection.return_value = loop.create_future() conn._create_connection.return_value.set_result(proto) - connection = await conn.connect(req) + connection = await conn.connect(req, None, ClientTimeout()) assert connection._protocol == proto assert connection.transport == proto.transport @@ -1541,11 +1627,12 @@ with pytest.raises(asyncio.TimeoutError): # limit exhausted - await asyncio.wait_for(conn.connect(req), 0.01, loop=loop) + await asyncio.wait_for(conn.connect(req, None, ClientTimeout()), + 0.01, loop=loop) connection.close() -async def test_connect_with_capacity_release_waiters(loop): +async def test_connect_with_capacity_release_waiters(loop) -> None: def check_with_exc(err): conn = aiohttp.BaseConnector(limit=1, loop=loop) @@ -1556,7 +1643,7 @@ with pytest.raises(Exception): req = mock.Mock() - yield from conn.connect(req) + yield from conn.connect(req, None, ClientTimeout()) assert not conn._waiters @@ -1565,7 +1652,7 @@ check_with_exc(asyncio.TimeoutError()) -async def test_connect_with_limit_concurrent(loop): +async def test_connect_with_limit_concurrent(loop) -> None: proto = mock.Mock() proto.should_close = False proto.is_connected.return_value = True @@ -1580,7 +1667,7 @@ # Use a real coroutine for _create_connection; a mock would mask # problems that only happen when the method yields. - async def create_connection(req, traces=None): + async def create_connection(req, traces, timeout): nonlocal num_connections num_connections += 1 await asyncio.sleep(0, loop=loop) @@ -1611,7 +1698,7 @@ return num_requests += 1 if not start: - connection = await conn.connect(req) + connection = await conn.connect(req, None, ClientTimeout()) await asyncio.sleep(0, loop=loop) connection.release() tasks = [ @@ -1626,7 +1713,49 @@ assert max_connections == num_connections -async def test_close_with_acquired_connection(loop): +async def test_connect_waiters_cleanup(loop) -> None: + proto = mock.Mock() + proto.is_connected.return_value = True + + req = ClientRequest('GET', URL('http://host:80'), loop=loop) + + conn = aiohttp.BaseConnector(loop=loop, limit=1) + conn._available_connections = mock.Mock(return_value=0) + + t = loop.create_task(conn.connect(req, None, ClientTimeout())) + + await asyncio.sleep(0, loop=loop) + assert conn._waiters.keys() + + t.cancel() + await asyncio.sleep(0, loop=loop) + assert not conn._waiters.keys() + + +async def test_connect_waiters_cleanup_key_error(loop) -> None: + proto = mock.Mock() + proto.is_connected.return_value = True + + req = ClientRequest('GET', URL('http://host:80'), loop=loop) + + conn = aiohttp.BaseConnector(loop=loop, limit=1) + conn._available_connections = mock.Mock(return_value=0) + + t = loop.create_task(conn.connect(req, None, ClientTimeout())) + + await asyncio.sleep(0, loop=loop) + assert conn._waiters.keys() + + # we delete the entry explicitly before the + # canceled connection grabs the loop again, we + # must expect a none failure termination + conn._waiters.clear() + t.cancel() + await asyncio.sleep(0, loop=loop) + assert not conn._waiters.keys() == [] + + +async def test_close_with_acquired_connection(loop) -> None: proto = mock.Mock() proto.is_connected.return_value = True @@ -1639,7 +1768,7 @@ conn._create_connection.return_value = loop.create_future() conn._create_connection.return_value.set_result(proto) - connection = await conn.connect(req) + connection = await conn.connect(req, None, ClientTimeout()) assert 1 == len(conn._acquired) conn.close() @@ -1652,38 +1781,38 @@ assert connection.closed -def test_default_force_close(loop): +async def test_default_force_close(loop) -> None: connector = aiohttp.BaseConnector(loop=loop) assert not connector.force_close -def test_limit_property(loop): +async def test_limit_property(loop) -> None: conn = aiohttp.BaseConnector(loop=loop, limit=15) assert 15 == conn.limit conn.close() -def test_limit_per_host_property(loop): +async def test_limit_per_host_property(loop) -> None: conn = aiohttp.BaseConnector(loop=loop, limit_per_host=15) assert 15 == conn.limit_per_host conn.close() -def test_limit_property_default(loop): +async def test_limit_property_default(loop) -> None: conn = aiohttp.BaseConnector(loop=loop) assert conn.limit == 100 conn.close() -def test_limit_per_host_property_default(loop): +async def test_limit_per_host_property_default(loop) -> None: conn = aiohttp.BaseConnector(loop=loop) assert conn.limit_per_host == 0 conn.close() -def test_force_close_and_explicit_keep_alive(loop): +async def test_force_close_and_explicit_keep_alive(loop) -> None: with pytest.raises(ValueError): aiohttp.BaseConnector(loop=loop, keepalive_timeout=30, force_close=True) @@ -1697,18 +1826,18 @@ assert conn -async def test_error_on_connection(loop): +async def test_error_on_connection(loop, key) -> None: conn = aiohttp.BaseConnector(limit=1, loop=loop) req = mock.Mock() - req.connection_key = 'key' + req.connection_key = key proto = mock.Mock() i = 0 fut = loop.create_future() exc = OSError() - async def create_connection(req, traces=None): + async def create_connection(req, traces, timeout): nonlocal i i += 1 if i == 1: @@ -1719,38 +1848,61 @@ conn._create_connection = create_connection - t1 = loop.create_task(conn.connect(req)) - t2 = loop.create_task(conn.connect(req)) + t1 = loop.create_task(conn.connect(req, None, ClientTimeout())) + t2 = loop.create_task(conn.connect(req, None, ClientTimeout())) await asyncio.sleep(0, loop=loop) assert not t1.done() assert not t2.done() - assert len(conn._acquired_per_host['key']) == 1 + assert len(conn._acquired_per_host[key]) == 1 fut.set_result(None) with pytest.raises(OSError): await t1 ret = await t2 - assert len(conn._acquired_per_host['key']) == 1 + assert len(conn._acquired_per_host[key]) == 1 - assert ret._key == 'key' + assert ret._key == key assert ret.protocol == proto assert proto in conn._acquired + ret.release() -async def test_error_on_connection_with_cancelled_waiter(loop): +async def test_cancelled_waiter(loop) -> None: conn = aiohttp.BaseConnector(limit=1, loop=loop) - req = mock.Mock() req.connection_key = 'key' proto = mock.Mock() + + async def create_connection(req, traces=None): + await asyncio.sleep(1) + return proto + + conn._create_connection = create_connection + + conn._acquired.add(proto) + + conn2 = loop.create_task(conn.connect(req, None, ClientTimeout())) + await asyncio.sleep(0, loop=loop) + conn2.cancel() + + with pytest.raises(asyncio.CancelledError): + await conn2 + + +async def test_error_on_connection_with_cancelled_waiter(loop, key) -> None: + conn = aiohttp.BaseConnector(limit=1, loop=loop) + + req = mock.Mock() + req.connection_key = key + proto = mock.Mock() i = 0 fut1 = loop.create_future() fut2 = loop.create_future() exc = OSError() - async def create_connection(req, traces=None): + async def create_connection(req, traces, timeout): nonlocal i i += 1 if i == 1: @@ -1763,13 +1915,13 @@ conn._create_connection = create_connection - t1 = loop.create_task(conn.connect(req)) - t2 = loop.create_task(conn.connect(req)) - t3 = loop.create_task(conn.connect(req)) + t1 = loop.create_task(conn.connect(req, None, ClientTimeout())) + t2 = loop.create_task(conn.connect(req, None, ClientTimeout())) + t3 = loop.create_task(conn.connect(req, None, ClientTimeout())) await asyncio.sleep(0, loop=loop) assert not t1.done() assert not t2.done() - assert len(conn._acquired_per_host['key']) == 1 + assert len(conn._acquired_per_host[key]) == 1 fut1.set_result(None) fut2.cancel() @@ -1780,14 +1932,15 @@ await t2 ret = await t3 - assert len(conn._acquired_per_host['key']) == 1 + assert len(conn._acquired_per_host[key]) == 1 - assert ret._key == 'key' + assert ret._key == key assert ret.protocol == proto assert proto in conn._acquired + ret.release() -async def test_tcp_connector(aiohttp_client, loop): +async def test_tcp_connector(aiohttp_client, loop) -> None: async def handler(request): return web.Response() @@ -1802,38 +1955,36 @@ @pytest.mark.skipif(not hasattr(socket, 'AF_UNIX'), reason="requires unix socket") -def test_unix_connector_not_found(loop): +async def test_unix_connector_not_found(loop) -> None: connector = aiohttp.UnixConnector('/' + uuid.uuid4().hex, loop=loop) req = ClientRequest( 'GET', URL('http://www.python.org'), - loop=loop, - ) + loop=loop) with pytest.raises(aiohttp.ClientConnectorError): - loop.run_until_complete(connector.connect(req)) + await connector.connect(req, None, ClientTimeout()) @pytest.mark.skipif(not hasattr(socket, 'AF_UNIX'), reason="requires unix socket") -def test_unix_connector_permission(loop): +async def test_unix_connector_permission(loop) -> None: loop.create_unix_connection = make_mocked_coro( raise_exception=PermissionError()) connector = aiohttp.UnixConnector('/' + uuid.uuid4().hex, loop=loop) req = ClientRequest( 'GET', URL('http://www.python.org'), - loop=loop, - ) + loop=loop) with pytest.raises(aiohttp.ClientConnectorError): - loop.run_until_complete(connector.connect(req)) + await connector.connect(req, None, ClientTimeout()) -def test_default_use_dns_cache(loop): - conn = aiohttp.TCPConnector(loop=loop) +async def test_default_use_dns_cache() -> None: + conn = aiohttp.TCPConnector() assert conn.use_dns_cache -async def test_resolver_not_called_with_address_is_ip(loop): +async def test_resolver_not_called_with_address_is_ip(loop) -> None: resolver = mock.MagicMock() connector = aiohttp.TCPConnector(resolver=resolver) @@ -1843,12 +1994,12 @@ response_class=mock.Mock()) with pytest.raises(OSError): - await connector.connect(req) + await connector.connect(req, None, ClientTimeout()) resolver.resolve.assert_not_called() -async def test_tcp_connector_raise_connector_ssl_error(aiohttp_server): +async def test_tcp_connector_raise_connector_ssl_error(aiohttp_server) -> None: async def handler(request): return web.Response() @@ -1869,17 +2020,25 @@ session = aiohttp.ClientSession(connector=conn) url = srv.make_url('/') - with pytest.raises(aiohttp.ClientConnectorSSLError) as ctx: - print(url) + if PY_37: + err = aiohttp.ClientConnectorCertificateError + else: + err = aiohttp.ClientConnectorSSLError + with pytest.raises(err) as ctx: await session.get(url) - assert isinstance(ctx.value.os_error, ssl.SSLError) - assert isinstance(ctx.value, aiohttp.ClientSSLError) + if PY_37: + assert isinstance(ctx.value, aiohttp.ClientConnectorCertificateError) + assert isinstance(ctx.value.certificate_error, ssl.SSLError) + else: + assert isinstance(ctx.value, aiohttp.ClientSSLError) + assert isinstance(ctx.value.os_error, ssl.SSLError) await session.close() -async def test_tcp_connector_do_not_raise_connector_ssl_error(aiohttp_server): +async def test_tcp_connector_do_not_raise_connector_ssl_error( + aiohttp_server) -> None: async def handler(request): return web.Response() @@ -1916,7 +2075,7 @@ conn.close() -async def test_tcp_connector_uses_provided_local_addr(aiohttp_server): +async def test_tcp_connector_uses_provided_local_addr(aiohttp_server) -> None: async def handler(request): return web.Response() @@ -1943,7 +2102,7 @@ @pytest.mark.skipif(not hasattr(socket, 'AF_UNIX'), reason='requires UNIX sockets') -async def test_unix_connector(unix_server, unix_sockname): +async def test_unix_connector(unix_server, unix_sockname) -> None: async def handler(request): return web.Response() @@ -1969,7 +2128,7 @@ def dns_cache_table(self): return _DNSCacheTable() - def test_next_addrs_basic(self, dns_cache_table): + def test_next_addrs_basic(self, dns_cache_table) -> None: dns_cache_table.add('localhost', ['127.0.0.1']) dns_cache_table.add('foo', ['127.0.0.2']) @@ -1980,34 +2139,34 @@ with pytest.raises(KeyError): dns_cache_table.next_addrs('no-such-host') - def test_remove(self, dns_cache_table): + def test_remove(self, dns_cache_table) -> None: dns_cache_table.add('localhost', ['127.0.0.1']) dns_cache_table.remove('localhost') with pytest.raises(KeyError): dns_cache_table.next_addrs('localhost') - def test_clear(self, dns_cache_table): + def test_clear(self, dns_cache_table) -> None: dns_cache_table.add('localhost', ['127.0.0.1']) dns_cache_table.clear() with pytest.raises(KeyError): dns_cache_table.next_addrs('localhost') - def test_not_expired_ttl_None(self, dns_cache_table): + def test_not_expired_ttl_None(self, dns_cache_table) -> None: dns_cache_table.add('localhost', ['127.0.0.1']) assert not dns_cache_table.expired('localhost') - def test_not_expired_ttl(self): + def test_not_expired_ttl(self) -> None: dns_cache_table = _DNSCacheTable(ttl=0.1) dns_cache_table.add('localhost', ['127.0.0.1']) assert not dns_cache_table.expired('localhost') - async def test_expired_ttl(self, loop): + async def test_expired_ttl(self, loop) -> None: dns_cache_table = _DNSCacheTable(ttl=0.01) dns_cache_table.add('localhost', ['127.0.0.1']) await asyncio.sleep(0.02, loop=loop) assert dns_cache_table.expired('localhost') - def test_next_addrs(self, dns_cache_table): + def test_next_addrs(self, dns_cache_table) -> None: dns_cache_table.add('foo', ['127.0.0.1', '127.0.0.2', '127.0.0.3']) # Each calls to next_addrs return the hosts using @@ -2024,7 +2183,7 @@ addrs = dns_cache_table.next_addrs('foo') assert addrs == ['127.0.0.1', '127.0.0.2', '127.0.0.3'] - def test_next_addrs_single(self, dns_cache_table): + def test_next_addrs_single(self, dns_cache_table) -> None: dns_cache_table.add('foo', ['127.0.0.1']) addrs = dns_cache_table.next_addrs('foo') diff -Nru python-aiohttp-3.1.3/tests/test_cookiejar.py python-aiohttp-3.5.1/tests/test_cookiejar.py --- python-aiohttp-3.1.3/tests/test_cookiejar.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_cookiejar.py 2018-12-24 20:58:54.000000000 +0000 @@ -54,7 +54,7 @@ ) -def test_date_parsing(): +def test_date_parsing() -> None: parse_func = CookieJar._parse_date utc = datetime.timezone.utc @@ -98,7 +98,7 @@ assert parse_func("Tue, 1 Jan 1970 77:88:99 GMT") is None -def test_domain_matching(): +def test_domain_matching() -> None: test_func = CookieJar._is_domain_match assert test_func("test.com", "test.com") @@ -111,7 +111,7 @@ assert not test_func("test.com", "127.0.0.1") -def test_path_matching(): +def test_path_matching() -> None: test_func = CookieJar._is_path_match assert test_func("/", "") @@ -133,7 +133,7 @@ assert not test_func("/different-folder/", "/folder/") -def test_constructor(loop, cookies_to_send, cookies_to_receive): +async def test_constructor(loop, cookies_to_send, cookies_to_receive) -> None: jar = CookieJar(loop=loop) jar.update_cookies(cookies_to_send) jar_cookies = SimpleCookie() @@ -144,7 +144,7 @@ assert jar._loop is loop -def test_save_load(loop, cookies_to_send, cookies_to_receive): +async def test_save_load(loop, cookies_to_send, cookies_to_receive) -> None: file_path = tempfile.mkdtemp() + '/aiohttp.test.cookie' # export cookie jar @@ -163,7 +163,7 @@ assert jar_test == cookies_to_receive -def test_update_cookie_with_unicode_domain(loop): +async def test_update_cookie_with_unicode_domain(loop) -> None: cookies = ( "idna-domain-first=first; Domain=xn--9caa.com; Path=/;", "idna-domain-second=second; Domain=xn--9caa.com; Path=/;", @@ -180,8 +180,8 @@ assert jar_test == SimpleCookie(" ".join(cookies)) -def test_filter_cookie_with_unicode_domain(loop): - jar = CookieJar(loop=loop) +async def test_filter_cookie_with_unicode_domain(loop) -> None: + jar = CookieJar() jar.update_cookies(SimpleCookie( "idna-domain-first=first; Domain=xn--9caa.com; Path=/; " )) @@ -189,13 +189,7 @@ assert len(jar.filter_cookies(URL("http://xn--9caa.com"))) == 1 -def test_ctor_ith_default_loop(loop): - asyncio.set_event_loop(loop) - jar = CookieJar() - assert jar._loop is loop - - -def test_domain_filter_ip_cookie_send(loop): +async def test_domain_filter_ip_cookie_send(loop) -> None: jar = CookieJar(loop=loop) cookies = SimpleCookie( "shared-cookie=first; " @@ -226,14 +220,14 @@ assert cookies_sent == 'Cookie: shared-cookie=first' -def test_domain_filter_ip_cookie_receive(loop, cookies_to_receive): - jar = CookieJar(loop=loop) +async def test_domain_filter_ip_cookie_receive(cookies_to_receive) -> None: + jar = CookieJar() jar.update_cookies(cookies_to_receive, URL("http://1.2.3.4/")) assert len(jar) == 0 -def test_preserving_ip_domain_cookies(loop): +async def test_preserving_ip_domain_cookies(loop) -> None: jar = CookieJar(loop=loop, unsafe=True) jar.update_cookies(SimpleCookie( "shared-cookie=first; " @@ -245,7 +239,7 @@ 'Cookie: shared-cookie=first') -def test_preserving_quoted_cookies(loop): +async def test_preserving_quoted_cookies(loop) -> None: jar = CookieJar(loop=loop, unsafe=True) jar.update_cookies(SimpleCookie( "ip-cookie=\"second\"; Domain=127.0.0.1;" @@ -255,7 +249,7 @@ assert cookies_sent == 'Cookie: ip-cookie=\"second\"' -def test_ignore_domain_ending_with_dot(loop): +async def test_ignore_domain_ending_with_dot(loop) -> None: jar = CookieJar(loop=loop, unsafe=True) jar.update_cookies(SimpleCookie("cookie=val; Domain=example.com.;"), URL("http://www.example.com")) @@ -272,7 +266,9 @@ asyncio.set_event_loop(None) # N.B. those need to be overridden in child test cases - self.jar = CookieJar(loop=self.loop) + async def make_jar(): + return CookieJar() + self.jar = self.loop.run_until_complete(make_jar()) def tearDown(self): self.loop.close() @@ -333,7 +329,9 @@ "wrong-path-cookie=nineth; Domain=pathtest.com; Path=somepath;" ) - self.jar = CookieJar(loop=self.loop) + async def make_jar(): + return CookieJar() + self.jar = self.loop.run_until_complete(make_jar()) def timed_request(self, url, update_time, send_time): with mock.patch.object(self.loop, 'time', return_value=update_time): @@ -346,7 +344,7 @@ return cookies_sent - def test_domain_filter_same_host(self): + def test_domain_filter_same_host(self) -> None: cookies_sent, cookies_received = ( self.request_reply_with_same_url("http://example.com/")) @@ -362,7 +360,7 @@ "dotted-domain-cookie" }) - def test_domain_filter_same_host_and_subdomain(self): + def test_domain_filter_same_host_and_subdomain(self) -> None: cookies_sent, cookies_received = ( self.request_reply_with_same_url("http://test1.example.com/")) @@ -380,7 +378,7 @@ "dotted-domain-cookie" }) - def test_domain_filter_same_host_diff_subdomain(self): + def test_domain_filter_same_host_diff_subdomain(self) -> None: cookies_sent, cookies_received = ( self.request_reply_with_same_url("http://different.example.com/")) @@ -396,7 +394,7 @@ "dotted-domain-cookie" }) - def test_domain_filter_diff_host(self): + def test_domain_filter_diff_host(self) -> None: cookies_sent, cookies_received = ( self.request_reply_with_same_url("http://different.org/")) @@ -410,7 +408,7 @@ "different-domain-cookie" }) - def test_domain_filter_host_only(self): + def test_domain_filter_host_only(self) -> None: self.jar.update_cookies(self.cookies_to_receive, URL("http://example.com/")) @@ -420,7 +418,7 @@ cookies_sent = self.jar.filter_cookies(URL("http://different.org/")) self.assertNotIn("unconstrained-cookie", set(cookies_sent.keys())) - def test_secure_filter(self): + def test_secure_filter(self) -> None: cookies_sent, _ = ( self.request_reply_with_same_url("http://secure.com/")) @@ -436,7 +434,7 @@ "secure-cookie" }) - def test_path_filter_root(self): + def test_path_filter_root(self) -> None: cookies_sent, _ = ( self.request_reply_with_same_url("http://pathtest.com/")) @@ -446,7 +444,7 @@ "path1-cookie" }) - def test_path_filter_folder(self): + def test_path_filter_folder(self) -> None: cookies_sent, _ = ( self.request_reply_with_same_url("http://pathtest.com/one/")) @@ -458,7 +456,7 @@ "path2-cookie" }) - def test_path_filter_file(self): + def test_path_filter_file(self) -> None: cookies_sent, _ = self.request_reply_with_same_url( "http://pathtest.com/one/two") @@ -471,7 +469,7 @@ "path3-cookie" }) - def test_path_filter_subfolder(self): + def test_path_filter_subfolder(self) -> None: cookies_sent, _ = self.request_reply_with_same_url( "http://pathtest.com/one/two/") @@ -485,7 +483,7 @@ "path4-cookie" }) - def test_path_filter_subsubfolder(self): + def test_path_filter_subsubfolder(self) -> None: cookies_sent, _ = self.request_reply_with_same_url( "http://pathtest.com/one/two/three/") @@ -499,7 +497,7 @@ "path4-cookie" }) - def test_path_filter_different_folder(self): + def test_path_filter_different_folder(self) -> None: cookies_sent, _ = ( self.request_reply_with_same_url("http://pathtest.com/hundred/")) @@ -510,7 +508,7 @@ "path1-cookie" }) - def test_path_value(self): + def test_path_value(self) -> None: _, cookies_received = ( self.request_reply_with_same_url("http://pathtest.com/")) @@ -525,7 +523,7 @@ self.assertEqual(cookies_received["path-cookie"]["path"], "/somepath") self.assertEqual(cookies_received["wrong-path-cookie"]["path"], "/") - def test_expires(self): + def test_expires(self) -> None: ts_before = datetime.datetime( 1975, 1, 1, tzinfo=datetime.timezone.utc).timestamp() @@ -547,7 +545,7 @@ "shared-cookie" }) - def test_max_age(self): + def test_max_age(self) -> None: cookies_sent = self.timed_request( "http://maxagetest.com/", 1000, 1000) @@ -563,7 +561,7 @@ "shared-cookie" }) - def test_invalid_values(self): + def test_invalid_values(self) -> None: cookies_sent, cookies_received = ( self.request_reply_with_same_url("http://invalid-values.com/")) @@ -579,7 +577,7 @@ cookie = cookies_sent["invalid-expires-cookie"] self.assertEqual(cookie["expires"], "") - def test_cookie_not_expired_when_added_after_removal(self): + def test_cookie_not_expired_when_added_after_removal(self) -> None: """Test case for https://github.com/aio-libs/aiohttp/issues/2084""" timestamps = [533588.993, 533588.993, 533588.993, 533588.993, 533589.093, 533589.093] @@ -588,7 +586,9 @@ loop.time.side_effect = itertools.chain( timestamps, itertools.cycle([timestamps[-1]])) - jar = CookieJar(unsafe=True, loop=loop) + async def make_jar(): + return CookieJar(unsafe=True) + jar = self.loop.run_until_complete(make_jar()) # Remove `foo` cookie. jar.update_cookies(SimpleCookie('foo=""; Max-Age=0')) # Set `foo` cookie to `bar`. @@ -598,13 +598,13 @@ assert len(jar) == 1 -def test_dummy_cookie_jar(loop): +async def test_dummy_cookie_jar() -> None: cookie = SimpleCookie('foo=bar; Domain=example.com;') - dummy_jar = DummyCookieJar(loop=loop) + dummy_jar = DummyCookieJar() assert len(dummy_jar) == 0 dummy_jar.update_cookies(cookie) assert len(dummy_jar) == 0 with pytest.raises(StopIteration): next(iter(dummy_jar)) - assert dummy_jar.filter_cookies(URL("http://example.com/")) is None + assert not dummy_jar.filter_cookies(URL("http://example.com/")) dummy_jar.clear() diff -Nru python-aiohttp-3.1.3/tests/test_flowcontrol_streams.py python-aiohttp-3.5.1/tests/test_flowcontrol_streams.py --- python-aiohttp-3.1.3/tests/test_flowcontrol_streams.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_flowcontrol_streams.py 2018-12-24 20:58:54.000000000 +0000 @@ -26,13 +26,13 @@ class TestFlowControlStreamReader: - async def test_read(self, stream): + async def test_read(self, stream) -> None: stream.feed_data(b'da', 2) res = await stream.read(1) assert res == b'd' assert not stream._protocol.resume_reading.called - async def test_read_resume_paused(self, stream): + async def test_read_resume_paused(self, stream) -> None: stream.feed_data(b'test', 4) stream._protocol._reading_paused = True @@ -40,40 +40,40 @@ assert res == b't' assert stream._protocol.pause_reading.called - async def test_readline(self, stream): + async def test_readline(self, stream) -> None: stream.feed_data(b'd\n', 5) res = await stream.readline() assert res == b'd\n' assert not stream._protocol.resume_reading.called - async def test_readline_resume_paused(self, stream): + async def test_readline_resume_paused(self, stream) -> None: stream._protocol._reading_paused = True stream.feed_data(b'd\n', 5) res = await stream.readline() assert res == b'd\n' assert stream._protocol.resume_reading.called - async def test_readany(self, stream): + async def test_readany(self, stream) -> None: stream.feed_data(b'data', 4) res = await stream.readany() assert res == b'data' assert not stream._protocol.resume_reading.called - async def test_readany_resume_paused(self, stream): + async def test_readany_resume_paused(self, stream) -> None: stream._protocol._reading_paused = True stream.feed_data(b'data', 4) res = await stream.readany() assert res == b'data' assert stream._protocol.resume_reading.called - async def test_readchunk(self, stream): + async def test_readchunk(self, stream) -> None: stream.feed_data(b'data', 4) res, end_of_http_chunk = await stream.readchunk() assert res == b'data' assert not end_of_http_chunk assert not stream._protocol.resume_reading.called - async def test_readchunk_resume_paused(self, stream): + async def test_readchunk_resume_paused(self, stream) -> None: stream._protocol._reading_paused = True stream.feed_data(b'data', 4) res, end_of_http_chunk = await stream.readchunk() @@ -81,18 +81,18 @@ assert not end_of_http_chunk assert stream._protocol.resume_reading.called - async def test_readexactly(self, stream): + async def test_readexactly(self, stream) -> None: stream.feed_data(b'data', 4) res = await stream.readexactly(3) assert res == b'dat' assert not stream._protocol.resume_reading.called - async def test_feed_data(self, stream): + async def test_feed_data(self, stream) -> None: stream._protocol._reading_paused = False stream.feed_data(b'datadata', 8) assert stream._protocol.pause_reading.called - async def test_read_nowait(self, stream): + async def test_read_nowait(self, stream) -> None: stream._protocol._reading_paused = True stream.feed_data(b'data1', 5) stream.feed_data(b'data2', 5) @@ -117,13 +117,13 @@ class TestFlowControlDataQueue: - def test_feed_pause(self, buffer): + def test_feed_pause(self, buffer) -> None: buffer._protocol._reading_paused = False buffer.feed_data(object(), 100) assert buffer._protocol.pause_reading.called - async def test_resume_on_read(self, buffer): + async def test_resume_on_read(self, buffer) -> None: buffer.feed_data(object(), 100) buffer._protocol._reading_paused = True diff -Nru python-aiohttp-3.1.3/tests/test_formdata.py python-aiohttp-3.5.1/tests/test_formdata.py --- python-aiohttp-3.1.3/tests/test_formdata.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_formdata.py 2018-12-24 20:58:54.000000000 +0000 @@ -21,7 +21,7 @@ return writer -def test_formdata_multipart(buf, writer): +def test_formdata_multipart(buf, writer) -> None: form = FormData() assert not form.is_multipart @@ -29,24 +29,24 @@ assert form.is_multipart -def test_invalid_formdata_payload(): +def test_invalid_formdata_payload() -> None: form = FormData() form.add_field('test', object(), filename='test.txt') with pytest.raises(TypeError): form() -def test_invalid_formdata_params(): +def test_invalid_formdata_params() -> None: with pytest.raises(TypeError): FormData('asdasf') -def test_invalid_formdata_params2(): +def test_invalid_formdata_params2() -> None: with pytest.raises(TypeError): FormData('as') # 2-char str is not allowed -def test_invalid_formdata_content_type(): +def test_invalid_formdata_content_type() -> None: form = FormData() invalid_vals = [0, 0.1, {}, [], b'foo'] for invalid_val in invalid_vals: @@ -54,7 +54,7 @@ form.add_field('foo', 'bar', content_type=invalid_val) -def test_invalid_formdata_filename(): +def test_invalid_formdata_filename() -> None: form = FormData() invalid_vals = [0, 0.1, {}, [], b'foo'] for invalid_val in invalid_vals: @@ -62,7 +62,7 @@ form.add_field('foo', 'bar', filename=invalid_val) -def test_invalid_formdata_content_transfer_encoding(): +def test_invalid_formdata_content_transfer_encoding() -> None: form = FormData() invalid_vals = [0, 0.1, {}, [], b'foo'] for invalid_val in invalid_vals: @@ -72,7 +72,7 @@ content_transfer_encoding=invalid_val) -async def test_formdata_field_name_is_quoted(buf, writer): +async def test_formdata_field_name_is_quoted(buf, writer) -> None: form = FormData(charset="ascii") form.add_field("emails[]", "xxx@x.co", content_type="multipart/form-data") payload = form() @@ -80,7 +80,7 @@ assert b'name="emails%5B%5D"' in buf -async def test_formdata_field_name_is_not_quoted(buf, writer): +async def test_formdata_field_name_is_not_quoted(buf, writer) -> None: form = FormData(quote_fields=False, charset="ascii") form.add_field("emails[]", "xxx@x.co", content_type="multipart/form-data") payload = form() diff -Nru python-aiohttp-3.1.3/tests/test_frozenlist.py python-aiohttp-3.5.1/tests/test_frozenlist.py --- python-aiohttp-3.1.3/tests/test_frozenlist.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_frozenlist.py 2018-12-24 20:58:54.000000000 +0000 @@ -6,216 +6,216 @@ class FrozenListMixin: - FrozenList = None + FrozenList = NotImplemented SKIP_METHODS = {'__abstractmethods__', '__slots__'} - def test_subclass(self): + def test_subclass(self) -> None: assert issubclass(self.FrozenList, MutableSequence) - def test_iface(self): + def test_iface(self) -> None: for name in set(dir(MutableSequence)) - self.SKIP_METHODS: if name.startswith('_') and not name.endswith('_'): continue assert hasattr(self.FrozenList, name) - def test_ctor_default(self): + def test_ctor_default(self) -> None: _list = self.FrozenList([]) assert not _list.frozen - def test_ctor(self): + def test_ctor(self) -> None: _list = self.FrozenList([1]) assert not _list.frozen - def test_ctor_copy_list(self): + def test_ctor_copy_list(self) -> None: orig = [1] _list = self.FrozenList(orig) del _list[0] assert _list != orig - def test_freeze(self): + def test_freeze(self) -> None: _list = self.FrozenList() _list.freeze() assert _list.frozen - def test_repr(self): + def test_repr(self) -> None: _list = self.FrozenList([1]) assert repr(_list) == '' _list.freeze() assert repr(_list) == '' - def test_getitem(self): + def test_getitem(self) -> None: _list = self.FrozenList([1, 2]) assert _list[1] == 2 - def test_setitem(self): + def test_setitem(self) -> None: _list = self.FrozenList([1, 2]) _list[1] = 3 assert _list[1] == 3 - def test_delitem(self): + def test_delitem(self) -> None: _list = self.FrozenList([1, 2]) del _list[0] assert len(_list) == 1 assert _list[0] == 2 - def test_len(self): + def test_len(self) -> None: _list = self.FrozenList([1]) assert len(_list) == 1 - def test_iter(self): + def test_iter(self) -> None: _list = self.FrozenList([1, 2]) assert list(iter(_list)) == [1, 2] - def test_reversed(self): + def test_reversed(self) -> None: _list = self.FrozenList([1, 2]) assert list(reversed(_list)) == [2, 1] - def test_eq(self): + def test_eq(self) -> None: _list = self.FrozenList([1]) assert _list == [1] - def test_ne(self): + def test_ne(self) -> None: _list = self.FrozenList([1]) assert _list != [2] - def test_le(self): + def test_le(self) -> None: _list = self.FrozenList([1]) assert _list <= [1] - def test_lt(self): + def test_lt(self) -> None: _list = self.FrozenList([1]) assert _list <= [3] - def test_ge(self): + def test_ge(self) -> None: _list = self.FrozenList([1]) assert _list >= [1] - def test_gt(self): + def test_gt(self) -> None: _list = self.FrozenList([2]) assert _list > [1] - def test_insert(self): + def test_insert(self) -> None: _list = self.FrozenList([2]) _list.insert(0, 1) assert _list == [1, 2] - def test_frozen_setitem(self): + def test_frozen_setitem(self) -> None: _list = self.FrozenList([1]) _list.freeze() with pytest.raises(RuntimeError): _list[0] = 2 - def test_frozen_delitem(self): + def test_frozen_delitem(self) -> None: _list = self.FrozenList([1]) _list.freeze() with pytest.raises(RuntimeError): del _list[0] - def test_frozen_insert(self): + def test_frozen_insert(self) -> None: _list = self.FrozenList([1]) _list.freeze() with pytest.raises(RuntimeError): _list.insert(0, 2) - def test_contains(self): + def test_contains(self) -> None: _list = self.FrozenList([2]) assert 2 in _list - def test_iadd(self): + def test_iadd(self) -> None: _list = self.FrozenList([1]) _list += [2] assert _list == [1, 2] - def test_iadd_frozen(self): + def test_iadd_frozen(self) -> None: _list = self.FrozenList([1]) _list.freeze() with pytest.raises(RuntimeError): _list += [2] assert _list == [1] - def test_index(self): + def test_index(self) -> None: _list = self.FrozenList([1]) assert _list.index(1) == 0 - def test_remove(self): + def test_remove(self) -> None: _list = self.FrozenList([1]) _list.remove(1) assert len(_list) == 0 - def test_remove_frozen(self): + def test_remove_frozen(self) -> None: _list = self.FrozenList([1]) _list.freeze() with pytest.raises(RuntimeError): _list.remove(1) assert _list == [1] - def test_clear(self): + def test_clear(self) -> None: _list = self.FrozenList([1]) _list.clear() assert len(_list) == 0 - def test_clear_frozen(self): + def test_clear_frozen(self) -> None: _list = self.FrozenList([1]) _list.freeze() with pytest.raises(RuntimeError): _list.clear() assert _list == [1] - def test_extend(self): + def test_extend(self) -> None: _list = self.FrozenList([1]) _list.extend([2]) assert _list == [1, 2] - def test_extend_frozen(self): + def test_extend_frozen(self) -> None: _list = self.FrozenList([1]) _list.freeze() with pytest.raises(RuntimeError): _list.extend([2]) assert _list == [1] - def test_reverse(self): + def test_reverse(self) -> None: _list = self.FrozenList([1, 2]) _list.reverse() assert _list == [2, 1] - def test_reverse_frozen(self): + def test_reverse_frozen(self) -> None: _list = self.FrozenList([1, 2]) _list.freeze() with pytest.raises(RuntimeError): _list.reverse() assert _list == [1, 2] - def test_pop(self): + def test_pop(self) -> None: _list = self.FrozenList([1, 2]) assert _list.pop(0) == 1 assert _list == [2] - def test_pop_default(self): + def test_pop_default(self) -> None: _list = self.FrozenList([1, 2]) assert _list.pop() == 2 assert _list == [1] - def test_pop_frozen(self): + def test_pop_frozen(self) -> None: _list = self.FrozenList([1, 2]) _list.freeze() with pytest.raises(RuntimeError): _list.pop() assert _list == [1, 2] - def test_append(self): + def test_append(self) -> None: _list = self.FrozenList([1, 2]) _list.append(3) assert _list == [1, 2, 3] - def test_append_frozen(self): + def test_append_frozen(self) -> None: _list = self.FrozenList([1, 2]) _list.freeze() with pytest.raises(RuntimeError): _list.append(3) assert _list == [1, 2] - def test_count(self): + def test_count(self) -> None: _list = self.FrozenList([1, 2]) assert _list.count(1) == 1 diff -Nru python-aiohttp-3.1.3/tests/test_helpers.py python-aiohttp-3.5.1/tests/test_helpers.py --- python-aiohttp-3.1.3/tests/test_helpers.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_helpers.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,41 +1,43 @@ import asyncio -import datetime +import base64 import gc import os +import platform import tempfile from unittest import mock import pytest +from multidict import MultiDict from yarl import URL from aiohttp import helpers -from aiohttp.abc import AbstractAccessLogger + + +IS_PYPY = platform.python_implementation() == 'PyPy' # ------------------- parse_mimetype ---------------------------------- @pytest.mark.parametrize('mimetype, expected', [ - ('', helpers.MimeType('', '', '', {})), - ('*', helpers.MimeType('*', '*', '', {})), - ('application/json', helpers.MimeType('application', 'json', '', {})), - ( - 'application/json; charset=utf-8', - helpers.MimeType('application', 'json', '', {'charset': 'utf-8'}) - ), - ( - '''application/json; charset=utf-8;''', - helpers.MimeType('application', 'json', '', {'charset': 'utf-8'}) - ), - ( - 'ApPlIcAtIoN/JSON;ChaRseT="UTF-8"', - helpers.MimeType('application', 'json', '', {'charset': 'UTF-8'}) - ), + ('', helpers.MimeType('', '', '', MultiDict())), + ('*', helpers.MimeType('*', '*', '', MultiDict())), + ('application/json', + helpers.MimeType('application', 'json', '', MultiDict())), + ('application/json; charset=utf-8', + helpers.MimeType('application', 'json', '', + MultiDict({'charset': 'utf-8'}))), + ('''application/json; charset=utf-8;''', + helpers.MimeType('application', 'json', '', + MultiDict({'charset': 'utf-8'}))), + ('ApPlIcAtIoN/JSON;ChaRseT="UTF-8"', + helpers.MimeType('application', 'json', '', + MultiDict({'charset': 'UTF-8'}))), ('application/rss+xml', - helpers.MimeType('application', 'rss', 'xml', {})), + helpers.MimeType('application', 'rss', 'xml', MultiDict())), ('text/plain;base64', - helpers.MimeType('text', 'plain', '', {'base64': ''})) + helpers.MimeType('text', 'plain', '', MultiDict({'base64': ''}))) ]) -def test_parse_mimetype(mimetype, expected): +def test_parse_mimetype(mimetype, expected) -> None: result = helpers.parse_mimetype(mimetype) assert isinstance(result, helpers.MimeType) @@ -44,236 +46,141 @@ # ------------------- guess_filename ---------------------------------- -def test_guess_filename_with_tempfile(): +def test_guess_filename_with_tempfile() -> None: with tempfile.TemporaryFile() as fp: assert (helpers.guess_filename(fp, 'no-throw') is not None) # ------------------- BasicAuth ----------------------------------- -def test_basic_auth1(): +def test_basic_auth1() -> None: # missing password here with pytest.raises(ValueError): helpers.BasicAuth(None) -def test_basic_auth2(): +def test_basic_auth2() -> None: with pytest.raises(ValueError): helpers.BasicAuth('nkim', None) -def test_basic_with_auth_colon_in_login(): +def test_basic_with_auth_colon_in_login() -> None: with pytest.raises(ValueError): helpers.BasicAuth('nkim:1', 'pwd') -def test_basic_auth3(): +def test_basic_auth3() -> None: auth = helpers.BasicAuth('nkim') assert auth.login == 'nkim' assert auth.password == '' -def test_basic_auth4(): +def test_basic_auth4() -> None: auth = helpers.BasicAuth('nkim', 'pwd') assert auth.login == 'nkim' assert auth.password == 'pwd' assert auth.encode() == 'Basic bmtpbTpwd2Q=' -def test_basic_auth_decode(): - auth = helpers.BasicAuth.decode('Basic bmtpbTpwd2Q=') +@pytest.mark.parametrize('header', ( + 'Basic bmtpbTpwd2Q=', + 'basic bmtpbTpwd2Q=', +)) +def test_basic_auth_decode(header) -> None: + auth = helpers.BasicAuth.decode(header) assert auth.login == 'nkim' assert auth.password == 'pwd' -def test_basic_auth_invalid(): +def test_basic_auth_invalid() -> None: with pytest.raises(ValueError): helpers.BasicAuth.decode('bmtpbTpwd2Q=') -def test_basic_auth_decode_not_basic(): +def test_basic_auth_decode_not_basic() -> None: with pytest.raises(ValueError): helpers.BasicAuth.decode('Complex bmtpbTpwd2Q=') -def test_basic_auth_decode_bad_base64(): +def test_basic_auth_decode_bad_base64() -> None: with pytest.raises(ValueError): helpers.BasicAuth.decode('Basic bmtpbTpwd2Q') -def test_basic_auth_from_url(): +@pytest.mark.parametrize('header', ('Basic ???', 'Basic ')) +def test_basic_auth_decode_illegal_chars_base64(header) -> None: + with pytest.raises(ValueError, match='Invalid base64 encoding.'): + helpers.BasicAuth.decode(header) + + +def test_basic_auth_decode_invalid_credentials() -> None: + with pytest.raises(ValueError, match='Invalid credentials.'): + header = 'Basic {}'.format(base64.b64encode(b'username').decode()) + helpers.BasicAuth.decode(header) + + +@pytest.mark.parametrize('credentials, expected_auth', ( + (':', helpers.BasicAuth( + login='', password='', encoding='latin1')), + ('username:', helpers.BasicAuth( + login='username', password='', encoding='latin1')), + (':password', helpers.BasicAuth( + login='', password='password', encoding='latin1')), + ('username:password', helpers.BasicAuth( + login='username', password='password', encoding='latin1')), +)) +def test_basic_auth_decode_blank_username(credentials, expected_auth) -> None: + header = 'Basic {}'.format(base64.b64encode(credentials.encode()).decode()) + assert helpers.BasicAuth.decode(header) == expected_auth + + +def test_basic_auth_from_url() -> None: url = URL('http://user:pass@example.com') auth = helpers.BasicAuth.from_url(url) assert auth.login == 'user' assert auth.password == 'pass' -def test_basic_auth_from_not_url(): +def test_basic_auth_from_not_url() -> None: with pytest.raises(TypeError): helpers.BasicAuth.from_url('http://user:pass@example.com') -# ------------- access logger ------------------------- - - -def test_access_logger_format(): - log_format = '%T "%{ETag}o" %X {X} %%P' - mock_logger = mock.Mock() - access_logger = helpers.AccessLogger(mock_logger, log_format) - expected = '%s "%s" %%X {X} %%%s' - assert expected == access_logger._log_format - - -def test_access_logger_atoms(mocker): - utcnow = datetime.datetime(1843, 1, 1, 0, 30) - mock_datetime = mocker.patch("aiohttp.helpers.datetime.datetime") - mock_getpid = mocker.patch("os.getpid") - mock_datetime.utcnow.return_value = utcnow - mock_getpid.return_value = 42 - log_format = '%a %t %P %r %s %b %T %Tf %D "%{H1}i" "%{H2}i"' - mock_logger = mock.Mock() - access_logger = helpers.AccessLogger(mock_logger, log_format) - request = mock.Mock(headers={'H1': 'a', 'H2': 'b'}, - method="GET", path_qs="/path", - version=(1, 1), - remote="127.0.0.2") - response = mock.Mock(headers={}, body_length=42, status=200) - access_logger.log(request, response, 3.1415926) - assert not mock_logger.exception.called - expected = ('127.0.0.2 [01/Jan/1843:00:29:56 +0000] <42> ' - 'GET /path HTTP/1.1 200 42 3 3.141593 3141593 "a" "b"') - extra = { - 'first_request_line': 'GET /path HTTP/1.1', - 'process_id': '<42>', - 'remote_address': '127.0.0.2', - 'request_start_time': '[01/Jan/1843:00:29:56 +0000]', - 'request_time': 3, - 'request_time_frac': '3.141593', - 'request_time_micro': 3141593, - 'response_size': 42, - 'response_status': 200, - 'request_header': {'H1': 'a', 'H2': 'b'}, - } - - mock_logger.info.assert_called_with(expected, extra=extra) - - -def test_access_logger_dicts(): - log_format = '%{User-Agent}i %{Content-Length}o %{None}i' - mock_logger = mock.Mock() - access_logger = helpers.AccessLogger(mock_logger, log_format) - request = mock.Mock(headers={"User-Agent": "Mock/1.0"}, version=(1, 1), - remote="127.0.0.2") - response = mock.Mock(headers={"Content-Length": 123}) - access_logger.log(request, response, 0.0) - assert not mock_logger.error.called - expected = 'Mock/1.0 123 -' - extra = { - 'request_header': {"User-Agent": "Mock/1.0", 'None': '-'}, - 'response_header': {'Content-Length': 123} - } - - mock_logger.info.assert_called_with(expected, extra=extra) - - -def test_access_logger_unix_socket(): - log_format = '|%a|' - mock_logger = mock.Mock() - access_logger = helpers.AccessLogger(mock_logger, log_format) - request = mock.Mock(headers={"User-Agent": "Mock/1.0"}, version=(1, 1), - remote="") - response = mock.Mock() - access_logger.log(request, response, 0.0) - assert not mock_logger.error.called - expected = '||' - mock_logger.info.assert_called_with(expected, extra={'remote_address': ''}) - - -def test_logger_no_message(): - mock_logger = mock.Mock() - access_logger = helpers.AccessLogger(mock_logger, - "%r %{content-type}i") - extra_dict = { - 'first_request_line': '-', - 'request_header': {'content-type': '(no headers)'} - } - - access_logger.log(None, None, 0.0) - mock_logger.info.assert_called_with("- (no headers)", extra=extra_dict) - - -def test_logger_internal_error(): - mock_logger = mock.Mock() - access_logger = helpers.AccessLogger(mock_logger, "%D") - access_logger.log(None, None, 'invalid') - mock_logger.exception.assert_called_with("Error in logging") - - -def test_logger_no_transport(): - mock_logger = mock.Mock() - access_logger = helpers.AccessLogger(mock_logger, "%a") - access_logger.log(None, None, 0) - mock_logger.info.assert_called_with("-", extra={'remote_address': '-'}) - - -def test_logger_abc(): - class Logger(AbstractAccessLogger): - def log(self, request, response, time): - 1 / 0 - - mock_logger = mock.Mock() - access_logger = Logger(mock_logger, None) - - with pytest.raises(ZeroDivisionError): - access_logger.log(None, None, None) - - class Logger(AbstractAccessLogger): - def log(self, request, response, time): - self.logger.info(self.log_format.format( - request=request, - response=response, - time=time - )) - - mock_logger = mock.Mock() - access_logger = Logger(mock_logger, '{request} {response} {time}') - access_logger.log('request', 'response', 1) - mock_logger.info.assert_called_with('request response 1') - +class ReifyMixin: -class TestReify: + reify = NotImplemented - def test_reify(self): + def test_reify(self) -> None: class A: def __init__(self): self._cache = {} - @helpers.reify + @self.reify def prop(self): return 1 a = A() assert 1 == a.prop - def test_reify_class(self): + def test_reify_class(self) -> None: class A: def __init__(self): self._cache = {} - @helpers.reify + @self.reify def prop(self): """Docstring.""" return 1 - assert isinstance(A.prop, helpers.reify) + assert isinstance(A.prop, self.reify) assert 'Docstring.' == A.prop.__doc__ - def test_reify_assignment(self): + def test_reify_assignment(self) -> None: class A: def __init__(self): self._cache = {} - @helpers.reify + @self.reify def prop(self): return 1 @@ -282,10 +189,19 @@ with pytest.raises(AttributeError): a.prop = 123 + +class TestPyReify(ReifyMixin): + reify = helpers.reify_py + + +if not helpers.NO_EXTENSIONS and not IS_PYPY: + class TestCReify(ReifyMixin): + reify = helpers.reify_c + # ----------------------------------- is_ip_address() ---------------------- -def test_is_ip_address(): +def test_is_ip_address() -> None: assert helpers.is_ip_address("127.0.0.1") assert helpers.is_ip_address("::1") assert helpers.is_ip_address("FE80:0000:0000:0000:0202:B3FF:FE1E:8329") @@ -303,7 +219,7 @@ assert not helpers.is_ip_address("1200::AB00:1234::2552:7777:1313") -def test_is_ip_address_bytes(): +def test_is_ip_address_bytes() -> None: assert helpers.is_ip_address(b"127.0.0.1") assert helpers.is_ip_address(b"::1") assert helpers.is_ip_address(b"FE80:0000:0000:0000:0202:B3FF:FE1E:8329") @@ -321,11 +237,20 @@ assert not helpers.is_ip_address(b"1200::AB00:1234::2552:7777:1313") -def test_ip_addresses(): +def test_ipv4_addresses() -> None: ip_addresses = [ '0.0.0.0', '127.0.0.1', '255.255.255.255', + ] + for address in ip_addresses: + assert helpers.is_ipv4_address(address) + assert not helpers.is_ipv6_address(address) + assert helpers.is_ip_address(address) + + +def test_ipv6_addresses() -> None: + ip_addresses = [ '0:0:0:0:0:0:0:0', 'FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF', '00AB:0002:3008:8CFD:00AB:0002:3008:8CFD', @@ -336,10 +261,12 @@ '1::1', ] for address in ip_addresses: + assert not helpers.is_ipv4_address(address) + assert helpers.is_ipv6_address(address) assert helpers.is_ip_address(address) -def test_host_addresses(): +def test_host_addresses() -> None: hosts = [ 'www.four.part.host' 'www.python.org', @@ -350,7 +277,7 @@ assert not helpers.is_ip_address(host) -def test_is_ip_address_invalid_type(): +def test_is_ip_address_invalid_type() -> None: with pytest.raises(TypeError): helpers.is_ip_address(123) @@ -360,7 +287,7 @@ # ----------------------------------- TimeoutHandle ------------------- -def test_timeout_handle(loop): +def test_timeout_handle(loop) -> None: handle = helpers.TimeoutHandle(loop, 10.2) cb = mock.Mock() handle.register(cb) @@ -369,7 +296,7 @@ assert not handle._callbacks -def test_timeout_handle_cb_exc(loop): +def test_timeout_handle_cb_exc(loop) -> None: handle = helpers.TimeoutHandle(loop, 10.2) cb = mock.Mock() handle.register(cb) @@ -379,7 +306,7 @@ assert not handle._callbacks -def test_timer_context_cancelled(): +def test_timer_context_cancelled() -> None: with mock.patch('aiohttp.helpers.asyncio') as m_asyncio: m_asyncio.TimeoutError = asyncio.TimeoutError loop = mock.Mock() @@ -390,10 +317,13 @@ with ctx: pass - assert m_asyncio.Task.current_task.return_value.cancel.called + if helpers.PY_37: + assert m_asyncio.current_task.return_value.cancel.called + else: + assert m_asyncio.Task.current_task.return_value.cancel.called -def test_timer_context_no_task(loop): +def test_timer_context_no_task(loop) -> None: with pytest.raises(RuntimeError): with helpers.TimerContext(loop): pass @@ -402,14 +332,14 @@ # -------------------------------- CeilTimeout -------------------------- -async def test_weakref_handle(loop): +async def test_weakref_handle(loop) -> None: cb = mock.Mock() helpers.weakref_handle(cb, 'test', 0.01, loop, False) await asyncio.sleep(0.1, loop=loop) assert cb.test.called -async def test_weakref_handle_weak(loop): +async def test_weakref_handle_weak(loop) -> None: cb = mock.Mock() helpers.weakref_handle(cb, 'test', 0.01, loop, False) del cb @@ -417,7 +347,7 @@ await asyncio.sleep(0.1, loop=loop) -def test_ceil_call_later(): +def test_ceil_call_later() -> None: cb = mock.Mock() loop = mock.Mock() loop.time.return_value = 10.1 @@ -425,20 +355,20 @@ loop.call_at.assert_called_with(21.0, cb) -def test_ceil_call_later_no_timeout(): +def test_ceil_call_later_no_timeout() -> None: cb = mock.Mock() loop = mock.Mock() helpers.call_later(cb, 0, loop) assert not loop.call_at.called -async def test_ceil_timeout(loop): +async def test_ceil_timeout(loop) -> None: with helpers.CeilTimeout(None, loop=loop) as timeout: assert timeout._timeout is None assert timeout._cancel_handler is None -def test_ceil_timeout_no_task(loop): +def test_ceil_timeout_no_task(loop) -> None: with pytest.raises(RuntimeError): with helpers.CeilTimeout(10, loop=loop): pass @@ -446,12 +376,12 @@ # -------------------------------- ContentDisposition ------------------- -def test_content_disposition(): +def test_content_disposition() -> None: assert (helpers.content_disposition_header('attachment', foo='bar') == 'attachment; foo="bar"') -def test_content_disposition_bad_type(): +def test_content_disposition_bad_type() -> None: with pytest.raises(ValueError): helpers.content_disposition_header('foo bar') with pytest.raises(ValueError): @@ -462,7 +392,7 @@ helpers.content_disposition_header('') -def test_set_content_disposition_bad_param(): +def test_set_content_disposition_bad_param() -> None: with pytest.raises(ValueError): helpers.content_disposition_header('inline', **{'foo bar': 'baz'}) with pytest.raises(ValueError): @@ -476,7 +406,7 @@ # --------------------- proxies_from_env ------------------------------ -def test_proxies_from_env_http(mocker): +def test_proxies_from_env_http(mocker) -> None: url = URL('http://aiohttp.io/path') mocker.patch.dict(os.environ, {'http_proxy': str(url)}) ret = helpers.proxies_from_env() @@ -485,7 +415,7 @@ assert ret['http'].proxy_auth is None -def test_proxies_from_env_http_proxy_for_https_proto(mocker): +def test_proxies_from_env_http_proxy_for_https_proto(mocker) -> None: url = URL('http://aiohttp.io/path') mocker.patch.dict(os.environ, {'https_proxy': str(url)}) ret = helpers.proxies_from_env() @@ -494,7 +424,7 @@ assert ret['https'].proxy_auth is None -def test_proxies_from_env_https_proxy_skipped(mocker): +def test_proxies_from_env_https_proxy_skipped(mocker) -> None: url = URL('https://aiohttp.io/path') mocker.patch.dict(os.environ, {'https_proxy': str(url)}) log = mocker.patch('aiohttp.log.client_logger.warning') @@ -503,7 +433,7 @@ URL('https://aiohttp.io/path')) -def test_proxies_from_env_http_with_auth(mocker): +def test_proxies_from_env_http_with_auth(mocker) -> None: url = URL('http://user:pass@aiohttp.io/path') mocker.patch.dict(os.environ, {'http_proxy': str(url)}) ret = helpers.proxies_from_env() @@ -514,17 +444,28 @@ assert proxy_auth.password == 'pass' assert proxy_auth.encoding == 'latin1' +# ------------ get_running_loop --------------------------------- + + +def test_get_running_loop_not_running(loop) -> None: + with pytest.warns(DeprecationWarning): + helpers.get_running_loop() + + +async def test_get_running_loop_ok(loop) -> None: + assert helpers.get_running_loop() is loop + # ------------- set_result / set_exception ---------------------- -async def test_set_result(loop): +async def test_set_result(loop) -> None: fut = loop.create_future() helpers.set_result(fut, 123) assert 123 == await fut -async def test_set_result_cancelled(loop): +async def test_set_result_cancelled(loop) -> None: fut = loop.create_future() fut.cancel() helpers.set_result(fut, 123) @@ -533,17 +474,91 @@ await fut -async def test_set_exception(loop): +async def test_set_exception(loop) -> None: fut = loop.create_future() helpers.set_exception(fut, RuntimeError()) with pytest.raises(RuntimeError): await fut -async def test_set_exception_cancelled(loop): +async def test_set_exception_cancelled(loop) -> None: fut = loop.create_future() fut.cancel() helpers.set_exception(fut, RuntimeError()) with pytest.raises(asyncio.CancelledError): await fut + + +# ----------- ChainMapProxy -------------------------- + +class TestChainMapProxy: + @pytest.mark.skipif(not helpers.PY_36, + reason="Requires Python 3.6+") + def test_inheritance(self) -> None: + with pytest.raises(TypeError): + class A(helpers.ChainMapProxy): + pass + + def test_getitem(self) -> None: + d1 = {'a': 2, 'b': 3} + d2 = {'a': 1} + cp = helpers.ChainMapProxy([d1, d2]) + assert cp['a'] == 2 + assert cp['b'] == 3 + + def test_getitem_not_found(self) -> None: + d = {'a': 1} + cp = helpers.ChainMapProxy([d]) + with pytest.raises(KeyError): + cp['b'] + + def test_get(self) -> None: + d1 = {'a': 2, 'b': 3} + d2 = {'a': 1} + cp = helpers.ChainMapProxy([d1, d2]) + assert cp.get('a') == 2 + + def test_get_default(self) -> None: + d1 = {'a': 2, 'b': 3} + d2 = {'a': 1} + cp = helpers.ChainMapProxy([d1, d2]) + assert cp.get('c', 4) == 4 + + def test_get_non_default(self) -> None: + d1 = {'a': 2, 'b': 3} + d2 = {'a': 1} + cp = helpers.ChainMapProxy([d1, d2]) + assert cp.get('a', 4) == 2 + + def test_len(self) -> None: + d1 = {'a': 2, 'b': 3} + d2 = {'a': 1} + cp = helpers.ChainMapProxy([d1, d2]) + assert len(cp) == 2 + + def test_iter(self) -> None: + d1 = {'a': 2, 'b': 3} + d2 = {'a': 1} + cp = helpers.ChainMapProxy([d1, d2]) + assert set(cp) == {'a', 'b'} + + def test_contains(self) -> None: + d1 = {'a': 2, 'b': 3} + d2 = {'a': 1} + cp = helpers.ChainMapProxy([d1, d2]) + assert 'a' in cp + assert 'b' in cp + assert 'c' not in cp + + def test_bool(self) -> None: + assert helpers.ChainMapProxy([{'a': 1}]) + assert not helpers.ChainMapProxy([{}, {}]) + assert not helpers.ChainMapProxy([]) + + def test_repr(self) -> None: + d1 = {'a': 2, 'b': 3} + d2 = {'a': 1} + cp = helpers.ChainMapProxy([d1, d2]) + expected = "ChainMapProxy({!r}, {!r})".format(d1, d2) + assert expected == repr(cp) diff -Nru python-aiohttp-3.1.3/tests/test_http_exceptions.py python-aiohttp-3.5.1/tests/test_http_exceptions.py --- python-aiohttp-3.1.3/tests/test_http_exceptions.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_http_exceptions.py 2018-12-24 20:58:54.000000000 +0000 @@ -3,17 +3,17 @@ from aiohttp import http_exceptions -def test_bad_status_line1(): +def test_bad_status_line1() -> None: err = http_exceptions.BadStatusLine(b'') assert str(err) == "b''" -def test_bad_status_line2(): +def test_bad_status_line2() -> None: err = http_exceptions.BadStatusLine('Test') assert str(err) == 'Test' -def test_http_error_exception(): +def test_http_error_exception() -> None: exc = http_exceptions.HttpProcessingError( code=500, message='Internal error') assert exc.code == 500 diff -Nru python-aiohttp-3.1.3/tests/test_http_parser.py python-aiohttp-3.5.1/tests/test_http_parser.py --- python-aiohttp-3.1.3/tests/test_http_parser.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_http_parser.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,5 +1,6 @@ """Tests for aiohttp/protocol.py""" +import asyncio import zlib from unittest import mock @@ -23,9 +24,9 @@ RESPONSE_PARSERS = [HttpResponseParserPy] try: - from aiohttp import _http_parser - REQUEST_PARSERS.append(_http_parser.HttpRequestParserC) - RESPONSE_PARSERS.append(_http_parser.HttpResponseParserC) + from aiohttp.http_parser import HttpRequestParserC, HttpResponseParserC + REQUEST_PARSERS.append(HttpRequestParserC) + RESPONSE_PARSERS.append(HttpResponseParserC) except ImportError: # pragma: no cover pass @@ -70,7 +71,7 @@ return mock.Mock() -def test_parse_headers(parser): +def test_parse_headers(parser) -> None: text = b'''GET /test HTTP/1.1\r test: line\r continue\r @@ -90,7 +91,7 @@ assert not msg.upgrade -def test_parse(parser): +def test_parse(parser) -> None: text = b'GET /test HTTP/1.1\r\n\r\n' messages, upgrade, tail = parser.feed_data(text) assert len(messages) == 1 @@ -102,7 +103,7 @@ assert msg.version == (1, 1) -async def test_parse_body(parser): +async def test_parse_body(parser) -> None: text = b'GET /test HTTP/1.1\r\nContent-Length: 4\r\n\r\nbody' messages, upgrade, tail = parser.feed_data(text) assert len(messages) == 1 @@ -111,7 +112,7 @@ assert body == b'body' -async def test_parse_body_with_CRLF(parser): +async def test_parse_body_with_CRLF(parser) -> None: text = b'\r\nGET /test HTTP/1.1\r\nContent-Length: 4\r\n\r\nbody' messages, upgrade, tail = parser.feed_data(text) assert len(messages) == 1 @@ -120,7 +121,7 @@ assert body == b'body' -def test_parse_delayed(parser): +def test_parse_delayed(parser) -> None: text = b'GET /test HTTP/1.1\r\n' messages, upgrade, tail = parser.feed_data(text) assert len(messages) == 0 @@ -132,7 +133,7 @@ assert msg.method == 'GET' -def test_headers_multi_feed(parser): +def test_headers_multi_feed(parser) -> None: text1 = b'GET /test HTTP/1.1\r\n' text2 = b'test: line\r' text3 = b'\n continue\r\n\r\n' @@ -154,7 +155,7 @@ assert not msg.upgrade -def test_headers_split_field(parser): +def test_headers_split_field(parser) -> None: text1 = b'GET /test HTTP/1.1\r\n' text2 = b't' text3 = b'es' @@ -175,7 +176,7 @@ assert not msg.upgrade -def test_parse_headers_multi(parser): +def test_parse_headers_multi(parser) -> None: text = (b'GET /test HTTP/1.1\r\n' b'Set-Cookie: c1=cookie1\r\n' b'Set-Cookie: c2=cookie2\r\n\r\n') @@ -192,21 +193,21 @@ assert msg.compression is None -def test_conn_default_1_0(parser): +def test_conn_default_1_0(parser) -> None: text = b'GET /test HTTP/1.0\r\n\r\n' messages, upgrade, tail = parser.feed_data(text) msg = messages[0][0] assert msg.should_close -def test_conn_default_1_1(parser): +def test_conn_default_1_1(parser) -> None: text = b'GET /test HTTP/1.1\r\n\r\n' messages, upgrade, tail = parser.feed_data(text) msg = messages[0][0] assert not msg.should_close -def test_conn_close(parser): +def test_conn_close(parser) -> None: text = (b'GET /test HTTP/1.1\r\n' b'connection: close\r\n\r\n') messages, upgrade, tail = parser.feed_data(text) @@ -214,7 +215,7 @@ assert msg.should_close -def test_conn_close_1_0(parser): +def test_conn_close_1_0(parser) -> None: text = (b'GET /test HTTP/1.0\r\n' b'connection: close\r\n\r\n') messages, upgrade, tail = parser.feed_data(text) @@ -222,7 +223,7 @@ assert msg.should_close -def test_conn_keep_alive_1_0(parser): +def test_conn_keep_alive_1_0(parser) -> None: text = (b'GET /test HTTP/1.0\r\n' b'connection: keep-alive\r\n\r\n') messages, upgrade, tail = parser.feed_data(text) @@ -230,7 +231,7 @@ assert not msg.should_close -def test_conn_keep_alive_1_1(parser): +def test_conn_keep_alive_1_1(parser) -> None: text = (b'GET /test HTTP/1.1\r\n' b'connection: keep-alive\r\n\r\n') messages, upgrade, tail = parser.feed_data(text) @@ -238,7 +239,7 @@ assert not msg.should_close -def test_conn_other_1_0(parser): +def test_conn_other_1_0(parser) -> None: text = (b'GET /test HTTP/1.0\r\n' b'connection: test\r\n\r\n') messages, upgrade, tail = parser.feed_data(text) @@ -246,7 +247,7 @@ assert msg.should_close -def test_conn_other_1_1(parser): +def test_conn_other_1_1(parser) -> None: text = (b'GET /test HTTP/1.1\r\n' b'connection: test\r\n\r\n') messages, upgrade, tail = parser.feed_data(text) @@ -254,7 +255,7 @@ assert not msg.should_close -def test_request_chunked(parser): +def test_request_chunked(parser) -> None: text = (b'GET /test HTTP/1.1\r\n' b'transfer-encoding: chunked\r\n\r\n') messages, upgrade, tail = parser.feed_data(text) @@ -264,7 +265,7 @@ assert isinstance(payload, streams.StreamReader) -def test_conn_upgrade(parser): +def test_conn_upgrade(parser) -> None: text = (b'GET /test HTTP/1.1\r\n' b'connection: upgrade\r\n' b'upgrade: websocket\r\n\r\n') @@ -275,7 +276,7 @@ assert upgrade -def test_compression_empty(parser): +def test_compression_empty(parser) -> None: text = (b'GET /test HTTP/1.1\r\n' b'content-encoding: \r\n\r\n') messages, upgrade, tail = parser.feed_data(text) @@ -283,7 +284,7 @@ assert msg.compression is None -def test_compression_deflate(parser): +def test_compression_deflate(parser) -> None: text = (b'GET /test HTTP/1.1\r\n' b'content-encoding: deflate\r\n\r\n') messages, upgrade, tail = parser.feed_data(text) @@ -291,7 +292,7 @@ assert msg.compression == 'deflate' -def test_compression_gzip(parser): +def test_compression_gzip(parser) -> None: text = (b'GET /test HTTP/1.1\r\n' b'content-encoding: gzip\r\n\r\n') messages, upgrade, tail = parser.feed_data(text) @@ -300,7 +301,7 @@ @pytest.mark.skipif(brotli is None, reason="brotli is not installed") -def test_compression_brotli(parser): +def test_compression_brotli(parser) -> None: text = (b'GET /test HTTP/1.1\r\n' b'content-encoding: br\r\n\r\n') messages, upgrade, tail = parser.feed_data(text) @@ -308,7 +309,7 @@ assert msg.compression == 'br' -def test_compression_unknown(parser): +def test_compression_unknown(parser) -> None: text = (b'GET /test HTTP/1.1\r\n' b'content-encoding: compress\r\n\r\n') messages, upgrade, tail = parser.feed_data(text) @@ -316,7 +317,7 @@ assert msg.compression is None -def test_headers_connect(parser): +def test_headers_connect(parser) -> None: text = (b'CONNECT www.google.com HTTP/1.1\r\n' b'content-length: 0\r\n\r\n') messages, upgrade, tail = parser.feed_data(text) @@ -325,7 +326,7 @@ assert isinstance(payload, streams.StreamReader) -def test_headers_old_websocket_key1(parser): +def test_headers_old_websocket_key1(parser) -> None: text = (b'GET /test HTTP/1.1\r\n' b'SEC-WEBSOCKET-KEY1: line\r\n\r\n') @@ -333,7 +334,7 @@ parser.feed_data(text) -def test_headers_content_length_err_1(parser): +def test_headers_content_length_err_1(parser) -> None: text = (b'GET /test HTTP/1.1\r\n' b'content-length: line\r\n\r\n') @@ -341,7 +342,7 @@ parser.feed_data(text) -def test_headers_content_length_err_2(parser): +def test_headers_content_length_err_2(parser) -> None: text = (b'GET /test HTTP/1.1\r\n' b'content-length: -1\r\n\r\n') @@ -349,14 +350,14 @@ parser.feed_data(text) -def test_invalid_header(parser): +def test_invalid_header(parser) -> None: text = (b'GET /test HTTP/1.1\r\n' b'test line\r\n\r\n') with pytest.raises(http_exceptions.BadHttpMessage): parser.feed_data(text) -def test_invalid_name(parser): +def test_invalid_name(parser) -> None: text = (b'GET /test HTTP/1.1\r\n' b'test[]: line\r\n\r\n') @@ -365,97 +366,120 @@ @pytest.mark.parametrize('size', [40960, 8191]) -def test_max_header_field_size(parser, size): +def test_max_header_field_size(parser, size) -> None: name = b't' * size text = (b'GET /test HTTP/1.1\r\n' + name + b':data\r\n\r\n') - match = ("400, message='Got more than 8190 bytes \({}\) when reading" + match = ("400, message='Got more than 8190 bytes \\({}\\) when reading" .format(size)) with pytest.raises(http_exceptions.LineTooLong, match=match): parser.feed_data(text) -def test_max_header_field_size_under_limit(parser): +def test_max_header_field_size_under_limit(parser) -> None: name = b't' * 8190 text = (b'GET /test HTTP/1.1\r\n' + name + b':data\r\n\r\n') messages, upgrade, tail = parser.feed_data(text) msg = messages[0][0] - assert msg == ( - 'GET', '/test', (1, 1), - CIMultiDict({name.decode(): 'data'}), - ((name, b'data'),), - False, None, False, False, URL('/test')) + assert msg.method == 'GET' + assert msg.path == '/test' + assert msg.version == (1, 1) + assert msg.headers == CIMultiDict({name.decode(): 'data'}) + assert msg.raw_headers == ((name, b'data'),) + assert not msg.should_close + assert msg.compression is None + assert not msg.upgrade + assert not msg.chunked + assert msg.url == URL('/test') @pytest.mark.parametrize('size', [40960, 8191]) -def test_max_header_value_size(parser, size): +def test_max_header_value_size(parser, size) -> None: name = b't' * size text = (b'GET /test HTTP/1.1\r\n' b'data:' + name + b'\r\n\r\n') - match = ("400, message='Got more than 8190 bytes \({}\) when reading" + match = ("400, message='Got more than 8190 bytes \\({}\\) when reading" .format(size)) with pytest.raises(http_exceptions.LineTooLong, match=match): parser.feed_data(text) -def test_max_header_value_size_under_limit(parser): +def test_max_header_value_size_under_limit(parser) -> None: value = b'A' * 8190 text = (b'GET /test HTTP/1.1\r\n' b'data:' + value + b'\r\n\r\n') messages, upgrade, tail = parser.feed_data(text) msg = messages[0][0] - assert msg == ( - 'GET', '/test', (1, 1), - CIMultiDict({'data': value.decode()}), - ((b'data', value),), - False, None, False, False, URL('/test')) + assert msg.method == 'GET' + assert msg.path == '/test' + assert msg.version == (1, 1) + assert msg.headers == CIMultiDict({'data': value.decode()}) + assert msg.raw_headers == ((b'data', value),) + assert not msg.should_close + assert msg.compression is None + assert not msg.upgrade + assert not msg.chunked + assert msg.url == URL('/test') @pytest.mark.parametrize('size', [40965, 8191]) -def test_max_header_value_size_continuation(parser, size): +def test_max_header_value_size_continuation(parser, size) -> None: name = b'T' * (size - 5) text = (b'GET /test HTTP/1.1\r\n' b'data: test\r\n ' + name + b'\r\n\r\n') - match = ("400, message='Got more than 8190 bytes \({}\) when reading" + match = ("400, message='Got more than 8190 bytes \\({}\\) when reading" .format(size)) with pytest.raises(http_exceptions.LineTooLong, match=match): parser.feed_data(text) -def test_max_header_value_size_continuation_under_limit(parser): +def test_max_header_value_size_continuation_under_limit(parser) -> None: value = b'A' * 8185 text = (b'GET /test HTTP/1.1\r\n' b'data: test\r\n ' + value + b'\r\n\r\n') messages, upgrade, tail = parser.feed_data(text) msg = messages[0][0] - assert msg == ( - 'GET', '/test', (1, 1), - CIMultiDict({'data': 'test ' + value.decode()}), - ((b'data', b'test ' + value),), - False, None, False, False, URL('/test')) + assert msg.method == 'GET' + assert msg.path == '/test' + assert msg.version == (1, 1) + assert msg.headers == CIMultiDict({'data': 'test ' + value.decode()}) + assert msg.raw_headers == ((b'data', b'test ' + value),) + assert not msg.should_close + assert msg.compression is None + assert not msg.upgrade + assert not msg.chunked + assert msg.url == URL('/test') -def test_http_request_parser(parser): +def test_http_request_parser(parser) -> None: text = b'GET /path HTTP/1.1\r\n\r\n' messages, upgrade, tail = parser.feed_data(text) msg = messages[0][0] - assert msg == ('GET', '/path', (1, 1), CIMultiDict(), (), - False, None, False, False, URL('/path')) + assert msg.method == 'GET' + assert msg.path == '/path' + assert msg.version == (1, 1) + assert msg.headers == CIMultiDict() + assert msg.raw_headers == () + assert not msg.should_close + assert msg.compression is None + assert not msg.upgrade + assert not msg.chunked + assert msg.url == URL('/path') -def test_http_request_bad_status_line(parser): +def test_http_request_bad_status_line(parser) -> None: text = b'getpath \r\n\r\n' with pytest.raises(http_exceptions.BadStatusLine): parser.feed_data(text) -def test_http_request_upgrade(parser): +def test_http_request_upgrade(parser) -> None: text = (b'GET /test HTTP/1.1\r\n' b'connection: upgrade\r\n' b'upgrade: websocket\r\n\r\n' @@ -468,66 +492,92 @@ assert tail == b'some raw data' -def test_http_request_parser_utf8(parser): +def test_http_request_parser_utf8(parser) -> None: text = 'GET /path HTTP/1.1\r\nx-test:тест\r\n\r\n'.encode('utf-8') messages, upgrade, tail = parser.feed_data(text) msg = messages[0][0] - assert msg == ('GET', '/path', (1, 1), - CIMultiDict([('X-TEST', 'тест')]), - ((b'x-test', 'тест'.encode('utf-8')),), - False, None, False, False, URL('/path')) + assert msg.method == 'GET' + assert msg.path == '/path' + assert msg.version == (1, 1) + assert msg.headers == CIMultiDict([('X-TEST', 'тест')]) + assert msg.raw_headers == ((b'x-test', 'тест'.encode('utf-8')),) + assert not msg.should_close + assert msg.compression is None + assert not msg.upgrade + assert not msg.chunked + assert msg.url == URL('/path') -def test_http_request_parser_non_utf8(parser): +def test_http_request_parser_non_utf8(parser) -> None: text = 'GET /path HTTP/1.1\r\nx-test:тест\r\n\r\n'.encode('cp1251') msg = parser.feed_data(text)[0][0][0] - assert msg == ('GET', '/path', (1, 1), - CIMultiDict([('X-TEST', 'тест'.encode('cp1251').decode( - 'utf-8', 'surrogateescape'))]), - ((b'x-test', 'тест'.encode('cp1251')),), - False, None, False, False, URL('/path')) + assert msg.method == 'GET' + assert msg.path == '/path' + assert msg.version == (1, 1) + assert msg.headers == CIMultiDict([('X-TEST', 'тест'.encode('cp1251') + .decode('utf8', 'surrogateescape'))]) + assert msg.raw_headers == ((b'x-test', 'тест'.encode('cp1251')),) + assert not msg.should_close + assert msg.compression is None + assert not msg.upgrade + assert not msg.chunked + assert msg.url == URL('/path') -def test_http_request_parser_two_slashes(parser): +def test_http_request_parser_two_slashes(parser) -> None: text = b'GET //path HTTP/1.1\r\n\r\n' msg = parser.feed_data(text)[0][0][0] - assert msg[:-1] == ('GET', '//path', (1, 1), CIMultiDict(), (), - False, None, False, False) + assert msg.method == 'GET' + assert msg.path == '//path' + assert msg.version == (1, 1) + assert not msg.should_close + assert msg.compression is None + assert not msg.upgrade + assert not msg.chunked -def test_http_request_parser_bad_method(parser): +def test_http_request_parser_bad_method(parser) -> None: with pytest.raises(http_exceptions.BadStatusLine): - parser.feed_data(b'!12%()+=~$ /get HTTP/1.1\r\n\r\n') + parser.feed_data(b'=":(e),[T];?" /get HTTP/1.1\r\n\r\n') -def test_http_request_parser_bad_version(parser): +def test_http_request_parser_bad_version(parser) -> None: with pytest.raises(http_exceptions.BadHttpMessage): parser.feed_data(b'GET //get HT/11\r\n\r\n') @pytest.mark.parametrize('size', [40965, 8191]) -def test_http_request_max_status_line(parser, size): +def test_http_request_max_status_line(parser, size) -> None: path = b't' * (size - 5) - match = ("400, message='Got more than 8190 bytes \({}\) when reading" + match = ("400, message='Got more than 8190 bytes \\({}\\) when reading" .format(size)) with pytest.raises(http_exceptions.LineTooLong, match=match): parser.feed_data( b'GET /path' + path + b' HTTP/1.1\r\n\r\n') -def test_http_request_max_status_line_under_limit(parser): +def test_http_request_max_status_line_under_limit(parser) -> None: path = b't' * (8190 - 5) messages, upgraded, tail = parser.feed_data( b'GET /path' + path + b' HTTP/1.1\r\n\r\n') msg = messages[0][0] - assert msg == ('GET', '/path' + path.decode(), (1, 1), CIMultiDict(), (), - False, None, False, False, URL('/path' + path.decode())) + + assert msg.method == 'GET' + assert msg.path == '/path' + path.decode() + assert msg.version == (1, 1) + assert msg.headers == CIMultiDict() + assert msg.raw_headers == () + assert not msg.should_close + assert msg.compression is None + assert not msg.upgrade + assert not msg.chunked + assert msg.url == URL('/path' + path.decode()) -def test_http_response_parser_utf8(response): +def test_http_response_parser_utf8(response) -> None: text = 'HTTP/1.1 200 Ok\r\nx-test:тест\r\n\r\n'.encode('utf-8') messages, upgraded, tail = response.feed_data(text) @@ -544,16 +594,16 @@ @pytest.mark.parametrize('size', [40962, 8191]) -def test_http_response_parser_bad_status_line_too_long(response, size): +def test_http_response_parser_bad_status_line_too_long(response, size) -> None: reason = b't' * (size - 2) - match = ("400, message='Got more than 8190 bytes \({}\) when reading" + match = ("400, message='Got more than 8190 bytes \\({}\\) when reading" .format(size)) with pytest.raises(http_exceptions.LineTooLong, match=match): response.feed_data( b'HTTP/1.1 200 Ok' + reason + b'\r\n\r\n') -def test_http_response_parser_status_line_under_limit(response): +def test_http_response_parser_status_line_under_limit(response) -> None: reason = b'O' * 8190 messages, upgraded, tail = response.feed_data( b'HTTP/1.1 200 ' + reason + b'\r\n\r\n') @@ -563,12 +613,12 @@ assert msg.reason == reason.decode() -def test_http_response_parser_bad_version(response): +def test_http_response_parser_bad_version(response) -> None: with pytest.raises(http_exceptions.BadHttpMessage): response.feed_data(b'HT/11 200 Ok\r\n\r\n') -def test_http_response_parser_no_reason(response): +def test_http_response_parser_no_reason(response) -> None: msg = response.feed_data(b'HTTP/1.1 200\r\n\r\n')[0][0][0] assert msg.version == (1, 1) @@ -576,27 +626,27 @@ assert not msg.reason -def test_http_response_parser_bad(response): +def test_http_response_parser_bad(response) -> None: with pytest.raises(http_exceptions.BadHttpMessage): response.feed_data(b'HTT/1\r\n\r\n') -def test_http_response_parser_code_under_100(response): +def test_http_response_parser_code_under_100(response) -> None: msg = response.feed_data(b'HTTP/1.1 99 test\r\n\r\n')[0][0][0] assert msg.code == 99 -def test_http_response_parser_code_above_999(response): +def test_http_response_parser_code_above_999(response) -> None: with pytest.raises(http_exceptions.BadHttpMessage): response.feed_data(b'HTTP/1.1 9999 test\r\n\r\n') -def test_http_response_parser_code_not_int(response): +def test_http_response_parser_code_not_int(response) -> None: with pytest.raises(http_exceptions.BadHttpMessage): response.feed_data(b'HTTP/1.1 ttt test\r\n\r\n') -def test_http_request_chunked_payload(parser): +def test_http_request_chunked_payload(parser) -> None: text = (b'GET /test HTTP/1.1\r\n' b'transfer-encoding: chunked\r\n\r\n') msg, payload = parser.feed_data(text)[0][0] @@ -612,7 +662,7 @@ assert payload.is_eof() -def test_http_request_chunked_payload_and_next_message(parser): +def test_http_request_chunked_payload_and_next_message(parser) -> None: text = (b'GET /test HTTP/1.1\r\n' b'transfer-encoding: chunked\r\n\r\n') msg, payload = parser.feed_data(text)[0][0] @@ -634,7 +684,7 @@ assert not payload2.is_eof() -def test_http_request_chunked_payload_chunks(parser): +def test_http_request_chunked_payload_chunks(parser) -> None: text = (b'GET /test HTTP/1.1\r\n' b'transfer-encoding: chunked\r\n\r\n') msg, payload = parser.feed_data(text)[0][0] @@ -657,7 +707,7 @@ assert payload.is_eof() -def test_parse_chunked_payload_chunk_extension(parser): +def test_parse_chunked_payload_chunk_extension(parser) -> None: text = (b'GET /test HTTP/1.1\r\n' b'transfer-encoding: chunked\r\n\r\n') msg, payload = parser.feed_data(text)[0][0] @@ -678,7 +728,8 @@ assert payload.is_eof() -def test_parse_payload_response_without_body(loop, protocol, response_cls): +def test_parse_payload_response_without_body(loop, protocol, + response_cls) -> None: parser = response_cls(protocol, loop, response_with_body=False) text = (b'HTTP/1.1 200 Ok\r\n' b'content-length: 10\r\n\r\n') @@ -687,7 +738,7 @@ assert payload.is_eof() -def test_parse_length_payload(response): +def test_parse_length_payload(response) -> None: text = (b'HTTP/1.1 200 Ok\r\n' b'content-length: 4\r\n\r\n') msg, payload = response.feed_data(text)[0][0] @@ -701,13 +752,13 @@ assert b'data' == b''.join(d for d in payload._buffer) -def test_parse_no_length_payload(parser): +def test_parse_no_length_payload(parser) -> None: text = b'PUT / HTTP/1.1\r\n\r\n' msg, payload = parser.feed_data(text)[0][0] assert payload.is_eof() -def test_partial_url(parser): +def test_partial_url(parser) -> None: messages, upgrade, tail = parser.feed_data(b'GET /te') assert len(messages) == 0 messages, upgrade, tail = parser.feed_data(b'st HTTP/1.1\r\n\r\n') @@ -721,7 +772,7 @@ assert payload.is_eof() -def test_url_parse_non_strict_mode(parser): +def test_url_parse_non_strict_mode(parser) -> None: payload = 'GET /test/тест HTTP/1.1\r\n\r\n'.encode('utf-8') messages, upgrade, tail = parser.feed_data(payload) assert len(messages) == 1 @@ -736,8 +787,9 @@ class TestParsePayload: - def test_parse_eof_payload(self, stream): - out = aiohttp.FlowControlDataQueue(stream) + async def test_parse_eof_payload(self, stream) -> None: + out = aiohttp.FlowControlDataQueue(stream, + loop=asyncio.get_event_loop()) p = HttpPayloadParser(out, readall=True) p.feed_data(b'data') p.feed_eof() @@ -745,15 +797,17 @@ assert out.is_eof() assert [(bytearray(b'data'), 4)] == list(out._buffer) - def test_parse_no_body(self, stream): - out = aiohttp.FlowControlDataQueue(stream) + async def test_parse_no_body(self, stream) -> None: + out = aiohttp.FlowControlDataQueue(stream, + loop=asyncio.get_event_loop()) p = HttpPayloadParser(out, method='PUT') assert out.is_eof() assert p.done - def test_parse_length_payload_eof(self, stream): - out = aiohttp.FlowControlDataQueue(stream) + async def test_parse_length_payload_eof(self, stream) -> None: + out = aiohttp.FlowControlDataQueue(stream, + loop=asyncio.get_event_loop()) p = HttpPayloadParser(out, length=4) p.feed_data(b'da') @@ -761,16 +815,18 @@ with pytest.raises(http_exceptions.ContentLengthError): p.feed_eof() - def test_parse_chunked_payload_size_error(self, stream): - out = aiohttp.FlowControlDataQueue(stream) + async def test_parse_chunked_payload_size_error(self, stream) -> None: + out = aiohttp.FlowControlDataQueue(stream, + loop=asyncio.get_event_loop()) p = HttpPayloadParser(out, chunked=True) with pytest.raises(http_exceptions.TransferEncodingError): p.feed_data(b'blah\r\n') assert isinstance(out.exception(), http_exceptions.TransferEncodingError) - def test_http_payload_parser_length(self, stream): - out = aiohttp.FlowControlDataQueue(stream) + async def test_http_payload_parser_length(self, stream) -> None: + out = aiohttp.FlowControlDataQueue(stream, + loop=asyncio.get_event_loop()) p = HttpPayloadParser(out, length=2) eof, tail = p.feed_data(b'1245') assert eof @@ -781,37 +837,41 @@ _comp = zlib.compressobj(wbits=-zlib.MAX_WBITS) _COMPRESSED = b''.join([_comp.compress(b'data'), _comp.flush()]) - def test_http_payload_parser_deflate(self, stream): + async def test_http_payload_parser_deflate(self, stream) -> None: length = len(self._COMPRESSED) - out = aiohttp.FlowControlDataQueue(stream) + out = aiohttp.FlowControlDataQueue(stream, + loop=asyncio.get_event_loop()) p = HttpPayloadParser( out, length=length, compression='deflate') p.feed_data(self._COMPRESSED) assert b'data' == b''.join(d for d, _ in out._buffer) assert out.is_eof() - def test_http_payload_parser_deflate_no_wbits(self, stream): + async def test_http_payload_parser_deflate_no_wbits(self, stream) -> None: comp = zlib.compressobj() COMPRESSED = b''.join([comp.compress(b'data'), comp.flush()]) length = len(COMPRESSED) - out = aiohttp.FlowControlDataQueue(stream) + out = aiohttp.FlowControlDataQueue(stream, + loop=asyncio.get_event_loop()) p = HttpPayloadParser( out, length=length, compression='deflate') p.feed_data(COMPRESSED) assert b'data' == b''.join(d for d, _ in out._buffer) assert out.is_eof() - def test_http_payload_parser_length_zero(self, stream): - out = aiohttp.FlowControlDataQueue(stream) + async def test_http_payload_parser_length_zero(self, stream) -> None: + out = aiohttp.FlowControlDataQueue(stream, + loop=asyncio.get_event_loop()) p = HttpPayloadParser(out, length=0) assert p.done assert out.is_eof() @pytest.mark.skipif(brotli is None, reason="brotli is not installed") - def test_http_payload_brotli(self, stream): + async def test_http_payload_brotli(self, stream) -> None: compressed = brotli.compress(b'brotli data') - out = aiohttp.FlowControlDataQueue(stream) + out = aiohttp.FlowControlDataQueue(stream, + loop=asyncio.get_event_loop()) p = HttpPayloadParser( out, length=len(compressed), compression='br') p.feed_data(compressed) @@ -821,8 +881,9 @@ class TestDeflateBuffer: - def test_feed_data(self, stream): - buf = aiohttp.FlowControlDataQueue(stream) + async def test_feed_data(self, stream) -> None: + buf = aiohttp.FlowControlDataQueue(stream, + loop=asyncio.get_event_loop()) dbuf = DeflateBuffer(buf, 'deflate') dbuf.decompressor = mock.Mock() @@ -831,8 +892,9 @@ dbuf.feed_data(b'data', 4) assert [b'line'] == list(d for d, _ in buf._buffer) - def test_feed_data_err(self, stream): - buf = aiohttp.FlowControlDataQueue(stream) + async def test_feed_data_err(self, stream) -> None: + buf = aiohttp.FlowControlDataQueue(stream, + loop=asyncio.get_event_loop()) dbuf = DeflateBuffer(buf, 'deflate') exc = ValueError() @@ -842,8 +904,9 @@ with pytest.raises(http_exceptions.ContentEncodingError): dbuf.feed_data(b'data', 4) - def test_feed_eof(self, stream): - buf = aiohttp.FlowControlDataQueue(stream) + async def test_feed_eof(self, stream) -> None: + buf = aiohttp.FlowControlDataQueue(stream, + loop=asyncio.get_event_loop()) dbuf = DeflateBuffer(buf, 'deflate') dbuf.decompressor = mock.Mock() @@ -853,8 +916,9 @@ assert [b'line'] == list(d for d, _ in buf._buffer) assert buf._eof - def test_feed_eof_err(self, stream): - buf = aiohttp.FlowControlDataQueue(stream) + async def test_feed_eof_err_deflate(self, stream) -> None: + buf = aiohttp.FlowControlDataQueue(stream, + loop=asyncio.get_event_loop()) dbuf = DeflateBuffer(buf, 'deflate') dbuf.decompressor = mock.Mock() @@ -864,8 +928,33 @@ with pytest.raises(http_exceptions.ContentEncodingError): dbuf.feed_eof() - def test_empty_body(self, stream): - buf = aiohttp.FlowControlDataQueue(stream) + async def test_feed_eof_no_err_gzip(self, stream) -> None: + buf = aiohttp.FlowControlDataQueue(stream, + loop=asyncio.get_event_loop()) + dbuf = DeflateBuffer(buf, 'gzip') + + dbuf.decompressor = mock.Mock() + dbuf.decompressor.flush.return_value = b'line' + dbuf.decompressor.eof = False + + dbuf.feed_eof() + assert [b'line'] == list(d for d, _ in buf._buffer) + + async def test_feed_eof_no_err_brotli(self, stream) -> None: + buf = aiohttp.FlowControlDataQueue(stream, + loop=asyncio.get_event_loop()) + dbuf = DeflateBuffer(buf, 'br') + + dbuf.decompressor = mock.Mock() + dbuf.decompressor.flush.return_value = b'line' + dbuf.decompressor.eof = False + + dbuf.feed_eof() + assert [b'line'] == list(d for d, _ in buf._buffer) + + async def test_empty_body(self, stream) -> None: + buf = aiohttp.FlowControlDataQueue(stream, + loop=asyncio.get_event_loop()) dbuf = DeflateBuffer(buf, 'deflate') dbuf.feed_eof() diff -Nru python-aiohttp-3.1.3/tests/test_http_writer.py python-aiohttp-3.5.1/tests/test_http_writer.py --- python-aiohttp-3.1.3/tests/test_http_writer.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_http_writer.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,5 +1,4 @@ """Tests for aiohttp/http_writer.py""" -import asyncio import zlib from unittest import mock @@ -33,15 +32,16 @@ return protocol -def test_payloadwriter_properties(transport, protocol, loop): - writer = http.StreamWriter(protocol, transport, loop) +def test_payloadwriter_properties(transport, + protocol, loop) -> None: + writer = http.StreamWriter(protocol, loop) assert writer.protocol == protocol assert writer.transport == transport -async def test_write_payload_eof(transport, protocol, loop): +async def test_write_payload_eof(transport, protocol, loop) -> None: write = transport.write = mock.Mock() - msg = http.StreamWriter(protocol, transport, loop) + msg = http.StreamWriter(protocol, loop) await msg.write(b'data1') await msg.write(b'data2') @@ -51,8 +51,8 @@ assert b'data1data2' == content.split(b'\r\n\r\n', 1)[-1] -async def test_write_payload_chunked(buf, protocol, transport, loop): - msg = http.StreamWriter(protocol, transport, loop) +async def test_write_payload_chunked(buf, protocol, transport, loop) -> None: + msg = http.StreamWriter(protocol, loop) msg.enable_chunking() await msg.write(b'data') await msg.write_eof() @@ -60,8 +60,10 @@ assert b'4\r\ndata\r\n0\r\n\r\n' == buf -async def test_write_payload_chunked_multiple(buf, protocol, transport, loop): - msg = http.StreamWriter(protocol, transport, loop) +async def test_write_payload_chunked_multiple(buf, + protocol, + transport, loop) -> None: + msg = http.StreamWriter(protocol, loop) msg.enable_chunking() await msg.write(b'data1') await msg.write(b'data2') @@ -70,10 +72,10 @@ assert b'5\r\ndata1\r\n5\r\ndata2\r\n0\r\n\r\n' == buf -async def test_write_payload_length(protocol, transport, loop): +async def test_write_payload_length(protocol, transport, loop) -> None: write = transport.write = mock.Mock() - msg = http.StreamWriter(protocol, transport, loop) + msg = http.StreamWriter(protocol, loop) msg.length = 2 await msg.write(b'd') await msg.write(b'ata') @@ -83,10 +85,10 @@ assert b'da' == content.split(b'\r\n\r\n', 1)[-1] -async def test_write_payload_chunked_filter(protocol, transport, loop): +async def test_write_payload_chunked_filter(protocol, transport, loop) -> None: write = transport.write = mock.Mock() - msg = http.StreamWriter(protocol, transport, loop) + msg = http.StreamWriter(protocol, loop) msg.enable_chunking() await msg.write(b'da') await msg.write(b'ta') @@ -101,7 +103,7 @@ transport, loop): write = transport.write = mock.Mock() - msg = http.StreamWriter(protocol, transport, loop) + msg = http.StreamWriter(protocol, loop) msg.enable_chunking() await msg.write(b'da') await msg.write(b'ta') @@ -119,9 +121,10 @@ COMPRESSED = b''.join([compressor.compress(b'data'), compressor.flush()]) -async def test_write_payload_deflate_compression(protocol, transport, loop): +async def test_write_payload_deflate_compression(protocol, + transport, loop) -> None: write = transport.write = mock.Mock() - msg = http.StreamWriter(protocol, transport, loop) + msg = http.StreamWriter(protocol, loop) msg.enable_compression('deflate') await msg.write(b'data') await msg.write_eof() @@ -137,7 +140,7 @@ protocol, transport, loop): - msg = http.StreamWriter(protocol, transport, loop) + msg = http.StreamWriter(protocol, loop) msg.enable_compression('deflate') msg.enable_chunking() @@ -148,8 +151,8 @@ assert b'6\r\nKI,I\x04\x00\r\n0\r\n\r\n' == buf -async def test_write_drain(protocol, transport, loop): - msg = http.StreamWriter(protocol, transport, loop) +async def test_write_drain(protocol, transport, loop) -> None: + msg = http.StreamWriter(protocol, loop) msg.drain = make_mocked_coro() await msg.write(b'1' * (64 * 1024 * 2), drain=False) assert not msg.drain.called @@ -159,10 +162,10 @@ assert msg.buffer_size == 0 -async def test_write_calls_callback(protocol, transport, loop): +async def test_write_calls_callback(protocol, transport, loop) -> None: on_chunk_sent = make_mocked_coro() msg = http.StreamWriter( - protocol, transport, loop, + protocol, loop, on_chunk_sent=on_chunk_sent ) chunk = b'1' @@ -171,10 +174,10 @@ assert on_chunk_sent.call_args == mock.call(chunk) -async def test_write_eof_calls_callback(protocol, transport, loop): +async def test_write_eof_calls_callback(protocol, transport, loop) -> None: on_chunk_sent = make_mocked_coro() msg = http.StreamWriter( - protocol, transport, loop, + protocol, loop, on_chunk_sent=on_chunk_sent ) chunk = b'1' @@ -183,24 +186,24 @@ assert on_chunk_sent.call_args == mock.call(chunk) -async def test_write_to_closing_transport(protocol, transport, loop): - msg = http.StreamWriter(protocol, transport, loop) +async def test_write_to_closing_transport(protocol, transport, loop) -> None: + msg = http.StreamWriter(protocol, loop) await msg.write(b'Before closing') transport.is_closing.return_value = True - with pytest.raises(asyncio.CancelledError): + with pytest.raises(ConnectionResetError): await msg.write(b'After closing') -async def test_drain(protocol, transport, loop): - msg = http.StreamWriter(protocol, transport, loop) +async def test_drain(protocol, transport, loop) -> None: + msg = http.StreamWriter(protocol, loop) await msg.drain() assert protocol._drain_helper.called -async def test_drain_no_transport(protocol, transport, loop): - msg = http.StreamWriter(protocol, transport, loop) +async def test_drain_no_transport(protocol, transport, loop) -> None: + msg = http.StreamWriter(protocol, loop) msg._protocol.transport = None await msg.drain() assert not protocol._drain_helper.called diff -Nru python-aiohttp-3.1.3/tests/test_locks.py python-aiohttp-3.5.1/tests/test_locks.py --- python-aiohttp-3.1.3/tests/test_locks.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_locks.py 2018-12-24 20:58:54.000000000 +0000 @@ -8,7 +8,7 @@ class TestEventResultOrError: - async def test_set_exception(self, loop): + async def test_set_exception(self, loop) -> None: ev = EventResultOrError(loop=loop) async def c(): @@ -24,7 +24,7 @@ ev.set(exc=e) assert (await t) == e - async def test_set(self, loop): + async def test_set(self, loop) -> None: ev = EventResultOrError(loop=loop) async def c(): @@ -36,7 +36,7 @@ ev.set() assert (await t) == 1 - async def test_cancel_waiters(self, loop): + async def test_cancel_waiters(self, loop) -> None: ev = EventResultOrError(loop=loop) async def c(): diff -Nru python-aiohttp-3.1.3/tests/test_loop.py python-aiohttp-3.5.1/tests/test_loop.py --- python-aiohttp-3.1.3/tests/test_loop.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_loop.py 2018-12-24 20:58:54.000000000 +0000 @@ -10,7 +10,7 @@ @pytest.mark.skipif(platform.system() == "Windows", reason="the test is not valid for Windows") -async def test_subprocess_co(loop): +async def test_subprocess_co(loop) -> None: assert isinstance(threading.current_thread(), threading._MainThread) proc = await asyncio.create_subprocess_shell( "exit 0", loop=loop, stdin=asyncio.subprocess.DEVNULL, @@ -25,15 +25,15 @@ return app async def on_startup_hook(self, app): - self.startup_loop = app.loop + self.on_startup_called = True @unittest_run_loop - async def test_on_startup_hook(self): - self.assertIsNotNone(self.startup_loop) + async def test_on_startup_hook(self) -> None: + self.assertTrue(self.on_startup_called) - def test_default_loop(self): + def test_default_loop(self) -> None: self.assertIs(self.loop, asyncio.get_event_loop()) -def test_default_loop(loop): +def test_default_loop(loop) -> None: assert asyncio.get_event_loop() is loop diff -Nru python-aiohttp-3.1.3/tests/test_multipart_helpers.py python-aiohttp-3.5.1/tests/test_multipart_helpers.py --- python-aiohttp-3.1.3/tests/test_multipart_helpers.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_multipart_helpers.py 2018-12-24 20:58:54.000000000 +0000 @@ -7,419 +7,419 @@ class TestParseContentDisposition: # http://greenbytes.de/tech/tc2231/ - def test_parse_empty(self): + def test_parse_empty(self) -> None: disptype, params = parse_content_disposition(None) assert disptype is None assert {} == params - def test_inlonly(self): + def test_inlonly(self) -> None: disptype, params = parse_content_disposition('inline') assert 'inline' == disptype assert {} == params - def test_inlonlyquoted(self): + def test_inlonlyquoted(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition('"inline"') assert disptype is None assert {} == params - def test_semicolon(self): + def test_semicolon(self) -> None: disptype, params = parse_content_disposition( 'form-data; name="data"; filename="file ; name.mp4"') assert disptype == 'form-data' assert params == {'name': 'data', 'filename': 'file ; name.mp4'} - def test_inlwithasciifilename(self): + def test_inlwithasciifilename(self) -> None: disptype, params = parse_content_disposition( 'inline; filename="foo.html"') assert 'inline' == disptype assert {'filename': 'foo.html'} == params - def test_inlwithfnattach(self): + def test_inlwithfnattach(self) -> None: disptype, params = parse_content_disposition( 'inline; filename="Not an attachment!"') assert 'inline' == disptype assert {'filename': 'Not an attachment!'} == params - def test_attonly(self): + def test_attonly(self) -> None: disptype, params = parse_content_disposition('attachment') assert 'attachment' == disptype assert {} == params - def test_attonlyquoted(self): + def test_attonlyquoted(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition('"attachment"') assert disptype is None assert {} == params - def test_attonlyucase(self): + def test_attonlyucase(self) -> None: disptype, params = parse_content_disposition('ATTACHMENT') assert 'attachment' == disptype assert {} == params - def test_attwithasciifilename(self): + def test_attwithasciifilename(self) -> None: disptype, params = parse_content_disposition( 'attachment; filename="foo.html"') assert 'attachment' == disptype assert {'filename': 'foo.html'} == params - def test_inlwithasciifilenamepdf(self): + def test_inlwithasciifilenamepdf(self) -> None: disptype, params = parse_content_disposition( 'attachment; filename="foo.pdf"') assert 'attachment' == disptype assert {'filename': 'foo.pdf'} == params - def test_attwithasciifilename25(self): + def test_attwithasciifilename25(self) -> None: disptype, params = parse_content_disposition( 'attachment; filename="0000000000111111111122222"') assert 'attachment' == disptype assert {'filename': '0000000000111111111122222'} == params - def test_attwithasciifilename35(self): + def test_attwithasciifilename35(self) -> None: disptype, params = parse_content_disposition( 'attachment; filename="00000000001111111111222222222233333"') assert 'attachment' == disptype assert {'filename': '00000000001111111111222222222233333'} == params - def test_attwithasciifnescapedchar(self): + def test_attwithasciifnescapedchar(self) -> None: disptype, params = parse_content_disposition( r'attachment; filename="f\oo.html"') assert 'attachment' == disptype assert {'filename': 'foo.html'} == params - def test_attwithasciifnescapedquote(self): + def test_attwithasciifnescapedquote(self) -> None: disptype, params = parse_content_disposition( 'attachment; filename="\"quoting\" tested.html"') assert 'attachment' == disptype assert {'filename': '"quoting" tested.html'} == params @pytest.mark.skip('need more smart parser which respects quoted text') - def test_attwithquotedsemicolon(self): + def test_attwithquotedsemicolon(self) -> None: disptype, params = parse_content_disposition( 'attachment; filename="Here\'s a semicolon;.html"') assert 'attachment' == disptype assert {'filename': 'Here\'s a semicolon;.html'} == params - def test_attwithfilenameandextparam(self): + def test_attwithfilenameandextparam(self) -> None: disptype, params = parse_content_disposition( 'attachment; foo="bar"; filename="foo.html"') assert 'attachment' == disptype assert {'filename': 'foo.html', 'foo': 'bar'} == params - def test_attwithfilenameandextparamescaped(self): + def test_attwithfilenameandextparamescaped(self) -> None: disptype, params = parse_content_disposition( 'attachment; foo="\"\\";filename="foo.html"') assert 'attachment' == disptype assert {'filename': 'foo.html', 'foo': '"\\'} == params - def test_attwithasciifilenameucase(self): + def test_attwithasciifilenameucase(self) -> None: disptype, params = parse_content_disposition( 'attachment; FILENAME="foo.html"') assert 'attachment' == disptype assert {'filename': 'foo.html'} == params - def test_attwithasciifilenamenq(self): + def test_attwithasciifilenamenq(self) -> None: disptype, params = parse_content_disposition( 'attachment; filename=foo.html') assert 'attachment' == disptype assert {'filename': 'foo.html'} == params - def test_attwithtokfncommanq(self): + def test_attwithtokfncommanq(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition( 'attachment; filename=foo,bar.html') assert disptype is None assert {} == params - def test_attwithasciifilenamenqs(self): + def test_attwithasciifilenamenqs(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition( 'attachment; filename=foo.html ;') assert disptype is None assert {} == params - def test_attemptyparam(self): + def test_attemptyparam(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition( 'attachment; ;filename=foo') assert disptype is None assert {} == params - def test_attwithasciifilenamenqws(self): + def test_attwithasciifilenamenqws(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition( 'attachment; filename=foo bar.html') assert disptype is None assert {} == params - def test_attwithfntokensq(self): + def test_attwithfntokensq(self) -> None: disptype, params = parse_content_disposition( "attachment; filename='foo.html'") assert 'attachment' == disptype assert {'filename': "'foo.html'"} == params - def test_attwithisofnplain(self): + def test_attwithisofnplain(self) -> None: disptype, params = parse_content_disposition( 'attachment; filename="foo-ä.html"') assert 'attachment' == disptype assert {'filename': 'foo-ä.html'} == params - def test_attwithutf8fnplain(self): + def test_attwithutf8fnplain(self) -> None: disptype, params = parse_content_disposition( 'attachment; filename="foo-ä.html"') assert 'attachment' == disptype assert {'filename': 'foo-ä.html'} == params - def test_attwithfnrawpctenca(self): + def test_attwithfnrawpctenca(self) -> None: disptype, params = parse_content_disposition( 'attachment; filename="foo-%41.html"') assert 'attachment' == disptype assert {'filename': 'foo-%41.html'} == params - def test_attwithfnusingpct(self): + def test_attwithfnusingpct(self) -> None: disptype, params = parse_content_disposition( 'attachment; filename="50%.html"') assert 'attachment' == disptype assert {'filename': '50%.html'} == params - def test_attwithfnrawpctencaq(self): + def test_attwithfnrawpctencaq(self) -> None: disptype, params = parse_content_disposition( r'attachment; filename="foo-%\41.html"') assert 'attachment' == disptype assert {'filename': r'foo-%41.html'} == params - def test_attwithnamepct(self): + def test_attwithnamepct(self) -> None: disptype, params = parse_content_disposition( 'attachment; filename="foo-%41.html"') assert 'attachment' == disptype assert {'filename': 'foo-%41.html'} == params - def test_attwithfilenamepctandiso(self): + def test_attwithfilenamepctandiso(self) -> None: disptype, params = parse_content_disposition( 'attachment; filename="ä-%41.html"') assert 'attachment' == disptype assert {'filename': 'ä-%41.html'} == params - def test_attwithfnrawpctenclong(self): + def test_attwithfnrawpctenclong(self) -> None: disptype, params = parse_content_disposition( 'attachment; filename="foo-%c3%a4-%e2%82%ac.html"') assert 'attachment' == disptype assert {'filename': 'foo-%c3%a4-%e2%82%ac.html'} == params - def test_attwithasciifilenamews1(self): + def test_attwithasciifilenamews1(self) -> None: disptype, params = parse_content_disposition( 'attachment; filename ="foo.html"') assert 'attachment' == disptype assert {'filename': 'foo.html'} == params - def test_attwith2filenames(self): + def test_attwith2filenames(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition( 'attachment; filename="foo.html"; filename="bar.html"') assert disptype is None assert {} == params - def test_attfnbrokentoken(self): + def test_attfnbrokentoken(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition( 'attachment; filename=foo[1](2).html') assert disptype is None assert {} == params - def test_attfnbrokentokeniso(self): + def test_attfnbrokentokeniso(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition( 'attachment; filename=foo-ä.html') assert disptype is None assert {} == params - def test_attfnbrokentokenutf(self): + def test_attfnbrokentokenutf(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition( 'attachment; filename=foo-ä.html') assert disptype is None assert {} == params - def test_attmissingdisposition(self): + def test_attmissingdisposition(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition( 'filename=foo.html') assert disptype is None assert {} == params - def test_attmissingdisposition2(self): + def test_attmissingdisposition2(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition( 'x=y; filename=foo.html') assert disptype is None assert {} == params - def test_attmissingdisposition3(self): + def test_attmissingdisposition3(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition( '"foo; filename=bar;baz"; filename=qux') assert disptype is None assert {} == params - def test_attmissingdisposition4(self): + def test_attmissingdisposition4(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition( 'filename=foo.html, filename=bar.html') assert disptype is None assert {} == params - def test_emptydisposition(self): + def test_emptydisposition(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition( '; filename=foo.html') assert disptype is None assert {} == params - def test_doublecolon(self): + def test_doublecolon(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition( ': inline; attachment; filename=foo.html') assert disptype is None assert {} == params - def test_attandinline(self): + def test_attandinline(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition( 'inline; attachment; filename=foo.html') assert disptype is None assert {} == params - def test_attandinline2(self): + def test_attandinline2(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition( 'attachment; inline; filename=foo.html') assert disptype is None assert {} == params - def test_attbrokenquotedfn(self): + def test_attbrokenquotedfn(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition( 'attachment; filename="foo.html".txt') assert disptype is None assert {} == params - def test_attbrokenquotedfn2(self): + def test_attbrokenquotedfn2(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition( 'attachment; filename="bar') assert disptype is None assert {} == params - def test_attbrokenquotedfn3(self): + def test_attbrokenquotedfn3(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition( 'attachment; filename=foo"bar;baz"qux') assert disptype is None assert {} == params - def test_attmultinstances(self): + def test_attmultinstances(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition( 'attachment; filename=foo.html, attachment; filename=bar.html') assert disptype is None assert {} == params - def test_attmissingdelim(self): + def test_attmissingdelim(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition( 'attachment; foo=foo filename=bar') assert disptype is None assert {} == params - def test_attmissingdelim2(self): + def test_attmissingdelim2(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition( 'attachment; filename=bar foo=foo') assert disptype is None assert {} == params - def test_attmissingdelim3(self): + def test_attmissingdelim3(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition( 'attachment filename=bar') assert disptype is None assert {} == params - def test_attreversed(self): + def test_attreversed(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition( 'filename=foo.html; attachment') assert disptype is None assert {} == params - def test_attconfusedparam(self): + def test_attconfusedparam(self) -> None: disptype, params = parse_content_disposition( 'attachment; xfilename=foo.html') assert 'attachment' == disptype assert {'xfilename': 'foo.html'} == params - def test_attabspath(self): + def test_attabspath(self) -> None: disptype, params = parse_content_disposition( 'attachment; filename="/foo.html"') assert 'attachment' == disptype assert {'filename': 'foo.html'} == params - def test_attabspathwin(self): + def test_attabspathwin(self) -> None: disptype, params = parse_content_disposition( 'attachment; filename="\\foo.html"') assert 'attachment' == disptype assert {'filename': 'foo.html'} == params - def test_attcdate(self): + def test_attcdate(self) -> None: disptype, params = parse_content_disposition( 'attachment; creation-date="Wed, 12 Feb 1997 16:29:51 -0500"') assert 'attachment' == disptype assert {'creation-date': 'Wed, 12 Feb 1997 16:29:51 -0500'} == params - def test_attmdate(self): + def test_attmdate(self) -> None: disptype, params = parse_content_disposition( 'attachment; modification-date="Wed, 12 Feb 1997 16:29:51 -0500"') assert 'attachment' == disptype assert {'modification-date': 'Wed, 12 Feb 1997 16:29:51 -0500'} == params - def test_dispext(self): + def test_dispext(self) -> None: disptype, params = parse_content_disposition('foobar') assert 'foobar' == disptype assert {} == params - def test_dispextbadfn(self): + def test_dispextbadfn(self) -> None: disptype, params = parse_content_disposition( 'attachment; example="filename=example.txt"') assert 'attachment' == disptype assert {'example': 'filename=example.txt'} == params - def test_attwithisofn2231iso(self): + def test_attwithisofn2231iso(self) -> None: disptype, params = parse_content_disposition( "attachment; filename*=iso-8859-1''foo-%E4.html") assert 'attachment' == disptype assert {'filename*': 'foo-ä.html'} == params - def test_attwithfn2231utf8(self): + def test_attwithfn2231utf8(self) -> None: disptype, params = parse_content_disposition( "attachment; filename*=UTF-8''foo-%c3%a4-%e2%82%ac.html") assert 'attachment' == disptype assert {'filename*': 'foo-ä-€.html'} == params - def test_attwithfn2231noc(self): + def test_attwithfn2231noc(self) -> None: disptype, params = parse_content_disposition( "attachment; filename*=''foo-%c3%a4-%e2%82%ac.html") assert 'attachment' == disptype assert {'filename*': 'foo-ä-€.html'} == params - def test_attwithfn2231utf8comp(self): + def test_attwithfn2231utf8comp(self) -> None: disptype, params = parse_content_disposition( "attachment; filename*=UTF-8''foo-a%cc%88.html") assert 'attachment' == disptype assert {'filename*': 'foo-ä.html'} == params @pytest.mark.skip('should raise decoding error: %82 is invalid for latin1') - def test_attwithfn2231utf8_bad(self): + def test_attwithfn2231utf8_bad(self) -> None: with pytest.warns(aiohttp.BadContentDispositionParam): disptype, params = parse_content_disposition( "attachment; filename*=iso-8859-1''foo-%c3%a4-%e2%82%ac.html") @@ -427,47 +427,47 @@ assert {} == params @pytest.mark.skip('should raise decoding error: %E4 is invalid for utf-8') - def test_attwithfn2231iso_bad(self): + def test_attwithfn2231iso_bad(self) -> None: with pytest.warns(aiohttp.BadContentDispositionParam): disptype, params = parse_content_disposition( "attachment; filename*=utf-8''foo-%E4.html") assert 'attachment' == disptype assert {} == params - def test_attwithfn2231ws1(self): + def test_attwithfn2231ws1(self) -> None: with pytest.warns(aiohttp.BadContentDispositionParam): disptype, params = parse_content_disposition( "attachment; filename *=UTF-8''foo-%c3%a4.html") assert 'attachment' == disptype assert {} == params - def test_attwithfn2231ws2(self): + def test_attwithfn2231ws2(self) -> None: disptype, params = parse_content_disposition( "attachment; filename*= UTF-8''foo-%c3%a4.html") assert 'attachment' == disptype assert {'filename*': 'foo-ä.html'} == params - def test_attwithfn2231ws3(self): + def test_attwithfn2231ws3(self) -> None: disptype, params = parse_content_disposition( "attachment; filename* =UTF-8''foo-%c3%a4.html") assert 'attachment' == disptype assert {'filename*': 'foo-ä.html'} == params - def test_attwithfn2231quot(self): + def test_attwithfn2231quot(self) -> None: with pytest.warns(aiohttp.BadContentDispositionParam): disptype, params = parse_content_disposition( "attachment; filename*=\"UTF-8''foo-%c3%a4.html\"") assert 'attachment' == disptype assert {} == params - def test_attwithfn2231quot2(self): + def test_attwithfn2231quot2(self) -> None: with pytest.warns(aiohttp.BadContentDispositionParam): disptype, params = parse_content_disposition( "attachment; filename*=\"foo%20bar.html\"") assert 'attachment' == disptype assert {} == params - def test_attwithfn2231singleqmissing(self): + def test_attwithfn2231singleqmissing(self) -> None: with pytest.warns(aiohttp.BadContentDispositionParam): disptype, params = parse_content_disposition( "attachment; filename*=UTF-8'foo-%c3%a4.html") @@ -475,7 +475,7 @@ assert {} == params @pytest.mark.skip('urllib.parse.unquote is tolerate to standalone % chars') - def test_attwithfn2231nbadpct1(self): + def test_attwithfn2231nbadpct1(self) -> None: with pytest.warns(aiohttp.BadContentDispositionParam): disptype, params = parse_content_disposition( "attachment; filename*=UTF-8''foo%") @@ -483,75 +483,75 @@ assert {} == params @pytest.mark.skip('urllib.parse.unquote is tolerate to standalone % chars') - def test_attwithfn2231nbadpct2(self): + def test_attwithfn2231nbadpct2(self) -> None: with pytest.warns(aiohttp.BadContentDispositionParam): disptype, params = parse_content_disposition( "attachment; filename*=UTF-8''f%oo.html") assert 'attachment' == disptype assert {} == params - def test_attwithfn2231dpct(self): + def test_attwithfn2231dpct(self) -> None: disptype, params = parse_content_disposition( "attachment; filename*=UTF-8''A-%2541.html") assert 'attachment' == disptype assert {'filename*': 'A-%41.html'} == params - def test_attwithfn2231abspathdisguised(self): + def test_attwithfn2231abspathdisguised(self) -> None: disptype, params = parse_content_disposition( "attachment; filename*=UTF-8''%5cfoo.html") assert 'attachment' == disptype assert {'filename*': '\\foo.html'} == params - def test_attfncont(self): + def test_attfncont(self) -> None: disptype, params = parse_content_disposition( 'attachment; filename*0="foo."; filename*1="html"') assert 'attachment' == disptype assert {'filename*0': 'foo.', 'filename*1': 'html'} == params - def test_attfncontqs(self): + def test_attfncontqs(self) -> None: disptype, params = parse_content_disposition( r'attachment; filename*0="foo"; filename*1="\b\a\r.html"') assert 'attachment' == disptype assert {'filename*0': 'foo', 'filename*1': 'bar.html'} == params - def test_attfncontenc(self): + def test_attfncontenc(self) -> None: disptype, params = parse_content_disposition( 'attachment; filename*0*=UTF-8''foo-%c3%a4; filename*1=".html"') assert 'attachment' == disptype assert {'filename*0*': 'UTF-8''foo-%c3%a4', 'filename*1': '.html'} == params - def test_attfncontlz(self): + def test_attfncontlz(self) -> None: disptype, params = parse_content_disposition( 'attachment; filename*0="foo"; filename*01="bar"') assert 'attachment' == disptype assert {'filename*0': 'foo', 'filename*01': 'bar'} == params - def test_attfncontnc(self): + def test_attfncontnc(self) -> None: disptype, params = parse_content_disposition( 'attachment; filename*0="foo"; filename*2="bar"') assert 'attachment' == disptype assert {'filename*0': 'foo', 'filename*2': 'bar'} == params - def test_attfnconts1(self): + def test_attfnconts1(self) -> None: disptype, params = parse_content_disposition( 'attachment; filename*0="foo."; filename*2="html"') assert 'attachment' == disptype assert {'filename*0': 'foo.', 'filename*2': 'html'} == params - def test_attfncontord(self): + def test_attfncontord(self) -> None: disptype, params = parse_content_disposition( 'attachment; filename*1="bar"; filename*0="foo"') assert 'attachment' == disptype assert {'filename*0': 'foo', 'filename*1': 'bar'} == params - def test_attfnboth(self): + def test_attfnboth(self) -> None: disptype, params = parse_content_disposition( 'attachment; filename="foo-ae.html";' " filename*=UTF-8''foo-%c3%a4.html") @@ -559,7 +559,7 @@ assert {'filename': 'foo-ae.html', 'filename*': 'foo-ä.html'} == params - def test_attfnboth2(self): + def test_attfnboth2(self) -> None: disptype, params = parse_content_disposition( "attachment; filename*=UTF-8''foo-%c3%a4.html;" ' filename="foo-ae.html"') @@ -567,7 +567,7 @@ assert {'filename': 'foo-ae.html', 'filename*': 'foo-ä.html'} == params - def test_attfnboth3(self): + def test_attfnboth3(self) -> None: disptype, params = parse_content_disposition( "attachment; filename*0*=ISO-8859-15''euro-sign%3d%a4;" " filename*=ISO-8859-1''currency-sign%3d%a4") @@ -575,27 +575,27 @@ assert {'filename*': 'currency-sign=¤', 'filename*0*': "ISO-8859-15''euro-sign%3d%a4"} == params - def test_attnewandfn(self): + def test_attnewandfn(self) -> None: disptype, params = parse_content_disposition( 'attachment; foobar=x; filename="foo.html"') assert 'attachment' == disptype assert {'foobar': 'x', 'filename': 'foo.html'} == params - def test_attrfc2047token(self): + def test_attrfc2047token(self) -> None: with pytest.warns(aiohttp.BadContentDispositionHeader): disptype, params = parse_content_disposition( 'attachment; filename==?ISO-8859-1?Q?foo-=E4.html?=') assert disptype is None assert {} == params - def test_attrfc2047quoted(self): + def test_attrfc2047quoted(self) -> None: disptype, params = parse_content_disposition( 'attachment; filename="=?ISO-8859-1?Q?foo-=E4.html?="') assert 'attachment' == disptype assert {'filename': '=?ISO-8859-1?Q?foo-=E4.html?='} == params - def test_bad_continuous_param(self): + def test_bad_continuous_param(self) -> None: with pytest.warns(aiohttp.BadContentDispositionParam): disptype, params = parse_content_disposition( 'attachment; filename*0=foo bar') @@ -606,57 +606,57 @@ class TestContentDispositionFilename: # http://greenbytes.de/tech/tc2231/ - def test_no_filename(self): + def test_no_filename(self) -> None: assert content_disposition_filename({}) is None assert content_disposition_filename({'foo': 'bar'}) is None - def test_filename(self): + def test_filename(self) -> None: params = {'filename': 'foo.html'} assert 'foo.html' == content_disposition_filename(params) - def test_filename_ext(self): + def test_filename_ext(self) -> None: params = {'filename*': 'файл.html'} assert 'файл.html' == content_disposition_filename(params) - def test_attfncont(self): + def test_attfncont(self) -> None: params = {'filename*0': 'foo.', 'filename*1': 'html'} assert 'foo.html' == content_disposition_filename(params) - def test_attfncontqs(self): + def test_attfncontqs(self) -> None: params = {'filename*0': 'foo', 'filename*1': 'bar.html'} assert 'foobar.html' == content_disposition_filename(params) - def test_attfncontenc(self): + def test_attfncontenc(self) -> None: params = {'filename*0*': "UTF-8''foo-%c3%a4", 'filename*1': '.html'} assert 'foo-ä.html' == content_disposition_filename(params) - def test_attfncontlz(self): + def test_attfncontlz(self) -> None: params = {'filename*0': 'foo', 'filename*01': 'bar'} assert 'foo' == content_disposition_filename(params) - def test_attfncontnc(self): + def test_attfncontnc(self) -> None: params = {'filename*0': 'foo', 'filename*2': 'bar'} assert 'foo' == content_disposition_filename(params) - def test_attfnconts1(self): + def test_attfnconts1(self) -> None: params = {'filename*1': 'foo', 'filename*2': 'bar'} assert content_disposition_filename(params) is None - def test_attfnboth(self): + def test_attfnboth(self) -> None: params = {'filename': 'foo-ae.html', 'filename*': 'foo-ä.html'} assert 'foo-ä.html' == content_disposition_filename(params) - def test_attfnboth3(self): + def test_attfnboth3(self) -> None: params = {'filename*0*': "ISO-8859-15''euro-sign%3d%a4", 'filename*': 'currency-sign=¤'} assert 'currency-sign=¤' == content_disposition_filename(params) - def test_attrfc2047quoted(self): + def test_attrfc2047quoted(self) -> None: params = {'filename': '=?ISO-8859-1?Q?foo-=E4.html?='} assert '=?ISO-8859-1?Q?foo-=E4.html?=' == content_disposition_filename( params) diff -Nru python-aiohttp-3.1.3/tests/test_multipart.py python-aiohttp-3.5.1/tests/test_multipart.py --- python-aiohttp-3.1.3/tests/test_multipart.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_multipart.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,3 +1,4 @@ +import asyncio import io import json import zlib @@ -80,13 +81,13 @@ class TestMultipartResponseWrapper: - def test_at_eof(self): + def test_at_eof(self) -> None: wrapper = MultipartResponseWrapper(mock.Mock(), mock.Mock()) wrapper.at_eof() assert wrapper.resp.content.at_eof.called - async def test_next(self): + async def test_next(self) -> None: wrapper = MultipartResponseWrapper(mock.Mock(), mock.Mock()) wrapper.stream.next = make_mocked_coro(b'') @@ -94,14 +95,14 @@ await wrapper.next() assert wrapper.stream.next.called - async def test_release(self): + async def test_release(self) -> None: wrapper = MultipartResponseWrapper(mock.Mock(), mock.Mock()) wrapper.resp.release = make_mocked_coro(None) await wrapper.release() assert wrapper.resp.release.called - async def test_release_when_stream_at_eof(self): + async def test_release_when_stream_at_eof(self) -> None: wrapper = MultipartResponseWrapper(mock.Mock(), mock.Mock()) wrapper.resp.release = make_mocked_coro(None) @@ -114,14 +115,14 @@ class TestPartReader: - async def test_next(self): + async def test_next(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {}, Stream(b'Hello, world!\r\n--:')) result = await obj.next() assert b'Hello, world!' == result assert obj.at_eof() - async def test_next_next(self): + async def test_next_next(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {}, Stream(b'Hello, world!\r\n--:')) result = await obj.next() @@ -130,21 +131,21 @@ result = await obj.next() assert result is None - async def test_read(self): + async def test_read(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {}, Stream(b'Hello, world!\r\n--:')) result = await obj.read() assert b'Hello, world!' == result assert obj.at_eof() - async def test_read_chunk_at_eof(self): + async def test_read_chunk_at_eof(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {}, Stream(b'--:')) obj._at_eof = True result = await obj.read_chunk() assert b'' == result - async def test_read_chunk_without_content_length(self): + async def test_read_chunk_without_content_length(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {}, Stream(b'Hello, world!\r\n--:')) c1 = await obj.read_chunk(8) @@ -153,7 +154,8 @@ assert c1 + c2 == b'Hello, world!' assert c3 == b'' - async def test_read_incomplete_chunk(self, loop): + async def test_read_incomplete_chunk(self) -> None: + loop = asyncio.get_event_loop() stream = Stream(b'') def prepare(data): @@ -176,7 +178,7 @@ c3 = await obj.read_chunk(8) assert c3 == b'!' - async def test_read_all_at_once(self): + async def test_read_all_at_once(self) -> None: stream = Stream(b'Hello, World!\r\n--:--\r\n') obj = aiohttp.BodyPartReader(BOUNDARY, {}, stream) result = await obj.read_chunk() @@ -185,7 +187,7 @@ assert b'' == result assert obj.at_eof() - async def test_read_incomplete_body_chunked(self): + async def test_read_incomplete_body_chunked(self) -> None: stream = Stream(b'Hello, World!\r\n-') obj = aiohttp.BodyPartReader(BOUNDARY, {}, stream) result = b'' @@ -194,7 +196,8 @@ result += await obj.read_chunk(7) assert b'Hello, World!\r\n-' == result - async def test_read_boundary_with_incomplete_chunk(self, loop): + async def test_read_boundary_with_incomplete_chunk(self) -> None: + loop = asyncio.get_event_loop() stream = Stream(b'') def prepare(data): @@ -217,7 +220,7 @@ c3 = await obj.read_chunk(8) assert c3 == b'' - async def test_multi_read_chunk(self): + async def test_multi_read_chunk(self) -> None: stream = Stream(b'Hello,\r\n--:\r\n\r\nworld!\r\n--:--') obj = aiohttp.BodyPartReader(BOUNDARY, {}, stream) result = await obj.read_chunk(8) @@ -226,7 +229,7 @@ assert b'' == result assert obj.at_eof() - async def test_read_chunk_properly_counts_read_bytes(self): + async def test_read_chunk_properly_counts_read_bytes(self) -> None: expected = b'.' * 10 size = len(expected) obj = aiohttp.BodyPartReader( @@ -242,7 +245,7 @@ assert b'.' * size == result assert obj.at_eof() - async def test_read_does_not_read_boundary(self): + async def test_read_does_not_read_boundary(self) -> None: stream = Stream(b'Hello, world!\r\n--:') obj = aiohttp.BodyPartReader( BOUNDARY, {}, stream) @@ -250,7 +253,7 @@ assert b'Hello, world!' == result assert b'--:' == (await stream.read()) - async def test_multiread(self): + async def test_multiread(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {}, Stream(b'Hello,\r\n--:\r\n\r\nworld!\r\n--:--')) result = await obj.read() @@ -259,7 +262,7 @@ assert b'' == result assert obj.at_eof() - async def test_read_multiline(self): + async def test_read_multiline(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {}, Stream(b'Hello\n,\r\nworld!\r\n--:--')) result = await obj.read() @@ -268,7 +271,7 @@ assert b'' == result assert obj.at_eof() - async def test_read_respects_content_length(self): + async def test_read_respects_content_length(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {'CONTENT-LENGTH': 100500}, Stream(b'.' * 100500 + b'\r\n--:--')) @@ -276,7 +279,7 @@ assert b'.' * 100500 == result assert obj.at_eof() - async def test_read_with_content_encoding_gzip(self): + async def test_read_with_content_encoding_gzip(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {CONTENT_ENCODING: 'gzip'}, Stream(b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03\x0b\xc9\xccMU' @@ -285,14 +288,14 @@ result = await obj.read(decode=True) assert b'Time to Relax!' == result - async def test_read_with_content_encoding_deflate(self): + async def test_read_with_content_encoding_deflate(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {CONTENT_ENCODING: 'deflate'}, Stream(b'\x0b\xc9\xccMU(\xc9W\x08J\xcdI\xacP\x04\x00\r\n--:--')) result = await obj.read(decode=True) assert b'Time to Relax!' == result - async def test_read_with_content_encoding_identity(self): + async def test_read_with_content_encoding_identity(self) -> None: thing = (b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03\x0b\xc9\xccMU' b'(\xc9W\x08J\xcdI\xacP\x04\x00$\xfb\x9eV\x0e\x00\x00\x00' b'\r\n') @@ -302,21 +305,22 @@ result = await obj.read(decode=True) assert thing[:-2] == result - async def test_read_with_content_encoding_unknown(self): + async def test_read_with_content_encoding_unknown(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {CONTENT_ENCODING: 'snappy'}, Stream(b'\x0e4Time to Relax!\r\n--:--')) with pytest.raises(RuntimeError): await obj.read(decode=True) - async def test_read_with_content_transfer_encoding_base64(self): + async def test_read_with_content_transfer_encoding_base64(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {CONTENT_TRANSFER_ENCODING: 'base64'}, Stream(b'VGltZSB0byBSZWxheCE=\r\n--:--')) result = await obj.read(decode=True) assert b'Time to Relax!' == result - async def test_read_with_content_transfer_encoding_quoted_printable(self): + async def test_read_with_content_transfer_encoding_quoted_printable( + self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {CONTENT_TRANSFER_ENCODING: 'quoted-printable'}, Stream(b'=D0=9F=D1=80=D0=B8=D0=B2=D0=B5=D1=82,' @@ -327,7 +331,8 @@ assert result == expected @pytest.mark.parametrize('encoding', ('binary', '8bit', '7bit')) - async def test_read_with_content_transfer_encoding_binary(self, encoding): + async def test_read_with_content_transfer_encoding_binary( + self, encoding) -> None: data = b'\xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82,' \ b' \xd0\xbc\xd0\xb8\xd1\x80!' obj = aiohttp.BodyPartReader( @@ -336,41 +341,41 @@ result = await obj.read(decode=True) assert data == result - async def test_read_with_content_transfer_encoding_unknown(self): + async def test_read_with_content_transfer_encoding_unknown(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {CONTENT_TRANSFER_ENCODING: 'unknown'}, Stream(b'\x0e4Time to Relax!\r\n--:--')) with pytest.raises(RuntimeError): await obj.read(decode=True) - async def test_read_text(self): + async def test_read_text(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {}, Stream(b'Hello, world!\r\n--:--')) result = await obj.text() assert 'Hello, world!' == result - async def test_read_text_default_encoding(self): + async def test_read_text_default_encoding(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {}, Stream('Привет, Мир!\r\n--:--'.encode('utf-8'))) result = await obj.text() assert 'Привет, Мир!' == result - async def test_read_text_encoding(self): + async def test_read_text_encoding(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {}, Stream('Привет, Мир!\r\n--:--'.encode('cp1251'))) result = await obj.text(encoding='cp1251') assert 'Привет, Мир!' == result - async def test_read_text_guess_encoding(self): + async def test_read_text_guess_encoding(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {CONTENT_TYPE: 'text/plain;charset=cp1251'}, Stream('Привет, Мир!\r\n--:--'.encode('cp1251'))) result = await obj.text() assert 'Привет, Мир!' == result - async def test_read_text_compressed(self): + async def test_read_text_compressed(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {CONTENT_ENCODING: 'deflate', CONTENT_TYPE: 'text/plain'}, @@ -378,35 +383,35 @@ result = await obj.text() assert 'Time to Relax!' == result - async def test_read_text_while_closed(self): + async def test_read_text_while_closed(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {CONTENT_TYPE: 'text/plain'}, Stream(b'')) obj._at_eof = True result = await obj.text() assert '' == result - async def test_read_json(self): + async def test_read_json(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {CONTENT_TYPE: 'application/json'}, Stream(b'{"test": "passed"}\r\n--:--')) result = await obj.json() assert {'test': 'passed'} == result - async def test_read_json_encoding(self): + async def test_read_json_encoding(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {CONTENT_TYPE: 'application/json'}, Stream('{"тест": "пассед"}\r\n--:--'.encode('cp1251'))) result = await obj.json(encoding='cp1251') assert {'тест': 'пассед'} == result - async def test_read_json_guess_encoding(self): + async def test_read_json_guess_encoding(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {CONTENT_TYPE: 'application/json; charset=cp1251'}, Stream('{"тест": "пассед"}\r\n--:--'.encode('cp1251'))) result = await obj.json() assert {'тест': 'пассед'} == result - async def test_read_json_compressed(self): + async def test_read_json_compressed(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {CONTENT_ENCODING: 'deflate', CONTENT_TYPE: 'application/json'}, @@ -414,7 +419,7 @@ result = await obj.json() assert {'test': 'passed'} == result - async def test_read_json_while_closed(self): + async def test_read_json_while_closed(self) -> None: stream = Stream(b'') obj = aiohttp.BodyPartReader( BOUNDARY, {CONTENT_TYPE: 'application/json'}, stream) @@ -422,21 +427,21 @@ result = await obj.json() assert result is None - async def test_read_form(self): + async def test_read_form(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {CONTENT_TYPE: 'application/x-www-form-urlencoded'}, Stream(b'foo=bar&foo=baz&boo=\r\n--:--')) result = await obj.form() assert [('foo', 'bar'), ('foo', 'baz'), ('boo', '')] == result - async def test_read_form_encoding(self): + async def test_read_form_encoding(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {CONTENT_TYPE: 'application/x-www-form-urlencoded'}, Stream('foo=bar&foo=baz&boo=\r\n--:--'.encode('cp1251'))) result = await obj.form(encoding='cp1251') assert [('foo', 'bar'), ('foo', 'baz'), ('boo', '')] == result - async def test_read_form_guess_encoding(self): + async def test_read_form_guess_encoding(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {CONTENT_TYPE: 'application/x-www-form-urlencoded; charset=utf-8'}, @@ -444,16 +449,16 @@ result = await obj.form() assert [('foo', 'bar'), ('foo', 'baz'), ('boo', '')] == result - async def test_read_form_while_closed(self): + async def test_read_form_while_closed(self) -> None: stream = Stream(b'') obj = aiohttp.BodyPartReader( BOUNDARY, {CONTENT_TYPE: 'application/x-www-form-urlencoded'}, stream) obj._at_eof = True result = await obj.form() - assert result is None + assert not result - async def test_readline(self): + async def test_readline(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {}, Stream(b'Hello\n,\r\nworld!\r\n--:--')) result = await obj.readline() @@ -466,7 +471,7 @@ assert b'' == result assert obj.at_eof() - async def test_release(self): + async def test_release(self) -> None: stream = Stream(b'Hello,\r\n--:\r\n\r\nworld!\r\n--:--') obj = aiohttp.BodyPartReader( BOUNDARY, {}, stream) @@ -474,7 +479,7 @@ assert obj.at_eof() assert b'--:\r\n\r\nworld!\r\n--:--' == stream.content.read() - async def test_release_respects_content_length(self): + async def test_release_respects_content_length(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {'CONTENT-LENGTH': 100500}, Stream(b'.' * 100500 + b'\r\n--:--')) @@ -482,7 +487,7 @@ assert result is None assert obj.at_eof() - async def test_release_release(self): + async def test_release_release(self) -> None: stream = Stream(b'Hello,\r\n--:\r\n\r\nworld!\r\n--:--') obj = aiohttp.BodyPartReader( BOUNDARY, {}, stream) @@ -490,14 +495,14 @@ await obj.release() assert b'--:\r\n\r\nworld!\r\n--:--' == stream.content.read() - async def test_filename(self): + async def test_filename(self) -> None: part = aiohttp.BodyPartReader( BOUNDARY, {CONTENT_DISPOSITION: 'attachment; filename=foo.html'}, None) assert 'foo.html' == part.filename - async def test_reading_long_part(self): + async def test_reading_long_part(self) -> None: size = 2 * stream_reader_default_limit protocol = mock.Mock(_reading_paused=False) stream = StreamReader(protocol) @@ -511,7 +516,7 @@ class TestMultipartReader: - def test_from_response(self): + def test_from_response(self) -> None: resp = Response({CONTENT_TYPE: 'multipart/related;boundary=":"'}, Stream(b'--:\r\n\r\nhello\r\n--:--')) res = aiohttp.MultipartReader.from_response(resp) @@ -520,28 +525,28 @@ assert isinstance(res.stream, aiohttp.MultipartReader) - def test_bad_boundary(self): + def test_bad_boundary(self) -> None: resp = Response( {CONTENT_TYPE: 'multipart/related;boundary=' + 'a' * 80}, Stream(b'')) with pytest.raises(ValueError): aiohttp.MultipartReader.from_response(resp) - def test_dispatch(self): + def test_dispatch(self) -> None: reader = aiohttp.MultipartReader( {CONTENT_TYPE: 'multipart/related;boundary=":"'}, Stream(b'--:\r\n\r\necho\r\n--:--')) res = reader._get_part_reader({CONTENT_TYPE: 'text/plain'}) assert isinstance(res, reader.part_reader_cls) - def test_dispatch_bodypart(self): + def test_dispatch_bodypart(self) -> None: reader = aiohttp.MultipartReader( {CONTENT_TYPE: 'multipart/related;boundary=":"'}, Stream(b'--:\r\n\r\necho\r\n--:--')) res = reader._get_part_reader({CONTENT_TYPE: 'text/plain'}) assert isinstance(res, reader.part_reader_cls) - def test_dispatch_multipart(self): + def test_dispatch_multipart(self) -> None: reader = aiohttp.MultipartReader( {CONTENT_TYPE: 'multipart/related;boundary=":"'}, Stream(b'----:--\r\n' @@ -556,7 +561,7 @@ {CONTENT_TYPE: 'multipart/related;boundary=--:--'}) assert isinstance(res, reader.__class__) - def test_dispatch_custom_multipart_reader(self): + def test_dispatch_custom_multipart_reader(self) -> None: class CustomReader(aiohttp.MultipartReader): pass reader = aiohttp.MultipartReader( @@ -574,21 +579,21 @@ {CONTENT_TYPE: 'multipart/related;boundary=--:--'}) assert isinstance(res, CustomReader) - async def test_emit_next(self): + async def test_emit_next(self) -> None: reader = aiohttp.MultipartReader( {CONTENT_TYPE: 'multipart/related;boundary=":"'}, Stream(b'--:\r\n\r\necho\r\n--:--')) res = await reader.next() assert isinstance(res, reader.part_reader_cls) - async def test_invalid_boundary(self): + async def test_invalid_boundary(self) -> None: reader = aiohttp.MultipartReader( {CONTENT_TYPE: 'multipart/related;boundary=":"'}, Stream(b'---:\r\n\r\necho\r\n---:--')) with pytest.raises(ValueError): await reader.next() - async def test_release(self): + async def test_release(self) -> None: reader = aiohttp.MultipartReader( {CONTENT_TYPE: 'multipart/mixed;boundary=":"'}, Stream(b'--:\r\n' @@ -606,7 +611,7 @@ await reader.release() assert reader.at_eof() - async def test_release_release(self): + async def test_release_release(self) -> None: reader = aiohttp.MultipartReader( {CONTENT_TYPE: 'multipart/related;boundary=":"'}, Stream(b'--:\r\n\r\necho\r\n--:--')) @@ -615,7 +620,7 @@ await reader.release() assert reader.at_eof() - async def test_release_next(self): + async def test_release_next(self) -> None: reader = aiohttp.MultipartReader( {CONTENT_TYPE: 'multipart/related;boundary=":"'}, Stream(b'--:\r\n\r\necho\r\n--:--')) @@ -624,7 +629,7 @@ res = await reader.next() assert res is None - async def test_second_next_releases_previous_object(self): + async def test_second_next_releases_previous_object(self) -> None: reader = aiohttp.MultipartReader( {CONTENT_TYPE: 'multipart/related;boundary=":"'}, Stream(b'--:\r\n' @@ -640,7 +645,7 @@ assert first.at_eof() assert not second.at_eof() - async def test_release_without_read_the_last_object(self): + async def test_release_without_read_the_last_object(self) -> None: reader = aiohttp.MultipartReader( {CONTENT_TYPE: 'multipart/related;boundary=":"'}, Stream(b'--:\r\n' @@ -658,7 +663,7 @@ assert second.at_eof() assert third is None - async def test_read_chunk_by_length_doesnt_breaks_reader(self): + async def test_read_chunk_by_length_doesnt_breaks_reader(self) -> None: reader = aiohttp.MultipartReader( {CONTENT_TYPE: 'multipart/related;boundary=":"'}, Stream(b'--:\r\n' @@ -679,7 +684,7 @@ body_parts.append(read_part) assert body_parts == [b'test', b'passed'] - async def test_read_chunk_from_stream_doesnt_breaks_reader(self): + async def test_read_chunk_from_stream_doesnt_breaks_reader(self) -> None: reader = aiohttp.MultipartReader( {CONTENT_TYPE: 'multipart/related;boundary=":"'}, Stream(b'--:\r\n' @@ -702,7 +707,7 @@ body_parts.append(read_part) assert body_parts == [b'chunk', b'two_chunks'] - async def test_reading_skips_prelude(self): + async def test_reading_skips_prelude(self) -> None: reader = aiohttp.MultipartReader( {CONTENT_TYPE: 'multipart/related;boundary=":"'}, Stream(b'Multi-part data is not supported.\r\n' @@ -721,12 +726,12 @@ assert not second.at_eof() -async def test_writer(writer): +async def test_writer(writer) -> None: assert writer.size == 0 assert writer.boundary == ':' -async def test_writer_serialize_io_chunk(buf, stream, writer): +async def test_writer_serialize_io_chunk(buf, stream, writer) -> None: flo = io.BytesIO(b'foobarbaz') writer.append(flo) await writer.write(stream) @@ -734,14 +739,14 @@ b'\r\nContent-Length: 9\r\n\r\nfoobarbaz\r\n--:--\r\n') -async def test_writer_serialize_json(buf, stream, writer): +async def test_writer_serialize_json(buf, stream, writer) -> None: writer.append_json({'привет': 'мир'}) await writer.write(stream) assert (b'{"\\u043f\\u0440\\u0438\\u0432\\u0435\\u0442":' b' "\\u043c\\u0438\\u0440"}' in buf) -async def test_writer_serialize_form(buf, stream, writer): +async def test_writer_serialize_form(buf, stream, writer) -> None: data = [('foo', 'bar'), ('foo', 'baz'), ('boo', 'zoo')] writer.append_form(data) await writer.write(stream) @@ -749,7 +754,7 @@ assert (b'foo=bar&foo=baz&boo=zoo' in buf) -async def test_writer_serialize_form_dict(buf, stream, writer): +async def test_writer_serialize_form_dict(buf, stream, writer) -> None: data = {'hello': 'мир'} writer.append_form(data) await writer.write(stream) @@ -757,7 +762,7 @@ assert (b'hello=%D0%BC%D0%B8%D1%80' in buf) -async def test_writer_write(buf, stream, writer): +async def test_writer_write(buf, stream, writer) -> None: writer.append('foo-bar-baz') writer.append_json({'test': 'passed'}) writer.append_form({'test': 'passed'}) @@ -806,6 +811,40 @@ b'--:--\r\n') == bytes(buf)) +async def test_writer_write_no_close_boundary(buf, stream) -> None: + writer = aiohttp.MultipartWriter(boundary=':') + writer.append('foo-bar-baz') + writer.append_json({'test': 'passed'}) + writer.append_form({'test': 'passed'}) + writer.append_form([('one', 1), ('two', 2)]) + await writer.write(stream, close_boundary=False) + + assert ( + (b'--:\r\n' + b'Content-Type: text/plain; charset=utf-8\r\n' + b'Content-Length: 11\r\n\r\n' + b'foo-bar-baz' + b'\r\n' + + b'--:\r\n' + b'Content-Type: application/json\r\n' + b'Content-Length: 18\r\n\r\n' + b'{"test": "passed"}' + b'\r\n' + + b'--:\r\n' + b'Content-Type: application/x-www-form-urlencoded\r\n' + b'Content-Length: 11\r\n\r\n' + b'test=passed' + b'\r\n' + + b'--:\r\n' + b'Content-Type: application/x-www-form-urlencoded\r\n' + b'Content-Length: 11\r\n\r\n' + b'one=1&two=2' + b'\r\n') == bytes(buf)) + + async def test_writer_serialize_with_content_encoding_gzip(buf, stream, writer): writer.append('Time to Relax!', {CONTENT_ENCODING: 'gzip'}) @@ -881,64 +920,64 @@ b' =D0=BC=D0=B8=D1=80!' == message.split(b'\r\n')[0]) -def test_writer_content_transfer_encoding_unknown(buf, stream, writer): +def test_writer_content_transfer_encoding_unknown(buf, stream, writer) -> None: with pytest.raises(RuntimeError): writer.append('Time to Relax!', {CONTENT_TRANSFER_ENCODING: 'unknown'}) class TestMultipartWriter: - def test_default_subtype(self, writer): + def test_default_subtype(self, writer) -> None: mimetype = parse_mimetype(writer.headers.get(CONTENT_TYPE)) assert 'multipart' == mimetype.type assert 'mixed' == mimetype.subtype - def test_unquoted_boundary(self): + def test_unquoted_boundary(self) -> None: writer = aiohttp.MultipartWriter(boundary='abc123') expected = {CONTENT_TYPE: 'multipart/mixed; boundary=abc123'} assert expected == writer.headers - def test_quoted_boundary(self): + def test_quoted_boundary(self) -> None: writer = aiohttp.MultipartWriter(boundary=R'\"') expected = {CONTENT_TYPE: R'multipart/mixed; boundary="\\\""'} assert expected == writer.headers - def test_bad_boundary(self): + def test_bad_boundary(self) -> None: with pytest.raises(ValueError): aiohttp.MultipartWriter(boundary='тест') with pytest.raises(ValueError): aiohttp.MultipartWriter(boundary='test\n') - def test_default_headers(self, writer): + def test_default_headers(self, writer) -> None: expected = {CONTENT_TYPE: 'multipart/mixed; boundary=":"'} assert expected == writer.headers - def test_iter_parts(self, writer): + def test_iter_parts(self, writer) -> None: writer.append('foo') writer.append('bar') writer.append('baz') assert 3 == len(list(writer)) - def test_append(self, writer): + def test_append(self, writer) -> None: assert 0 == len(writer) writer.append('hello, world!') assert 1 == len(writer) assert isinstance(writer._parts[0][0], payload.Payload) - def test_append_with_headers(self, writer): + def test_append_with_headers(self, writer) -> None: writer.append('hello, world!', {'x-foo': 'bar'}) assert 1 == len(writer) assert 'x-foo' in writer._parts[0][0].headers assert writer._parts[0][0].headers['x-foo'] == 'bar' - def test_append_json(self, writer): + def test_append_json(self, writer) -> None: writer.append_json({'foo': 'bar'}) assert 1 == len(writer) part = writer._parts[0][0] assert part.headers[CONTENT_TYPE] == 'application/json' - def test_append_part(self, writer): + def test_append_part(self, writer) -> None: part = payload.get_payload( 'test', headers={CONTENT_TYPE: 'text/plain'}) writer.append(part, {CONTENT_TYPE: 'test/passed'}) @@ -946,19 +985,19 @@ part = writer._parts[0][0] assert part.headers[CONTENT_TYPE] == 'test/passed' - def test_append_json_overrides_content_type(self, writer): + def test_append_json_overrides_content_type(self, writer) -> None: writer.append_json({'foo': 'bar'}, {CONTENT_TYPE: 'test/passed'}) assert 1 == len(writer) part = writer._parts[0][0] assert part.headers[CONTENT_TYPE] == 'test/passed' - def test_append_form(self, writer): + def test_append_form(self, writer) -> None: writer.append_form({'foo': 'bar'}, {CONTENT_TYPE: 'test/passed'}) assert 1 == len(writer) part = writer._parts[0][0] assert part.headers[CONTENT_TYPE] == 'test/passed' - def test_append_multipart(self, writer): + def test_append_multipart(self, writer) -> None: subwriter = aiohttp.MultipartWriter(boundary=':') subwriter.append_json({'foo': 'bar'}) writer.append(subwriter, {CONTENT_TYPE: 'test/passed'}) @@ -966,33 +1005,33 @@ part = writer._parts[0][0] assert part.headers[CONTENT_TYPE] == 'test/passed' - async def test_write(self, writer, stream): + async def test_write(self, writer, stream) -> None: await writer.write(stream) - def test_with(self): + def test_with(self) -> None: with aiohttp.MultipartWriter(boundary=':') as writer: writer.append('foo') writer.append(b'bar') writer.append_json({'baz': True}) assert 3 == len(writer) - def test_append_int_not_allowed(self): + def test_append_int_not_allowed(self) -> None: with pytest.raises(TypeError): with aiohttp.MultipartWriter(boundary=':') as writer: writer.append(1) - def test_append_float_not_allowed(self): + def test_append_float_not_allowed(self) -> None: with pytest.raises(TypeError): with aiohttp.MultipartWriter(boundary=':') as writer: writer.append(1.1) - def test_append_none_not_allowed(self): + def test_append_none_not_allowed(self) -> None: with pytest.raises(TypeError): with aiohttp.MultipartWriter(boundary=':') as writer: writer.append(None) -async def test_async_for_reader(loop): +async def test_async_for_reader() -> None: data = [ {"test": "passed"}, 42, @@ -1052,7 +1091,7 @@ await check(reader) -async def test_async_for_bodypart(loop): +async def test_async_for_bodypart() -> None: part = aiohttp.BodyPartReader( boundary=b'--:', headers={}, diff -Nru python-aiohttp-3.1.3/tests/test_payload.py python-aiohttp-3.5.1/tests/test_payload.py --- python-aiohttp-3.1.3/tests/test_payload.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_payload.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,9 +1,11 @@ +import asyncio from io import StringIO +from unittest import mock import pytest from async_generator import async_generator -from aiohttp import payload +from aiohttp import payload, streams @pytest.fixture @@ -20,7 +22,7 @@ pass -def test_register_type(registry): +def test_register_type(registry) -> None: class TestProvider: pass @@ -29,7 +31,7 @@ assert isinstance(p, Payload) -def test_register_unsupported_order(registry): +def test_register_unsupported_order(registry) -> None: class TestProvider: pass @@ -37,7 +39,7 @@ payload.register_payload(Payload, TestProvider, order=object()) -def test_payload_ctor(): +def test_payload_ctor() -> None: p = Payload('test', encoding='utf-8', filename='test.txt') assert p._value == 'test' assert p._encoding == 'utf-8' @@ -46,27 +48,27 @@ assert p.content_type == 'text/plain' -def test_payload_content_type(): +def test_payload_content_type() -> None: p = Payload('test', headers={'content-type': 'application/json'}) assert p.content_type == 'application/json' -def test_bytes_payload_default_content_type(): +def test_bytes_payload_default_content_type() -> None: p = payload.BytesPayload(b'data') assert p.content_type == 'application/octet-stream' -def test_bytes_payload_explicit_content_type(): +def test_bytes_payload_explicit_content_type() -> None: p = payload.BytesPayload(b'data', content_type='application/custom') assert p.content_type == 'application/custom' -def test_bytes_payload_bad_type(): +def test_bytes_payload_bad_type() -> None: with pytest.raises(TypeError): payload.BytesPayload(object()) -def test_string_payload(): +def test_string_payload() -> None: p = payload.StringPayload('test') assert p.encoding == 'utf-8' assert p.content_type == 'text/plain; charset=utf-8' @@ -81,7 +83,7 @@ assert p.content_type == 'text/plain; charset=koi8-r' -def test_string_io_payload(): +def test_string_io_payload() -> None: s = StringIO('ű' * 5000) p = payload.StringIOPayload(s) assert p.encoding == 'utf-8' @@ -89,7 +91,7 @@ assert p.size == 10000 -def test_async_iterable_payload_default_content_type(): +def test_async_iterable_payload_default_content_type() -> None: @async_generator async def gen(): pass @@ -98,7 +100,7 @@ assert p.content_type == 'application/octet-stream' -def test_async_iterable_payload_explicit_content_type(): +def test_async_iterable_payload_explicit_content_type() -> None: @async_generator async def gen(): pass @@ -107,7 +109,25 @@ assert p.content_type == 'application/custom' -def test_async_iterable_payload_not_async_iterable(): +def test_async_iterable_payload_not_async_iterable() -> None: with pytest.raises(TypeError): payload.AsyncIterablePayload(object()) + + +async def test_stream_reader_long_lines() -> None: + loop = asyncio.get_event_loop() + DATA = b'0' * 1024 ** 3 + + stream = streams.StreamReader(mock.Mock(), loop=loop) + stream.feed_data(DATA) + stream.feed_eof() + body = payload.get_payload(stream) + + writer = mock.Mock() + writer.write.return_value = loop.create_future() + writer.write.return_value.set_result(None) + await body.write(writer) + writer.write.assert_called_once_with(mock.ANY) + (chunk,), _ = writer.write.call_args + assert len(chunk) == len(DATA) diff -Nru python-aiohttp-3.1.3/tests/test_proxy_functional.py python-aiohttp-3.5.1/tests/test_proxy_functional.py --- python-aiohttp-3.1.3/tests/test_proxy_functional.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_proxy_functional.py 2018-12-24 20:58:54.000000000 +0000 @@ -75,7 +75,8 @@ return _request -async def test_proxy_http_absolute_path(proxy_test_server, get_request): +async def test_proxy_http_absolute_path(proxy_test_server, + get_request) -> None: url = 'http://aiohttp.io/path?query=yes' proxy = await proxy_test_server() @@ -87,7 +88,7 @@ assert proxy.request.path_qs == 'http://aiohttp.io/path?query=yes' -async def test_proxy_http_raw_path(proxy_test_server, get_request): +async def test_proxy_http_raw_path(proxy_test_server, get_request) -> None: url = 'http://aiohttp.io:2561/space sheep?q=can:fly' raw_url = 'http://aiohttp.io:2561/space%20sheep?q=can:fly' proxy = await proxy_test_server() @@ -98,7 +99,7 @@ assert proxy.request.path_qs == raw_url -async def test_proxy_http_idna_support(proxy_test_server, get_request): +async def test_proxy_http_idna_support(proxy_test_server, get_request) -> None: url = 'http://éé.com/' raw_url = 'http://xn--9caa.com/' proxy = await proxy_test_server() @@ -109,7 +110,7 @@ assert proxy.request.path_qs == raw_url -async def test_proxy_http_connection_error(get_request): +async def test_proxy_http_connection_error(get_request) -> None: url = 'http://aiohttp.io/path' proxy_url = 'http://localhost:2242/' @@ -117,7 +118,7 @@ await get_request(url=url, proxy=proxy_url) -async def test_proxy_http_bad_response(proxy_test_server, get_request): +async def test_proxy_http_bad_response(proxy_test_server, get_request) -> None: url = 'http://aiohttp.io/path' proxy = await proxy_test_server() proxy.return_value = dict( @@ -130,7 +131,7 @@ assert resp.headers['Proxy-Agent'] == 'TestProxy' -async def test_proxy_http_auth(proxy_test_server, get_request): +async def test_proxy_http_auth(proxy_test_server, get_request) -> None: url = 'http://aiohttp.io/path' proxy = await proxy_test_server() @@ -157,7 +158,7 @@ assert 'Proxy-Authorization' in proxy.request.headers -async def test_proxy_http_auth_utf8(proxy_test_server, get_request): +async def test_proxy_http_auth_utf8(proxy_test_server, get_request) -> None: url = 'http://aiohttp.io/path' auth = aiohttp.BasicAuth('юзер', 'пасс', 'utf-8') proxy = await proxy_test_server() @@ -168,7 +169,8 @@ assert 'Proxy-Authorization' not in proxy.request.headers -async def test_proxy_http_auth_from_url(proxy_test_server, get_request): +async def test_proxy_http_auth_from_url(proxy_test_server, + get_request) -> None: url = 'http://aiohttp.io/path' proxy = await proxy_test_server() @@ -185,7 +187,7 @@ assert 'Proxy-Authorization' in proxy.request.headers -async def test_proxy_http_acquired_cleanup(proxy_test_server, loop): +async def test_proxy_http_acquired_cleanup(proxy_test_server, loop) -> None: url = 'http://aiohttp.io/path' conn = aiohttp.TCPConnector(loop=loop) @@ -203,7 +205,8 @@ @pytest.mark.skip('we need to reconsider how we test this') -async def test_proxy_http_acquired_cleanup_force(proxy_test_server, loop): +async def test_proxy_http_acquired_cleanup_force(proxy_test_server, + loop) -> None: url = 'http://aiohttp.io/path' conn = aiohttp.TCPConnector(force_close=True, loop=loop) @@ -227,7 +230,7 @@ @pytest.mark.skip('we need to reconsider how we test this') -async def test_proxy_http_multi_conn_limit(proxy_test_server, loop): +async def test_proxy_http_multi_conn_limit(proxy_test_server, loop) -> None: url = 'http://aiohttp.io/path' limit, multi_conn_num = 1, 5 @@ -319,7 +322,7 @@ assert connect.host == 'xn--9caa.com' -async def test_proxy_https_connection_error(get_request): +async def test_proxy_https_connection_error(get_request) -> None: url = 'https://secure.aiohttp.io/path' proxy_url = 'http://localhost:2242/' @@ -327,7 +330,8 @@ await get_request(url=url, proxy=proxy_url) -async def test_proxy_https_bad_response(proxy_test_server, get_request): +async def test_proxy_https_bad_response(proxy_test_server, + get_request) -> None: url = 'https://secure.aiohttp.io/path' proxy = await proxy_test_server() proxy.return_value = dict( @@ -490,7 +494,8 @@ return original_is_file(self) -async def test_proxy_from_env_http(proxy_test_server, get_request, mocker): +async def test_proxy_from_env_http(proxy_test_server, + get_request, mocker) -> None: url = 'http://aiohttp.io/path' proxy = await proxy_test_server() mocker.patch.dict(os.environ, {'http_proxy': str(proxy.url)}) @@ -634,7 +639,7 @@ assert r2.headers['Proxy-Authorization'] == auth.encode() -async def test_proxy_auth(): +async def test_proxy_auth() -> None: async with aiohttp.ClientSession() as session: with pytest.raises( ValueError, diff -Nru python-aiohttp-3.1.3/tests/test_proxy.py python-aiohttp-3.5.1/tests/test_proxy.py --- python-aiohttp-3.1.3/tests/test_proxy.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_proxy.py 2018-12-24 20:58:54.000000000 +0000 @@ -35,16 +35,19 @@ gc.collect() @mock.patch('aiohttp.connector.ClientRequest') - def test_connect(self, ClientRequestMock): + def test_connect(self, ClientRequestMock) -> None: req = ClientRequest( 'GET', URL('http://www.python.org'), proxy=URL('http://proxy.example.com'), - loop=self.loop + loop=self.loop, ) self.assertEqual(str(req.proxy), 'http://proxy.example.com') # mock all the things! - connector = aiohttp.TCPConnector(loop=self.loop) + async def make_conn(): + return aiohttp.TCPConnector() + + connector = self.loop.run_until_complete(make_conn()) connector._resolve_host = make_mocked_coro([mock.MagicMock()]) proto = mock.Mock(**{ @@ -52,7 +55,8 @@ }) self.loop.create_connection = make_mocked_coro( (proto.transport, proto)) - conn = self.loop.run_until_complete(connector.connect(req)) + conn = self.loop.run_until_complete( + connector.connect(req, None, aiohttp.ClientTimeout())) self.assertEqual(req.url, URL('http://www.python.org')) self.assertIs(conn._protocol, proto) self.assertIs(conn.transport, proto.transport) @@ -65,7 +69,7 @@ ssl=None) @mock.patch('aiohttp.connector.ClientRequest') - def test_proxy_headers(self, ClientRequestMock): + def test_proxy_headers(self, ClientRequestMock) -> None: req = ClientRequest( 'GET', URL('http://www.python.org'), proxy=URL('http://proxy.example.com'), @@ -74,7 +78,9 @@ self.assertEqual(str(req.proxy), 'http://proxy.example.com') # mock all the things! - connector = aiohttp.TCPConnector(loop=self.loop) + async def make_conn(): + return aiohttp.TCPConnector() + connector = self.loop.run_until_complete(make_conn()) connector._resolve_host = make_mocked_coro([mock.MagicMock()]) proto = mock.Mock(**{ @@ -82,7 +88,8 @@ }) self.loop.create_connection = make_mocked_coro( (proto.transport, proto)) - conn = self.loop.run_until_complete(connector.connect(req)) + conn = self.loop.run_until_complete(connector.connect( + req, None, aiohttp.ClientTimeout())) self.assertEqual(req.url, URL('http://www.python.org')) self.assertIs(conn._protocol, proto) self.assertIs(conn.transport, proto.transport) @@ -94,7 +101,7 @@ loop=self.loop, ssl=None) - def test_proxy_auth(self): + def test_proxy_auth(self) -> None: with self.assertRaises(ValueError) as ctx: ClientRequest( 'GET', URL('http://python.org'), @@ -106,8 +113,10 @@ "proxy_auth must be None or BasicAuth() tuple", ) - def test_proxy_dns_error(self): - connector = aiohttp.TCPConnector(loop=self.loop) + def test_proxy_dns_error(self) -> None: + async def make_conn(): + return aiohttp.TCPConnector() + connector = self.loop.run_until_complete(make_conn()) connector._resolve_host = make_mocked_coro( raise_exception=OSError('dont take it serious')) @@ -118,12 +127,15 @@ ) expected_headers = dict(req.headers) with self.assertRaises(aiohttp.ClientConnectorError): - self.loop.run_until_complete(connector.connect(req)) + self.loop.run_until_complete(connector.connect( + req, None, aiohttp.ClientTimeout())) self.assertEqual(req.url.path, '/') self.assertEqual(dict(req.headers), expected_headers) - def test_proxy_connection_error(self): - connector = aiohttp.TCPConnector(loop=self.loop) + def test_proxy_connection_error(self) -> None: + async def make_conn(): + return aiohttp.TCPConnector() + connector = self.loop.run_until_complete(make_conn()) connector._resolve_host = make_mocked_coro([{ 'hostname': 'www.python.org', 'host': '127.0.0.1', 'port': 80, @@ -138,10 +150,11 @@ loop=self.loop, ) with self.assertRaises(aiohttp.ClientProxyConnectionError): - self.loop.run_until_complete(connector.connect(req)) + self.loop.run_until_complete(connector.connect( + req, None, aiohttp.ClientTimeout())) @mock.patch('aiohttp.connector.ClientRequest') - def test_https_connect(self, ClientRequestMock): + def test_https_connect(self, ClientRequestMock) -> None: proxy_req = ClientRequest('GET', URL('http://proxy.example.com'), loop=self.loop) ClientRequestMock.return_value = proxy_req @@ -151,14 +164,15 @@ writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=self.loop, session=mock.Mock()) proxy_req.send = make_mocked_coro(proxy_resp) proxy_resp.start = make_mocked_coro(mock.Mock(status=200)) - connector = aiohttp.TCPConnector(loop=self.loop) + async def make_conn(): + return aiohttp.TCPConnector() + connector = self.loop.run_until_complete(make_conn()) connector._resolve_host = make_mocked_coro( [{'hostname': 'hostname', 'host': '127.0.0.1', 'port': 80, 'family': socket.AF_INET, 'proto': 0, 'flags': 0}]) @@ -171,7 +185,8 @@ proxy=URL('http://proxy.example.com'), loop=self.loop, ) - self.loop.run_until_complete(connector._create_connection(req)) + self.loop.run_until_complete( + connector._create_connection(req, None, aiohttp.ClientTimeout())) self.assertEqual(req.url.path, '/') self.assertEqual(proxy_req.method, 'CONNECT') @@ -184,7 +199,7 @@ self.loop.run_until_complete(req.close()) @mock.patch('aiohttp.connector.ClientRequest') - def test_https_connect_certificate_error(self, ClientRequestMock): + def test_https_connect_certificate_error(self, ClientRequestMock) -> None: proxy_req = ClientRequest('GET', URL('http://proxy.example.com'), loop=self.loop) ClientRequestMock.return_value = proxy_req @@ -194,14 +209,15 @@ writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=self.loop, session=mock.Mock()) proxy_req.send = make_mocked_coro(proxy_resp) proxy_resp.start = make_mocked_coro(mock.Mock(status=200)) - connector = aiohttp.TCPConnector(loop=self.loop) + async def make_conn(): + return aiohttp.TCPConnector() + connector = self.loop.run_until_complete(make_conn()) connector._resolve_host = make_mocked_coro( [{'hostname': 'hostname', 'host': '127.0.0.1', 'port': 80, 'family': socket.AF_INET, 'proto': 0, 'flags': 0}]) @@ -230,10 +246,11 @@ loop=self.loop, ) with self.assertRaises(aiohttp.ClientConnectorCertificateError): - self.loop.run_until_complete(connector._create_connection(req)) + self.loop.run_until_complete(connector._create_connection( + req, None, aiohttp.ClientTimeout())) @mock.patch('aiohttp.connector.ClientRequest') - def test_https_connect_ssl_error(self, ClientRequestMock): + def test_https_connect_ssl_error(self, ClientRequestMock) -> None: proxy_req = ClientRequest('GET', URL('http://proxy.example.com'), loop=self.loop) ClientRequestMock.return_value = proxy_req @@ -243,14 +260,15 @@ writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=self.loop, session=mock.Mock()) proxy_req.send = make_mocked_coro(proxy_resp) proxy_resp.start = make_mocked_coro(mock.Mock(status=200)) - connector = aiohttp.TCPConnector(loop=self.loop) + async def make_conn(): + return aiohttp.TCPConnector() + connector = self.loop.run_until_complete(make_conn()) connector._resolve_host = make_mocked_coro( [{'hostname': 'hostname', 'host': '127.0.0.1', 'port': 80, 'family': socket.AF_INET, 'proto': 0, 'flags': 0}]) @@ -279,10 +297,11 @@ loop=self.loop, ) with self.assertRaises(aiohttp.ClientConnectorSSLError): - self.loop.run_until_complete(connector._create_connection(req)) + self.loop.run_until_complete(connector._create_connection( + req, None, aiohttp.ClientTimeout())) @mock.patch('aiohttp.connector.ClientRequest') - def test_https_connect_runtime_error(self, ClientRequestMock): + def test_https_connect_runtime_error(self, ClientRequestMock) -> None: proxy_req = ClientRequest('GET', URL('http://proxy.example.com'), loop=self.loop) ClientRequestMock.return_value = proxy_req @@ -292,14 +311,15 @@ writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=self.loop, session=mock.Mock()) proxy_req.send = make_mocked_coro(proxy_resp) proxy_resp.start = make_mocked_coro(mock.Mock(status=200)) - connector = aiohttp.TCPConnector(loop=self.loop) + async def make_conn(): + return aiohttp.TCPConnector() + connector = self.loop.run_until_complete(make_conn()) connector._resolve_host = make_mocked_coro( [{'hostname': 'hostname', 'host': '127.0.0.1', 'port': 80, 'family': socket.AF_INET, 'proto': 0, 'flags': 0}]) @@ -315,14 +335,15 @@ ) with self.assertRaisesRegex( RuntimeError, "Transport does not expose socket instance"): - self.loop.run_until_complete(connector._create_connection(req)) + self.loop.run_until_complete(connector._create_connection( + req, None, aiohttp.ClientTimeout())) self.loop.run_until_complete(proxy_req.close()) proxy_resp.close() self.loop.run_until_complete(req.close()) @mock.patch('aiohttp.connector.ClientRequest') - def test_https_connect_http_proxy_error(self, ClientRequestMock): + def test_https_connect_http_proxy_error(self, ClientRequestMock) -> None: proxy_req = ClientRequest('GET', URL('http://proxy.example.com'), loop=self.loop) ClientRequestMock.return_value = proxy_req @@ -332,7 +353,6 @@ writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=self.loop, session=mock.Mock()) @@ -340,7 +360,9 @@ proxy_resp.start = make_mocked_coro( mock.Mock(status=400, reason='bad request')) - connector = aiohttp.TCPConnector(loop=self.loop) + async def make_conn(): + return aiohttp.TCPConnector() + connector = self.loop.run_until_complete(make_conn()) connector._resolve_host = make_mocked_coro( [{'hostname': 'hostname', 'host': '127.0.0.1', 'port': 80, 'family': socket.AF_INET, 'proto': 0, 'flags': 0}]) @@ -356,14 +378,15 @@ ) with self.assertRaisesRegex( aiohttp.ClientHttpProxyError, "400, message='bad request'"): - self.loop.run_until_complete(connector._create_connection(req)) + self.loop.run_until_complete(connector._create_connection( + req, None, aiohttp.ClientTimeout())) self.loop.run_until_complete(proxy_req.close()) proxy_resp.close() self.loop.run_until_complete(req.close()) @mock.patch('aiohttp.connector.ClientRequest') - def test_https_connect_resp_start_error(self, ClientRequestMock): + def test_https_connect_resp_start_error(self, ClientRequestMock) -> None: proxy_req = ClientRequest('GET', URL('http://proxy.example.com'), loop=self.loop) ClientRequestMock.return_value = proxy_req @@ -373,7 +396,6 @@ writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=self.loop, session=mock.Mock()) @@ -381,7 +403,9 @@ proxy_resp.start = make_mocked_coro( raise_exception=OSError("error message")) - connector = aiohttp.TCPConnector(loop=self.loop) + async def make_conn(): + return aiohttp.TCPConnector() + connector = self.loop.run_until_complete(make_conn()) connector._resolve_host = make_mocked_coro( [{'hostname': 'hostname', 'host': '127.0.0.1', 'port': 80, 'family': socket.AF_INET, 'proto': 0, 'flags': 0}]) @@ -396,15 +420,18 @@ loop=self.loop, ) with self.assertRaisesRegex(OSError, "error message"): - self.loop.run_until_complete(connector._create_connection(req)) + self.loop.run_until_complete(connector._create_connection( + req, None, aiohttp.ClientTimeout())) @mock.patch('aiohttp.connector.ClientRequest') - def test_request_port(self, ClientRequestMock): + def test_request_port(self, ClientRequestMock) -> None: proxy_req = ClientRequest('GET', URL('http://proxy.example.com'), loop=self.loop) ClientRequestMock.return_value = proxy_req - connector = aiohttp.TCPConnector(loop=self.loop) + async def make_conn(): + return aiohttp.TCPConnector() + connector = self.loop.run_until_complete(make_conn()) connector._resolve_host = make_mocked_coro( [{'hostname': 'hostname', 'host': '127.0.0.1', 'port': 80, 'family': socket.AF_INET, 'proto': 0, 'flags': 0}]) @@ -418,10 +445,11 @@ proxy=URL('http://proxy.example.com'), loop=self.loop, ) - self.loop.run_until_complete(connector._create_connection(req)) + self.loop.run_until_complete(connector._create_connection( + req, None, aiohttp.ClientTimeout())) self.assertEqual(req.url, URL('http://localhost:1234/path')) - def test_proxy_auth_property(self): + def test_proxy_auth_property(self) -> None: req = aiohttp.ClientRequest( 'GET', URL('http://localhost:1234/path'), proxy=URL('http://proxy.example.com'), @@ -429,7 +457,7 @@ loop=self.loop) self.assertEqual(('user', 'pass', 'latin1'), req.proxy_auth) - def test_proxy_auth_property_default(self): + def test_proxy_auth_property_default(self) -> None: req = aiohttp.ClientRequest( 'GET', URL('http://localhost:1234/path'), proxy=URL('http://proxy.example.com'), @@ -437,7 +465,7 @@ self.assertIsNone(req.proxy_auth) @mock.patch('aiohttp.connector.ClientRequest') - def test_https_connect_pass_ssl_context(self, ClientRequestMock): + def test_https_connect_pass_ssl_context(self, ClientRequestMock) -> None: proxy_req = ClientRequest('GET', URL('http://proxy.example.com'), loop=self.loop) ClientRequestMock.return_value = proxy_req @@ -447,14 +475,15 @@ writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=self.loop, session=mock.Mock()) proxy_req.send = make_mocked_coro(proxy_resp) proxy_resp.start = make_mocked_coro(mock.Mock(status=200)) - connector = aiohttp.TCPConnector(loop=self.loop) + async def make_conn(): + return aiohttp.TCPConnector() + connector = self.loop.run_until_complete(make_conn()) connector._resolve_host = make_mocked_coro( [{'hostname': 'hostname', 'host': '127.0.0.1', 'port': 80, 'family': socket.AF_INET, 'proto': 0, 'flags': 0}]) @@ -467,7 +496,8 @@ proxy=URL('http://proxy.example.com'), loop=self.loop, ) - self.loop.run_until_complete(connector._create_connection(req)) + self.loop.run_until_complete(connector._create_connection( + req, None, aiohttp.ClientTimeout())) self.loop.create_connection.assert_called_with( mock.ANY, @@ -486,7 +516,7 @@ self.loop.run_until_complete(req.close()) @mock.patch('aiohttp.connector.ClientRequest') - def test_https_auth(self, ClientRequestMock): + def test_https_auth(self, ClientRequestMock) -> None: proxy_req = ClientRequest('GET', URL('http://proxy.example.com'), auth=aiohttp.helpers.BasicAuth('user', 'pass'), @@ -498,14 +528,15 @@ writer=mock.Mock(), continue100=None, timer=TimerNoop(), - auto_decompress=True, traces=[], loop=self.loop, session=mock.Mock()) proxy_req.send = make_mocked_coro(proxy_resp) proxy_resp.start = make_mocked_coro(mock.Mock(status=200)) - connector = aiohttp.TCPConnector(loop=self.loop) + async def make_conn(): + return aiohttp.TCPConnector() + connector = self.loop.run_until_complete(make_conn()) connector._resolve_host = make_mocked_coro( [{'hostname': 'hostname', 'host': '127.0.0.1', 'port': 80, 'family': socket.AF_INET, 'proto': 0, 'flags': 0}]) @@ -523,7 +554,8 @@ ) self.assertNotIn('AUTHORIZATION', req.headers) self.assertNotIn('PROXY-AUTHORIZATION', req.headers) - self.loop.run_until_complete(connector._create_connection(req)) + self.loop.run_until_complete( + connector._create_connection(req, None, aiohttp.ClientTimeout())) self.assertEqual(req.url.path, '/') self.assertNotIn('AUTHORIZATION', req.headers) @@ -534,7 +566,7 @@ connector._resolve_host.assert_called_with( 'proxy.example.com', 80, - traces=None) + traces=mock.ANY) self.loop.run_until_complete(proxy_req.close()) proxy_resp.close() diff -Nru python-aiohttp-3.1.3/tests/test_pytest_plugin.py python-aiohttp-3.5.1/tests/test_pytest_plugin.py --- python-aiohttp-3.1.3/tests/test_pytest_plugin.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_pytest_plugin.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,3 +1,5 @@ +import os +import platform import sys import pytest @@ -10,7 +12,10 @@ ''' -def test_aiohttp_plugin(testdir): +IS_PYPY = platform.python_implementation() == 'PyPy' + + +def test_aiohttp_plugin(testdir) -> None: testdir.makepyfile("""\ import pytest from unittest import mock @@ -28,7 +33,7 @@ return app -async def test_hello(aiohttp_client): +async def test_hello(aiohttp_client) -> None: client = await aiohttp_client(create_app) resp = await client.get('/') assert resp.status == 200 @@ -36,7 +41,7 @@ assert 'Hello, world' in text -async def test_hello_from_app(aiohttp_client, loop): +async def test_hello_from_app(aiohttp_client, loop) -> None: app = web.Application() app.router.add_get('/', hello) client = await aiohttp_client(app) @@ -46,7 +51,7 @@ assert 'Hello, world' in text -async def test_hello_with_loop(aiohttp_client, loop): +async def test_hello_with_loop(aiohttp_client, loop) -> None: client = await aiohttp_client(create_app) resp = await client.get('/') assert resp.status == 200 @@ -54,19 +59,19 @@ assert 'Hello, world' in text -async def test_set_args(aiohttp_client, loop): +async def test_set_args(aiohttp_client, loop) -> None: with pytest.raises(AssertionError): app = web.Application() await aiohttp_client(app, 1, 2, 3) -async def test_set_keyword_args(aiohttp_client, loop): +async def test_set_keyword_args(aiohttp_client, loop) -> None: app = web.Application() with pytest.raises(TypeError): await aiohttp_client(app, param=1) -async def test_noop(): +async def test_noop() -> None: pass @@ -91,7 +96,7 @@ return loop.run_until_complete(aiohttp_client(create_stateful_app)) -async def test_set_value(cli): +async def test_set_value(cli) -> None: resp = await cli.post('/', data={'value': 'foo'}) assert resp.status == 200 text = await resp.text() @@ -99,7 +104,7 @@ assert cli.server.app['value'] == 'foo' -async def test_get_value(cli): +async def test_get_value(cli) -> None: resp = await cli.get('/') assert resp.status == 200 text = await resp.text() @@ -112,11 +117,11 @@ assert text == 'value: bar' -def test_noncoro(): +def test_noncoro() -> None: assert True -async def test_failed_to_create_client(aiohttp_client): +async def test_failed_to_create_client(aiohttp_client) -> None: def make_app(loop): raise RuntimeError() @@ -147,26 +152,32 @@ result.assert_outcomes(passed=12) -def test_warning_checks(testdir): +def test_warning_checks(testdir) -> None: testdir.makepyfile("""\ async def foobar(): return 123 -async def test_good(): +async def test_good() -> None: v = await foobar() assert v == 123 -async def test_bad(): +async def test_bad() -> None: foobar() """) testdir.makeconftest(CONFTEST) result = testdir.runpytest('-p', 'no:sugar', '-s', '-W', 'default', '--aiohttp-loop=pyloop') - result.assert_outcomes(passed=1, failed=1) + expected_outcomes = ( + {'failed': 0, 'passed': 2} + if IS_PYPY and bool(os.environ.get('PYTHONASYNCIODEBUG')) + else {'failed': 1, 'passed': 1} + ) + """Under PyPy "coroutine 'foobar' was never awaited" does not happen.""" + result.assert_outcomes(**expected_outcomes) -def test_aiohttp_plugin_async_fixture(testdir, capsys): +def test_aiohttp_plugin_async_fixture(testdir, capsys) -> None: testdir.makepyfile("""\ import pytest @@ -200,21 +211,21 @@ return request.function -async def test_hello(cli): +async def test_hello(cli) -> None: resp = await cli.get('/') assert resp.status == 200 -def test_foo(loop, foo): +def test_foo(loop, foo) -> None: assert foo == 42 -def test_foo_without_loop(foo): +def test_foo_without_loop(foo) -> None: # will raise an error because there is no loop pass -def test_bar(loop, bar): +def test_bar(loop, bar) -> None: assert bar is test_bar """) testdir.makeconftest(CONFTEST) @@ -227,7 +238,7 @@ @pytest.mark.skipif(sys.version_info < (3, 6), reason='old python') -def test_aiohttp_plugin_async_gen_fixture(testdir): +def test_aiohttp_plugin_async_gen_fixture(testdir) -> None: testdir.makepyfile("""\ import pytest from unittest import mock @@ -254,12 +265,12 @@ canary() -async def test_hello(cli): +async def test_hello(cli) -> None: resp = await cli.get('/') assert resp.status == 200 -def test_finalized(): +def test_finalized() -> None: assert canary.called is True """) testdir.makeconftest(CONFTEST) diff -Nru python-aiohttp-3.1.3/tests/test_resolver.py python-aiohttp-3.5.1/tests/test_resolver.py --- python-aiohttp-3.1.3/tests/test_resolver.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_resolver.py 2018-12-24 20:58:54.000000000 +0000 @@ -47,7 +47,7 @@ @pytest.mark.skipif(not gethostbyname, reason="aiodns 1.1 required") -async def test_async_resolver_positive_lookup(loop): +async def test_async_resolver_positive_lookup(loop) -> None: with patch('aiodns.DNSResolver') as mock: mock().gethostbyname.return_value = fake_result(['127.0.0.1']) resolver = AsyncResolver(loop=loop) @@ -58,7 +58,7 @@ @pytest.mark.skipif(aiodns is None, reason="aiodns required") -async def test_async_resolver_query_positive_lookup(loop): +async def test_async_resolver_query_positive_lookup(loop) -> None: with patch('aiodns.DNSResolver') as mock: del mock().gethostbyname mock().query.return_value = fake_query_result(['127.0.0.1']) @@ -69,7 +69,7 @@ @pytest.mark.skipif(not gethostbyname, reason="aiodns 1.1 required") -async def test_async_resolver_multiple_replies(loop): +async def test_async_resolver_multiple_replies(loop) -> None: with patch('aiodns.DNSResolver') as mock: ips = ['127.0.0.1', '127.0.0.2', '127.0.0.3', '127.0.0.4'] mock().gethostbyname.return_value = fake_result(ips) @@ -80,7 +80,7 @@ @pytest.mark.skipif(aiodns is None, reason="aiodns required") -async def test_async_resolver_query_multiple_replies(loop): +async def test_async_resolver_query_multiple_replies(loop) -> None: with patch('aiodns.DNSResolver') as mock: del mock().gethostbyname ips = ['127.0.0.1', '127.0.0.2', '127.0.0.3', '127.0.0.4'] @@ -91,7 +91,7 @@ @pytest.mark.skipif(not gethostbyname, reason="aiodns 1.1 required") -async def test_async_resolver_negative_lookup(loop): +async def test_async_resolver_negative_lookup(loop) -> None: with patch('aiodns.DNSResolver') as mock: mock().gethostbyname.side_effect = aiodns.error.DNSError() resolver = AsyncResolver(loop=loop) @@ -100,7 +100,7 @@ @pytest.mark.skipif(aiodns is None, reason="aiodns required") -async def test_async_resolver_query_negative_lookup(loop): +async def test_async_resolver_query_negative_lookup(loop) -> None: with patch('aiodns.DNSResolver') as mock: del mock().gethostbyname mock().query.side_effect = aiodns.error.DNSError() @@ -110,7 +110,7 @@ @pytest.mark.skipif(aiodns is None, reason="aiodns required") -async def test_async_resolver_no_hosts_in_query(loop): +async def test_async_resolver_no_hosts_in_query(loop) -> None: with patch('aiodns.DNSResolver') as mock: del mock().gethostbyname mock().query.return_value = fake_query_result([]) @@ -120,7 +120,7 @@ @pytest.mark.skipif(not gethostbyname, reason="aiodns 1.1 required") -async def test_async_resolver_no_hosts_in_gethostbyname(loop): +async def test_async_resolver_no_hosts_in_gethostbyname(loop) -> None: with patch('aiodns.DNSResolver') as mock: mock().gethostbyname.return_value = fake_result([]) resolver = AsyncResolver(loop=loop) @@ -128,7 +128,7 @@ await resolver.resolve('doesnotexist.bla') -async def test_threaded_resolver_positive_lookup(): +async def test_threaded_resolver_positive_lookup() -> None: loop = Mock() loop.getaddrinfo = fake_addrinfo(["127.0.0.1"]) resolver = ThreadedResolver(loop=loop) @@ -136,7 +136,7 @@ ipaddress.ip_address(real[0]['host']) -async def test_threaded_resolver_multiple_replies(): +async def test_threaded_resolver_multiple_replies() -> None: loop = Mock() ips = ['127.0.0.1', '127.0.0.2', '127.0.0.3', '127.0.0.4'] loop.getaddrinfo = fake_addrinfo(ips) @@ -146,7 +146,7 @@ assert len(ips) > 3, "Expecting multiple addresses" -async def test_threaded_negative_lookup(): +async def test_threaded_negative_lookup() -> None: loop = Mock() ips = [] loop.getaddrinfo = fake_addrinfo(ips) @@ -155,32 +155,32 @@ await resolver.resolve('doesnotexist.bla') -async def test_close_for_threaded_resolver(loop): +async def test_close_for_threaded_resolver(loop) -> None: resolver = ThreadedResolver(loop=loop) await resolver.close() @pytest.mark.skipif(aiodns is None, reason="aiodns required") -async def test_close_for_async_resolver(loop): +async def test_close_for_async_resolver(loop) -> None: resolver = AsyncResolver(loop=loop) await resolver.close() -def test_default_loop_for_threaded_resolver(loop): +async def test_default_loop_for_threaded_resolver(loop) -> None: asyncio.set_event_loop(loop) resolver = ThreadedResolver() assert resolver._loop is loop @pytest.mark.skipif(aiodns is None, reason="aiodns required") -def test_default_loop_for_async_resolver(loop): +async def test_default_loop_for_async_resolver(loop) -> None: asyncio.set_event_loop(loop) resolver = AsyncResolver() assert resolver._loop is loop @pytest.mark.skipif(not gethostbyname, reason="aiodns 1.1 required") -async def test_async_resolver_ipv6_positive_lookup(loop): +async def test_async_resolver_ipv6_positive_lookup(loop) -> None: with patch('aiodns.DNSResolver') as mock: mock().gethostbyname.return_value = fake_result(['::1']) resolver = AsyncResolver(loop=loop) @@ -192,7 +192,7 @@ @pytest.mark.skipif(aiodns is None, reason="aiodns required") -async def test_async_resolver_query_ipv6_positive_lookup(loop): +async def test_async_resolver_query_ipv6_positive_lookup(loop) -> None: with patch('aiodns.DNSResolver') as mock: del mock().gethostbyname mock().query.return_value = fake_query_result(['::1']) @@ -203,13 +203,13 @@ mock().query.assert_called_with('www.python.org', 'AAAA') -def test_async_resolver_aiodns_not_present(loop, monkeypatch): +async def test_async_resolver_aiodns_not_present(loop, monkeypatch) -> None: monkeypatch.setattr("aiohttp.resolver.aiodns", None) with pytest.raises(RuntimeError): AsyncResolver(loop=loop) -def test_default_resolver(): +def test_default_resolver() -> None: # if gethostbyname: # assert DefaultResolver is AsyncResolver # else: diff -Nru python-aiohttp-3.1.3/tests/test_route_def.py python-aiohttp-3.5.1/tests/test_route_def.py --- python-aiohttp-3.1.3/tests/test_route_def.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_route_def.py 2018-12-24 20:58:54.000000000 +0000 @@ -12,7 +12,7 @@ return UrlDispatcher() -def test_get(router): +def test_get(router) -> None: async def handler(request): pass @@ -29,7 +29,7 @@ assert route2.method == 'HEAD' -def test_head(router): +def test_head(router) -> None: async def handler(request): pass @@ -42,7 +42,20 @@ assert str(route.url_for()) == '/' -def test_post(router): +def test_options(router) -> None: + async def handler(request): + pass + + router.add_routes([web.options('/', handler)]) + assert len(router.routes()) == 1 + + route = list(router.routes())[0] + assert route.handler is handler + assert route.method == 'OPTIONS' + assert str(route.url_for()) == '/' + + +def test_post(router) -> None: async def handler(request): pass @@ -54,7 +67,7 @@ assert str(route.url_for()) == '/' -def test_put(router): +def test_put(router) -> None: async def handler(request): pass @@ -67,7 +80,7 @@ assert str(route.url_for()) == '/' -def test_patch(router): +def test_patch(router) -> None: async def handler(request): pass @@ -80,7 +93,7 @@ assert str(route.url_for()) == '/' -def test_delete(router): +def test_delete(router) -> None: async def handler(request): pass @@ -93,7 +106,7 @@ assert str(route.url_for()) == '/' -def test_route(router): +def test_route(router) -> None: async def handler(request): pass @@ -106,7 +119,7 @@ assert str(route.url_for()) == '/' -def test_static(router): +def test_static(router) -> None: folder = pathlib.Path(__file__).parent router.add_routes([web.static('/prefix', folder)]) assert len(router.resources()) == 1 # 2 routes: for HEAD and GET @@ -119,7 +132,7 @@ assert url == URL('/prefix/sample.key') -def test_head_deco(router): +def test_head_deco(router) -> None: routes = web.RouteTableDef() @routes.head('/path') @@ -135,7 +148,7 @@ assert str(route.url_for()) == '/path' -def test_get_deco(router): +def test_get_deco(router) -> None: routes = web.RouteTableDef() @routes.get('/path') @@ -155,7 +168,7 @@ assert str(route2.url_for()) == '/path' -def test_post_deco(router): +def test_post_deco(router) -> None: routes = web.RouteTableDef() @routes.post('/path') @@ -171,7 +184,7 @@ assert str(route.url_for()) == '/path' -def test_put_deco(router): +def test_put_deco(router) -> None: routes = web.RouteTableDef() @routes.put('/path') @@ -187,7 +200,7 @@ assert str(route.url_for()) == '/path' -def test_patch_deco(router): +def test_patch_deco(router) -> None: routes = web.RouteTableDef() @routes.patch('/path') @@ -203,7 +216,7 @@ assert str(route.url_for()) == '/path' -def test_delete_deco(router): +def test_delete_deco(router) -> None: routes = web.RouteTableDef() @routes.delete('/path') @@ -219,7 +232,7 @@ assert str(route.url_for()) == '/path' -def test_route_deco(router): +def test_route_deco(router) -> None: routes = web.RouteTableDef() @routes.route('OTHER', '/path') @@ -235,7 +248,7 @@ assert str(route.url_for()) == '/path' -def test_routedef_sequence_protocol(): +def test_routedef_sequence_protocol() -> None: routes = web.RouteTableDef() @routes.delete('/path') @@ -250,7 +263,7 @@ assert list(routes)[0] is info -def test_repr_route_def(): +def test_repr_route_def() -> None: routes = web.RouteTableDef() @routes.get('/path') @@ -261,7 +274,7 @@ assert repr(rd) == " 'handler'>" -def test_repr_route_def_with_extra_info(): +def test_repr_route_def_with_extra_info() -> None: routes = web.RouteTableDef() @routes.get('/path', extra='info') @@ -272,7 +285,7 @@ assert repr(rd) == " 'handler', extra='info'>" -def test_repr_static_def(): +def test_repr_static_def() -> None: routes = web.RouteTableDef() routes.static('/prefix', '/path', name='name') @@ -281,7 +294,7 @@ assert repr(rd) == " /path, name='name'>" -def test_repr_route_table_def(): +def test_repr_route_table_def() -> None: routes = web.RouteTableDef() @routes.get('/path') diff -Nru python-aiohttp-3.1.3/tests/test_run_app.py python-aiohttp-3.5.1/tests/test_run_app.py --- python-aiohttp-3.1.3/tests/test_run_app.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_run_app.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,5 +1,6 @@ import asyncio import contextlib +import logging import os import platform import signal @@ -13,6 +14,7 @@ import pytest from aiohttp import web +from aiohttp.helpers import PY_37 from aiohttp.test_utils import make_mocked_coro @@ -21,7 +23,7 @@ if _has_unix_domain_socks: _abstract_path_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) try: - _abstract_path_sock.bind(b"\x00" + uuid4().hex.encode('ascii')) + _abstract_path_sock.bind(b"\x00" + uuid4().hex.encode('ascii')) # type: ignore # noqa except FileNotFoundError: _abstract_path_failed = True else: @@ -86,7 +88,7 @@ return f -def test_run_app_http(patched_loop): +def test_run_app_http(patched_loop) -> None: app = web.Application() startup_handler = make_mocked_coro() app.on_startup.append(startup_handler) @@ -103,7 +105,7 @@ cleanup_handler.assert_called_once_with(app) -def test_run_app_close_loop(patched_loop): +def test_run_app_close_loop(patched_loop) -> None: app = web.Application() web.run_app(app, print=stopper(patched_loop)) @@ -137,7 +139,7 @@ ] mock_socket = mock.Mock(getsockname=lambda: ('mock-socket', 123)) mixed_bindings_tests = ( - ( + ( # type: ignore "Nothing Specified", {}, [mock.call(mock.ANY, '0.0.0.0', 8080, ssl=None, backlog=128, @@ -308,7 +310,7 @@ expected_server_calls) -def test_run_app_https(patched_loop): +def test_run_app_https(patched_loop) -> None: app = web.Application() ssl_context = ssl.create_default_context() @@ -319,7 +321,8 @@ reuse_address=None, reuse_port=None) -def test_run_app_nondefault_host_port(patched_loop, aiohttp_unused_port): +def test_run_app_nondefault_host_port(patched_loop, + aiohttp_unused_port) -> None: port = aiohttp_unused_port() host = '127.0.0.1' @@ -332,7 +335,7 @@ reuse_port=None) -def test_run_app_custom_backlog(patched_loop): +def test_run_app_custom_backlog(patched_loop) -> None: app = web.Application() web.run_app(app, backlog=10, print=stopper(patched_loop)) @@ -341,7 +344,7 @@ reuse_address=None, reuse_port=None) -def test_run_app_custom_backlog_unix(patched_loop): +def test_run_app_custom_backlog_unix(patched_loop) -> None: app = web.Application() web.run_app(app, path='/tmp/tmpsock.sock', backlog=10, print=stopper(patched_loop)) @@ -351,10 +354,10 @@ @skip_if_no_unix_socks -def test_run_app_http_unix_socket(patched_loop, shorttmpdir): +def test_run_app_http_unix_socket(patched_loop, shorttmpdir) -> None: app = web.Application() - sock_path = str(shorttmpdir.join('socket.sock')) + sock_path = str(shorttmpdir / 'socket.sock') printer = mock.Mock(wraps=stopper(patched_loop)) web.run_app(app, path=sock_path, print=printer) @@ -364,10 +367,10 @@ @skip_if_no_unix_socks -def test_run_app_https_unix_socket(patched_loop, shorttmpdir): +def test_run_app_https_unix_socket(patched_loop, shorttmpdir) -> None: app = web.Application() - sock_path = str(shorttmpdir.join('socket.sock')) + sock_path = str(shorttmpdir / 'socket.sock') ssl_context = ssl.create_default_context() printer = mock.Mock(wraps=stopper(patched_loop)) web.run_app(app, path=sock_path, ssl_context=ssl_context, print=printer) @@ -379,7 +382,7 @@ @skip_if_no_unix_socks @skip_if_no_abstract_paths -def test_run_app_abstract_linux_socket(patched_loop): +def test_run_app_abstract_linux_socket(patched_loop) -> None: sock_path = b"\x00" + uuid4().hex.encode('ascii') app = web.Application() web.run_app( @@ -394,7 +397,7 @@ ) -def test_run_app_preexisting_inet_socket(patched_loop, mocker): +def test_run_app_preexisting_inet_socket(patched_loop, mocker) -> None: app = web.Application() sock = socket.socket() @@ -412,7 +415,7 @@ @pytest.mark.skipif(not HAS_IPV6, reason="IPv6 is not available") -def test_run_app_preexisting_inet6_socket(patched_loop): +def test_run_app_preexisting_inet6_socket(patched_loop) -> None: app = web.Application() sock = socket.socket(socket.AF_INET6) @@ -430,7 +433,7 @@ @skip_if_no_unix_socks -def test_run_app_preexisting_unix_socket(patched_loop, mocker): +def test_run_app_preexisting_unix_socket(patched_loop, mocker) -> None: app = web.Application() sock_path = '/tmp/test_preexisting_sock1' @@ -448,7 +451,7 @@ assert "http://unix:{}:".format(sock_path) in printer.call_args[0][0] -def test_run_app_multiple_preexisting_sockets(patched_loop): +def test_run_app_multiple_preexisting_sockets(patched_loop) -> None: app = web.Application() sock1 = socket.socket() @@ -478,7 +481,7 @@ """ -def test_sigint(): +def test_sigint() -> None: skip_if_on_windows() proc = subprocess.Popen([sys.executable, "-u", "-c", _script_test_signal], @@ -490,7 +493,7 @@ assert proc.wait() == 0 -def test_sigterm(): +def test_sigterm() -> None: skip_if_on_windows() proc = subprocess.Popen([sys.executable, "-u", "-c", _script_test_signal], @@ -502,7 +505,7 @@ assert proc.wait() == 0 -def test_startup_cleanup_signals_even_on_failure(patched_loop): +def test_startup_cleanup_signals_even_on_failure(patched_loop) -> None: patched_loop.create_server = mock.Mock(side_effect=RuntimeError()) app = web.Application() @@ -518,7 +521,7 @@ cleanup_handler.assert_called_once_with(app) -def test_run_app_coro(patched_loop): +def test_run_app_coro(patched_loop) -> None: startup_handler = cleanup_handler = None async def make_app(): @@ -538,3 +541,184 @@ reuse_port=None) startup_handler.assert_called_once_with(mock.ANY) cleanup_handler.assert_called_once_with(mock.ANY) + + +def test_run_app_default_logger(monkeypatch, patched_loop): + patched_loop.set_debug(True) + logger = web.access_logger + attrs = { + 'hasHandlers.return_value': False, + 'level': logging.NOTSET, + 'name': 'aiohttp.access', + } + mock_logger = mock.create_autospec(logger, name='mock_access_logger') + mock_logger.configure_mock(**attrs) + + app = web.Application() + web.run_app(app, + print=stopper(patched_loop), + access_log=mock_logger) + mock_logger.setLevel.assert_any_call(logging.DEBUG) + mock_logger.hasHandlers.assert_called_with() + assert isinstance(mock_logger.addHandler.call_args[0][0], + logging.StreamHandler) + + +def test_run_app_default_logger_setup_requires_debug(patched_loop): + patched_loop.set_debug(False) + logger = web.access_logger + attrs = { + 'hasHandlers.return_value': False, + 'level': logging.NOTSET, + 'name': 'aiohttp.access', + } + mock_logger = mock.create_autospec(logger, name='mock_access_logger') + mock_logger.configure_mock(**attrs) + + app = web.Application() + web.run_app(app, + print=stopper(patched_loop), + access_log=mock_logger) + mock_logger.setLevel.assert_not_called() + mock_logger.hasHandlers.assert_not_called() + mock_logger.addHandler.assert_not_called() + + +def test_run_app_default_logger_setup_requires_default_logger(patched_loop): + patched_loop.set_debug(True) + logger = web.access_logger + attrs = { + 'hasHandlers.return_value': False, + 'level': logging.NOTSET, + 'name': None, + } + mock_logger = mock.create_autospec(logger, name='mock_access_logger') + mock_logger.configure_mock(**attrs) + + app = web.Application() + web.run_app(app, + print=stopper(patched_loop), + access_log=mock_logger) + mock_logger.setLevel.assert_not_called() + mock_logger.hasHandlers.assert_not_called() + mock_logger.addHandler.assert_not_called() + + +def test_run_app_default_logger_setup_only_if_unconfigured(patched_loop): + patched_loop.set_debug(True) + logger = web.access_logger + attrs = { + 'hasHandlers.return_value': True, + 'level': None, + 'name': 'aiohttp.access', + } + mock_logger = mock.create_autospec(logger, name='mock_access_logger') + mock_logger.configure_mock(**attrs) + + app = web.Application() + web.run_app(app, + print=stopper(patched_loop), + access_log=mock_logger) + mock_logger.setLevel.assert_not_called() + mock_logger.hasHandlers.assert_called_with() + mock_logger.addHandler.assert_not_called() + + +def test_run_app_cancels_all_pending_tasks(patched_loop): + app = web.Application() + task = None + + async def on_startup(app): + nonlocal task + loop = asyncio.get_event_loop() + task = loop.create_task(asyncio.sleep(1000)) + + app.on_startup.append(on_startup) + + web.run_app(app, print=stopper(patched_loop)) + assert task.cancelled() + + +def test_run_app_cancels_done_tasks(patched_loop): + app = web.Application() + task = None + + async def coro(): + return 123 + + async def on_startup(app): + nonlocal task + loop = asyncio.get_event_loop() + task = loop.create_task(coro()) + + app.on_startup.append(on_startup) + + web.run_app(app, print=stopper(patched_loop)) + assert task.done() + + +def test_run_app_cancels_failed_tasks(patched_loop): + app = web.Application() + task = None + + exc = RuntimeError("FAIL") + + async def fail(): + try: + await asyncio.sleep(1000) + except asyncio.CancelledError: + raise exc + + async def on_startup(app): + nonlocal task + loop = asyncio.get_event_loop() + task = loop.create_task(fail()) + await asyncio.sleep(0.01) + + app.on_startup.append(on_startup) + + exc_handler = mock.Mock() + patched_loop.set_exception_handler(exc_handler) + web.run_app(app, print=stopper(patched_loop)) + assert task.done() + + msg = { + 'message': 'unhandled exception during asyncio.run() shutdown', + 'exception': exc, + 'task': task, + } + exc_handler.assert_called_with(patched_loop, msg) + + +@pytest.mark.skipif(not PY_37, + reason="contextvars support is required") +def test_run_app_context_vars(patched_loop): + from contextvars import ContextVar + + count = 0 + VAR = ContextVar('VAR', default='default') + + async def on_startup(app): + nonlocal count + assert 'init' == VAR.get() + VAR.set('on_startup') + count += 1 + + async def on_cleanup(app): + nonlocal count + assert 'on_startup' == VAR.get() + count += 1 + + async def init(): + nonlocal count + assert 'default' == VAR.get() + VAR.set('init') + app = web.Application() + + app.on_startup.append(on_startup) + app.on_cleanup.append(on_cleanup) + count += 1 + return app + + web.run_app(init(), print=stopper(patched_loop)) + assert count == 3 diff -Nru python-aiohttp-3.1.3/tests/test_signals.py python-aiohttp-3.5.1/tests/test_signals.py --- python-aiohttp-3.1.3/tests/test_signals.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_signals.py 2018-12-24 20:58:54.000000000 +0000 @@ -18,7 +18,7 @@ return make_mocked_request(method, path, headers, app=app) -async def test_add_signal_handler_not_a_callable(app): +async def test_add_signal_handler_not_a_callable(app) -> None: callback = True app.on_response_prepare.append(callback) app.on_response_prepare.freeze() @@ -26,7 +26,7 @@ await app.on_response_prepare(None, None) -async def test_function_signal_dispatch(app): +async def test_function_signal_dispatch(app) -> None: signal = Signal(app) kwargs = {'foo': 1, 'bar': 2} @@ -42,7 +42,7 @@ callback_mock.assert_called_once_with(**kwargs) -async def test_function_signal_dispatch2(app): +async def test_function_signal_dispatch2(app) -> None: signal = Signal(app) args = {'a', 'b'} kwargs = {'foo': 1, 'bar': 2} @@ -59,7 +59,7 @@ callback_mock.assert_called_once_with(*args, **kwargs) -async def test_response_prepare(app): +async def test_response_prepare(app) -> None: callback = mock.Mock() async def cb(*args, **kwargs): @@ -75,7 +75,7 @@ callback.assert_called_once_with(request, response) -async def test_non_coroutine(app): +async def test_non_coroutine(app) -> None: signal = Signal(app) kwargs = {'foo': 1, 'bar': 2} @@ -88,7 +88,7 @@ await signal.send(**kwargs) -def test_setitem(app): +def test_setitem(app) -> None: signal = Signal(app) m1 = mock.Mock() signal.append(m1) @@ -98,7 +98,7 @@ assert signal[0] is m2 -def test_delitem(app): +def test_delitem(app) -> None: signal = Signal(app) m1 = mock.Mock() signal.append(m1) @@ -107,7 +107,7 @@ assert len(signal) == 0 -def test_cannot_append_to_frozen_signal(app): +def test_cannot_append_to_frozen_signal(app) -> None: signal = Signal(app) m1 = mock.Mock() m2 = mock.Mock() @@ -119,7 +119,7 @@ assert list(signal) == [m1] -def test_cannot_setitem_in_frozen_signal(app): +def test_cannot_setitem_in_frozen_signal(app) -> None: signal = Signal(app) m1 = mock.Mock() m2 = mock.Mock() @@ -131,7 +131,7 @@ assert list(signal) == [m1] -def test_cannot_delitem_in_frozen_signal(app): +def test_cannot_delitem_in_frozen_signal(app) -> None: signal = Signal(app) m1 = mock.Mock() signal.append(m1) @@ -142,7 +142,7 @@ assert list(signal) == [m1] -async def test_cannot_send_non_frozen_signal(app): +async def test_cannot_send_non_frozen_signal(app) -> None: signal = Signal(app) callback = make_mocked_coro() @@ -155,7 +155,7 @@ assert not callback.called -async def test_repr(app): +async def test_repr(app) -> None: signal = Signal(app) callback = make_mocked_coro() diff -Nru python-aiohttp-3.1.3/tests/test_streams.py python-aiohttp-3.5.1/tests/test_streams.py --- python-aiohttp-3.1.3/tests/test_streams.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_streams.py 2018-12-24 20:58:54.000000000 +0000 @@ -17,7 +17,8 @@ yield seq[i:i+n] -def create_stream(loop): +async def create_stream(): + loop = asyncio.get_event_loop() protocol = mock.Mock(_reading_paused=False) stream = streams.StreamReader(protocol, loop=loop) stream.feed_data(DATA) @@ -38,20 +39,21 @@ return streams.StreamReader(mock.Mock(_reading_paused=False), *args, **kwargs) - async def test_create_waiter(self, loop): + async def test_create_waiter(self) -> None: + loop = asyncio.get_event_loop() stream = self._make_one(loop=loop) stream._waiter = loop.create_future with pytest.raises(RuntimeError): await stream._wait('test') - def test_ctor_global_loop(self): + def test_ctor_global_loop(self) -> None: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) stream = streams.StreamReader(mock.Mock(_reading_paused=False)) assert stream._loop is loop - async def test_at_eof(self): + async def test_at_eof(self) -> None: stream = self._make_one() assert not stream.at_eof() @@ -66,7 +68,8 @@ await stream.readline() assert stream.at_eof() - async def test_wait_eof(self, loop): + async def test_wait_eof(self) -> None: + loop = asyncio.get_event_loop() stream = self._make_one() wait_task = loop.create_task(stream.wait_eof()) @@ -79,7 +82,8 @@ assert stream.is_eof() assert stream._eof_waiter is None - async def test_wait_eof_eof(self, loop): + async def test_wait_eof_eof(self) -> None: + loop = asyncio.get_event_loop() stream = self._make_one() stream.feed_eof() @@ -87,7 +91,7 @@ await wait_task assert stream.is_eof() - async def test_feed_empty_data(self): + async def test_feed_empty_data(self) -> None: stream = self._make_one() stream.feed_data(b'') stream.feed_eof() @@ -95,7 +99,7 @@ data = await stream.read() assert b'' == data - async def test_feed_nonempty_data(self): + async def test_feed_nonempty_data(self) -> None: stream = self._make_one() stream.feed_data(self.DATA) stream.feed_eof() @@ -103,7 +107,7 @@ data = await stream.read() assert self.DATA == data - async def test_read_zero(self): + async def test_read_zero(self) -> None: # Read zero bytes. stream = self._make_one() stream.feed_data(self.DATA) @@ -115,7 +119,8 @@ data = await stream.read() assert self.DATA == data - async def test_read(self, loop): + async def test_read(self) -> None: + loop = asyncio.get_event_loop() # Read bytes. stream = self._make_one() read_task = loop.create_task(stream.read(30)) @@ -131,7 +136,7 @@ data = await stream.read() assert b'' == data - async def test_read_line_breaks(self): + async def test_read_line_breaks(self) -> None: # Read bytes without line breaks. stream = self._make_one() stream.feed_data(b'line1') @@ -143,7 +148,7 @@ data = await stream.read(5) assert b'line2' == data - async def test_read_all(self): + async def test_read_all(self) -> None: # Read all available buffered bytes stream = self._make_one() stream.feed_data(b'line1') @@ -153,7 +158,7 @@ data = await stream.read() assert b'line1line2' == data - async def test_read_up_to(self): + async def test_read_up_to(self) -> None: # Read available buffered bytes up to requested amount stream = self._make_one() stream.feed_data(b'line1') @@ -165,7 +170,8 @@ data = await stream.read(8) assert b'e2' == data - async def test_read_eof(self, loop): + async def test_read_eof(self) -> None: + loop = asyncio.get_event_loop() # Read bytes, stop at eof. stream = self._make_one() read_task = loop.create_task(stream.read(1024)) @@ -180,7 +186,7 @@ data = await stream.read() assert data == b'' - async def test_read_eof_infinit(self): + async def test_read_eof_infinite(self) -> None: # Read bytes. stream = self._make_one() stream.feed_eof() @@ -194,7 +200,7 @@ await stream.read() assert internal_logger.warning.called - async def test_read_eof_unread_data_no_warning(self): + async def test_read_eof_unread_data_no_warning(self) -> None: # Read bytes. stream = self._make_one() stream.feed_eof() @@ -205,12 +211,14 @@ await stream.read() await stream.read() await stream.read() - stream.unread_data(b'data') + with pytest.warns(DeprecationWarning): + stream.unread_data(b'data') await stream.read() await stream.read() assert not internal_logger.warning.called - async def test_read_until_eof(self, loop): + async def test_read_until_eof(self) -> None: + loop = asyncio.get_event_loop() # Read all bytes until eof. stream = self._make_one() read_task = loop.create_task(stream.read(-1)) @@ -227,7 +235,7 @@ data = await stream.read() assert b'' == data - async def test_read_exception(self): + async def test_read_exception(self) -> None: stream = self._make_one() stream.feed_data(b'line\n') @@ -238,7 +246,8 @@ with pytest.raises(ValueError): await stream.read(2) - async def test_readline(self, loop): + async def test_readline(self) -> None: + loop = asyncio.get_event_loop() # Read one line. 'readline' will need to wait for the data # to come from 'cb' stream = self._make_one() @@ -258,7 +267,7 @@ data = await stream.read() assert b' chunk4' == data - async def test_readline_limit_with_existing_data(self): + async def test_readline_limit_with_existing_data(self) -> None: # Read one line. The data is in StreamReader's buffer # before the event loop is run. @@ -273,7 +282,8 @@ data = await stream.read() assert b'line2\n' == data - async def test_readline_limit(self, loop): + async def test_readline_limit(self) -> None: + loop = asyncio.get_event_loop() # Read one line. StreamReaders are fed with data after # their 'readline' methods are called. stream = self._make_one(limit=4) @@ -290,7 +300,7 @@ data = await stream.read() assert b'chunk3\n' == data - async def test_readline_nolimit_nowait(self): + async def test_readline_nolimit_nowait(self) -> None: # All needed data for the first 'readline' call will be # in the buffer. stream = self._make_one() @@ -304,7 +314,7 @@ data = await stream.read() assert b'line2\nline3\n' == data - async def test_readline_eof(self): + async def test_readline_eof(self) -> None: stream = self._make_one() stream.feed_data(b'some data') stream.feed_eof() @@ -312,14 +322,14 @@ line = await stream.readline() assert b'some data' == line - async def test_readline_empty_eof(self): + async def test_readline_empty_eof(self) -> None: stream = self._make_one() stream.feed_eof() line = await stream.readline() assert b'' == line - async def test_readline_read_byte_count(self): + async def test_readline_read_byte_count(self) -> None: stream = self._make_one() stream.feed_data(self.DATA) @@ -332,7 +342,7 @@ data = await stream.read() assert b'ine3\n' == data - async def test_readline_exception(self): + async def test_readline_exception(self) -> None: stream = self._make_one() stream.feed_data(b'line\n') @@ -343,7 +353,7 @@ with pytest.raises(ValueError): await stream.readline() - async def test_readexactly_zero_or_less(self): + async def test_readexactly_zero_or_less(self) -> None: # Read exact number of bytes (zero or less). stream = self._make_one() stream.feed_data(self.DATA) @@ -363,7 +373,8 @@ data = await stream.read() assert self.DATA == data - async def test_readexactly(self, loop): + async def test_readexactly(self) -> None: + loop = asyncio.get_event_loop() # Read exact number of bytes. stream = self._make_one() @@ -383,7 +394,8 @@ data = await stream.read() assert self.DATA == data - async def test_readexactly_eof(self, loop): + async def test_readexactly_eof(self) -> None: + loop = asyncio.get_event_loop() # Read exact number of bytes (eof). stream = self._make_one(loop=loop) n = 2 * len(self.DATA) @@ -403,7 +415,7 @@ data = await stream.read() assert b'' == data - async def test_readexactly_exception(self): + async def test_readexactly_exception(self) -> None: stream = self._make_one() stream.feed_data(b'line\n') @@ -414,7 +426,7 @@ with pytest.raises(ValueError): await stream.readexactly(2) - async def test_unread_data(self): + async def test_unread_data(self) -> None: stream = self._make_one() stream.feed_data(b'line1') stream.feed_data(b'line2') @@ -423,7 +435,8 @@ data = await stream.read(5) assert b'line1' == data - stream.unread_data(data) + with pytest.warns(DeprecationWarning): + stream.unread_data(data) data = await stream.read(5) assert b'line1' == data @@ -431,7 +444,8 @@ data = await stream.read(4) assert b'line' == data - stream.unread_data(b'line1line') + with pytest.warns(DeprecationWarning): + stream.unread_data(b'line1line') data = b'' while len(data) < 10: @@ -441,23 +455,26 @@ data = await stream.read(7) assert b'onemore' == data - stream.unread_data(data) + with pytest.warns(DeprecationWarning): + stream.unread_data(data) data = b'' while len(data) < 11: data += await stream.read(11) assert b'onemoreline' == data - stream.unread_data(b'line') + with pytest.warns(DeprecationWarning): + stream.unread_data(b'line') data = await stream.read(4) assert b'line' == data stream.feed_eof() - stream.unread_data(b'at_eof') + with pytest.warns(DeprecationWarning): + stream.unread_data(b'at_eof') data = await stream.read(6) assert b'at_eof' == data - async def test_exception(self): + async def test_exception(self) -> None: stream = self._make_one() assert stream.exception() is None @@ -465,7 +482,8 @@ stream.set_exception(exc) assert stream.exception() is exc - async def test_exception_waiter(self, loop): + async def test_exception_waiter(self) -> None: + loop = asyncio.get_event_loop() stream = self._make_one() async def set_err(): @@ -478,7 +496,8 @@ with pytest.raises(ValueError): t1.result() - async def test_exception_cancel(self, loop): + async def test_exception_cancel(self) -> None: + loop = asyncio.get_event_loop() stream = self._make_one() async def read_a_line(): @@ -493,7 +512,8 @@ await asyncio.sleep(0) assert stream._waiter is None - async def test_readany_eof(self, loop): + async def test_readany_eof(self) -> None: + loop = asyncio.get_event_loop() stream = self._make_one() read_task = loop.create_task(stream.readany()) loop.call_soon(stream.feed_data, b'chunk1\n') @@ -504,7 +524,8 @@ data = await stream.read() assert b'' == data - async def test_readany_empty_eof(self, loop): + async def test_readany_empty_eof(self) -> None: + loop = asyncio.get_event_loop() stream = self._make_one() stream.feed_eof() read_task = loop.create_task(stream.readany()) @@ -513,7 +534,7 @@ assert b'' == data - async def test_readany_exception(self): + async def test_readany_exception(self) -> None: stream = self._make_one() stream.feed_data(b'line\n') @@ -524,7 +545,7 @@ with pytest.raises(ValueError): await stream.readany() - async def test_read_nowait(self): + async def test_read_nowait(self) -> None: stream = self._make_one() stream.feed_data(b'line1\nline2\n') @@ -534,7 +555,7 @@ data = await stream.read() assert b'' == data - async def test_read_nowait_n(self): + async def test_read_nowait_n(self) -> None: stream = self._make_one() stream.feed_data(b'line1\nline2\n') @@ -545,7 +566,7 @@ data = await stream.read() assert b'' == data - async def test_read_nowait_exception(self): + async def test_read_nowait_exception(self) -> None: stream = self._make_one() stream.feed_data(b'line\n') stream.set_exception(ValueError()) @@ -553,7 +574,8 @@ with pytest.raises(ValueError): stream.read_nowait() - async def test_read_nowait_waiter(self, loop): + async def test_read_nowait_waiter(self) -> None: + loop = asyncio.get_event_loop() stream = self._make_one() stream.feed_data(b'line\n') stream._waiter = loop.create_future() @@ -561,7 +583,8 @@ with pytest.raises(RuntimeError): stream.read_nowait() - async def test_readchunk(self, loop): + async def test_readchunk(self) -> None: + loop = asyncio.get_event_loop() stream = self._make_one() def cb(): @@ -582,7 +605,8 @@ assert b'' == data assert not end_of_chunk - async def test_readchunk_wait_eof(self, loop): + async def test_readchunk_wait_eof(self) -> None: + loop = asyncio.get_event_loop() stream = self._make_one() async def cb(): @@ -595,7 +619,7 @@ assert not end_of_chunk assert stream.is_eof() - async def test_begin_and_end_chunk_receiving(self): + async def test_begin_and_end_chunk_receiving(self) -> None: stream = self._make_one() stream.begin_http_chunk_receiving() @@ -626,12 +650,12 @@ assert b'' == data assert not end_of_chunk - async def test_end_chunk_receiving_without_begin(self): + async def test_end_chunk_receiving_without_begin(self) -> None: stream = self._make_one() with pytest.raises(RuntimeError): stream.end_http_chunk_receiving() - async def test_readchunk_with_unread(self): + async def test_readchunk_with_unread(self) -> None: """Test that stream.unread does not break controlled chunk receiving. """ stream = self._make_one() @@ -648,7 +672,8 @@ data, end_of_chunk = await stream.readchunk() # Try to unread a part of the first chunk - stream.unread_data(b'rt1') + with pytest.warns(DeprecationWarning): + stream.unread_data(b'rt1') # The end_of_chunk signal was already received for the first chunk, # so we receive up to the second one @@ -657,7 +682,8 @@ assert end_of_chunk # Unread a part of the second chunk - stream.unread_data(b'rt2') + with pytest.warns(DeprecationWarning): + stream.unread_data(b'rt2') data, end_of_chunk = await stream.readchunk() assert b'rt2' == data @@ -669,7 +695,7 @@ assert b'' == data assert not end_of_chunk - async def test_readchunk_with_other_read_calls(self): + async def test_readchunk_with_other_read_calls(self) -> None: """Test that stream.readchunk works when other read calls are made on the stream. """ @@ -694,52 +720,117 @@ assert b'' == data assert not end_of_chunk - async def test___repr__(self): + async def test_readchunk_separate_http_chunk_tail(self) -> None: + """Test that stream.readchunk returns (b'', True) when end of + http chunk received after body + """ + loop = asyncio.get_event_loop() + stream = self._make_one() + + stream.begin_http_chunk_receiving() + stream.feed_data(b'part1') + + data, end_of_chunk = await stream.readchunk() + assert b'part1' == data + assert not end_of_chunk + + async def cb(): + await asyncio.sleep(0.1) + stream.end_http_chunk_receiving() + + loop.create_task(cb()) + data, end_of_chunk = await stream.readchunk() + assert b'' == data + assert end_of_chunk + + stream.begin_http_chunk_receiving() + stream.feed_data(b'part2') + data, end_of_chunk = await stream.readchunk() + assert b'part2' == data + assert not end_of_chunk + + stream.end_http_chunk_receiving() + stream.begin_http_chunk_receiving() + stream.feed_data(b'part3') + stream.end_http_chunk_receiving() + + data, end_of_chunk = await stream.readchunk() + assert b'' == data + assert end_of_chunk + + data, end_of_chunk = await stream.readchunk() + assert b'part3' == data + assert end_of_chunk + + stream.begin_http_chunk_receiving() + stream.feed_data(b'part4') + data, end_of_chunk = await stream.readchunk() + assert b'part4' == data + assert not end_of_chunk + + async def cb(): + await asyncio.sleep(0.1) + stream.end_http_chunk_receiving() + stream.feed_eof() + + loop.create_task(cb()) + data, end_of_chunk = await stream.readchunk() + assert b'' == data + assert end_of_chunk + + data, end_of_chunk = await stream.readchunk() + assert b'' == data + assert not end_of_chunk + + async def test___repr__(self) -> None: stream = self._make_one() assert "" == repr(stream) - async def test___repr__nondefault_limit(self): + async def test___repr__nondefault_limit(self) -> None: stream = self._make_one(limit=123) assert "" == repr(stream) - async def test___repr__eof(self): + async def test___repr__eof(self) -> None: stream = self._make_one() stream.feed_eof() assert "" == repr(stream) - async def test___repr__data(self): + async def test___repr__data(self) -> None: stream = self._make_one() stream.feed_data(b'data') assert "" == repr(stream) - def test___repr__exception(self, loop): + async def test___repr__exception(self) -> None: + loop = asyncio.get_event_loop() stream = self._make_one(loop=loop) exc = RuntimeError() stream.set_exception(exc) assert "" == repr(stream) - async def test___repr__waiter(self, loop): + async def test___repr__waiter(self) -> None: + loop = asyncio.get_event_loop() stream = self._make_one() stream._waiter = loop.create_future() - assert re.search(">", + assert re.search(r">", repr(stream)) stream._waiter.set_result(None) await stream._waiter stream._waiter = None assert "" == repr(stream) - async def test_unread_empty(self): + async def test_unread_empty(self) -> None: stream = self._make_one() stream.feed_data(b'line1') stream.feed_eof() - stream.unread_data(b'') + with pytest.warns(DeprecationWarning): + stream.unread_data(b'') data = await stream.read(5) assert b'line1' == data assert stream.at_eof() -async def test_empty_stream_reader(): +async def test_empty_stream_reader() -> None: s = streams.EmptyStreamReader() assert s.set_exception(ValueError()) is None assert s.exception() is None @@ -750,41 +841,42 @@ assert await s.read() == b'' assert await s.readline() == b'' assert await s.readany() == b'' - assert await s.readchunk() == (b'', False) + assert await s.readchunk() == (b'', True) with pytest.raises(asyncio.IncompleteReadError): await s.readexactly(10) assert s.read_nowait() == b'' @pytest.fixture -def buffer(loop): - return streams.DataQueue(loop=loop) +async def buffer(loop): + return streams.DataQueue(loop) class TestDataQueue: - def test_is_eof(self, buffer): + def test_is_eof(self, buffer) -> None: assert not buffer.is_eof() buffer.feed_eof() assert buffer.is_eof() - def test_at_eof(self, buffer): + def test_at_eof(self, buffer) -> None: assert not buffer.at_eof() buffer.feed_eof() assert buffer.at_eof() buffer._buffer.append(object()) assert not buffer.at_eof() - def test_feed_data(self, buffer): + def test_feed_data(self, buffer) -> None: item = object() buffer.feed_data(item, 1) assert [(item, 1)] == list(buffer._buffer) - def test_feed_eof(self, buffer): + def test_feed_eof(self, buffer) -> None: buffer.feed_eof() assert buffer._eof - async def test_read(self, buffer, loop): + async def test_read(self, buffer) -> None: + loop = asyncio.get_event_loop() item = object() def cb(): @@ -794,7 +886,9 @@ data = await buffer.read() assert item is data - async def test_read_eof(self, buffer, loop): + async def test_read_eof(self, buffer) -> None: + loop = asyncio.get_event_loop() + def cb(): buffer.feed_eof() loop.call_soon(cb) @@ -802,7 +896,8 @@ with pytest.raises(streams.EofStream): await buffer.read() - async def test_read_cancelled(self, buffer, loop): + async def test_read_cancelled(self, buffer) -> None: + loop = asyncio.get_event_loop() read_task = loop.create_task(buffer.read()) await asyncio.sleep(0) waiter = buffer._waiter @@ -817,7 +912,7 @@ buffer.feed_data(b'test', 4) assert buffer._waiter is None - async def test_read_until_eof(self, buffer): + async def test_read_until_eof(self, buffer) -> None: item = object() buffer.feed_data(item, 1) buffer.feed_eof() @@ -828,7 +923,7 @@ with pytest.raises(streams.EofStream): await buffer.read() - async def test_read_exc(self, buffer): + async def test_read_exc(self, buffer) -> None: item = object() buffer.feed_data(item) buffer.set_exception(ValueError) @@ -839,13 +934,13 @@ with pytest.raises(ValueError): await buffer.read() - async def test_read_exception(self, buffer): + async def test_read_exception(self, buffer) -> None: buffer.set_exception(ValueError()) with pytest.raises(ValueError): await buffer.read() - async def test_read_exception_with_data(self, buffer): + async def test_read_exception_with_data(self, buffer) -> None: val = object() buffer.feed_data(val, 1) buffer.set_exception(ValueError()) @@ -854,7 +949,8 @@ with pytest.raises(ValueError): await buffer.read() - async def test_read_exception_on_wait(self, buffer, loop): + async def test_read_exception_on_wait(self, buffer) -> None: + loop = asyncio.get_event_loop() read_task = loop.create_task(buffer.read()) await asyncio.sleep(0) assert asyncio.isfuture(buffer._waiter) @@ -865,14 +961,15 @@ with pytest.raises(ValueError): await read_task - def test_exception(self, buffer): + def test_exception(self, buffer) -> None: assert buffer.exception() is None exc = ValueError() buffer.set_exception(exc) assert buffer.exception() is exc - async def test_exception_waiter(self, buffer, loop): + async def test_exception_waiter(self, buffer) -> None: + loop = asyncio.get_event_loop() async def set_err(): buffer.set_exception(ValueError()) @@ -886,7 +983,8 @@ t1.result() -def test_feed_data_waiters(loop, protocol): +async def test_feed_data_waiters(protocol) -> None: + loop = asyncio.get_event_loop() reader = streams.StreamReader(protocol, loop=loop) waiter = reader._waiter = loop.create_future() eof_waiter = reader._eof_waiter = loop.create_future() @@ -902,7 +1000,8 @@ assert reader._eof_waiter is eof_waiter -def test_feed_data_completed_waiters(loop, protocol): +async def test_feed_data_completed_waiters(protocol) -> None: + loop = asyncio.get_event_loop() reader = streams.StreamReader(protocol, loop=loop) waiter = reader._waiter = loop.create_future() @@ -912,7 +1011,8 @@ assert reader._waiter is None -def test_feed_eof_waiters(loop, protocol): +async def test_feed_eof_waiters(protocol) -> None: + loop = asyncio.get_event_loop() reader = streams.StreamReader(protocol, loop=loop) waiter = reader._waiter = loop.create_future() eof_waiter = reader._eof_waiter = loop.create_future() @@ -926,7 +1026,8 @@ assert reader._eof_waiter is None -def test_feed_eof_cancelled(loop, protocol): +async def test_feed_eof_cancelled(protocol) -> None: + loop = asyncio.get_event_loop() reader = streams.StreamReader(protocol, loop=loop) waiter = reader._waiter = loop.create_future() eof_waiter = reader._eof_waiter = loop.create_future() @@ -942,7 +1043,8 @@ assert reader._eof_waiter is None -def test_on_eof(loop, protocol): +async def test_on_eof(protocol) -> None: + loop = asyncio.get_event_loop() reader = streams.StreamReader(protocol, loop=loop) on_eof = mock.Mock() @@ -953,7 +1055,7 @@ assert on_eof.called -def test_on_eof_empty_reader(loop): +async def test_on_eof_empty_reader() -> None: reader = streams.EmptyStreamReader() on_eof = mock.Mock() @@ -962,7 +1064,8 @@ assert on_eof.called -def test_on_eof_exc_in_callback(loop, protocol): +async def test_on_eof_exc_in_callback(protocol) -> None: + loop = asyncio.get_event_loop() reader = streams.StreamReader(protocol, loop=loop) on_eof = mock.Mock() @@ -975,7 +1078,7 @@ assert not reader._eof_callbacks -def test_on_eof_exc_in_callback_empty_stream_reader(loop): +async def test_on_eof_exc_in_callback_empty_stream_reader() -> None: reader = streams.EmptyStreamReader() on_eof = mock.Mock() @@ -985,7 +1088,8 @@ assert on_eof.called -def test_on_eof_eof_is_set(loop, protocol): +async def test_on_eof_eof_is_set(protocol) -> None: + loop = asyncio.get_event_loop() reader = streams.StreamReader(protocol, loop=loop) reader.feed_eof() @@ -995,7 +1099,8 @@ assert not reader._eof_callbacks -def test_on_eof_eof_is_set_exception(loop, protocol): +async def test_on_eof_eof_is_set_exception(protocol) -> None: + loop = asyncio.get_event_loop() reader = streams.StreamReader(protocol, loop=loop) reader.feed_eof() @@ -1007,7 +1112,8 @@ assert not reader._eof_callbacks -def test_set_exception(loop, protocol): +async def test_set_exception(protocol) -> None: + loop = asyncio.get_event_loop() reader = streams.StreamReader(protocol, loop=loop) waiter = reader._waiter = loop.create_future() eof_waiter = reader._eof_waiter = loop.create_future() @@ -1021,7 +1127,8 @@ assert reader._eof_waiter is None -def test_set_exception_cancelled(loop, protocol): +async def test_set_exception_cancelled(protocol) -> None: + loop = asyncio.get_event_loop() reader = streams.StreamReader(protocol, loop=loop) waiter = reader._waiter = loop.create_future() eof_waiter = reader._eof_waiter = loop.create_future() @@ -1038,7 +1145,8 @@ assert reader._eof_waiter is None -def test_set_exception_eof_callbacks(loop, protocol): +async def test_set_exception_eof_callbacks(protocol) -> None: + loop = asyncio.get_event_loop() reader = streams.StreamReader(protocol, loop=loop) on_eof = mock.Mock() @@ -1049,43 +1157,45 @@ assert not reader._eof_callbacks -async def test_stream_reader_lines(loop): +async def test_stream_reader_lines() -> None: line_iter = iter(DATA.splitlines(keepends=True)) - async for line in create_stream(loop): + async for line in await create_stream(): assert line == next(line_iter, None) pytest.raises(StopIteration, next, line_iter) -async def test_stream_reader_chunks_complete(loop): +async def test_stream_reader_chunks_complete() -> None: """Tests if chunked iteration works if the chunking works out (i.e. the data is divisible by the chunk size) """ chunk_iter = chunkify(DATA, 9) - async for data in create_stream(loop).iter_chunked(9): + async for data in (await create_stream()).iter_chunked(9): assert data == next(chunk_iter, None) pytest.raises(StopIteration, next, chunk_iter) -async def test_stream_reader_chunks_incomplete(loop): +async def test_stream_reader_chunks_incomplete() -> None: """Tests if chunked iteration works if the last chunk is incomplete""" chunk_iter = chunkify(DATA, 8) - async for data in create_stream(loop).iter_chunked(8): + async for data in (await create_stream()).iter_chunked(8): assert data == next(chunk_iter, None) pytest.raises(StopIteration, next, chunk_iter) -async def test_data_queue_empty(loop): +async def test_data_queue_empty() -> None: """Tests that async looping yields nothing if nothing is there""" - buffer = streams.DataQueue(loop=loop) + loop = asyncio.get_event_loop() + buffer = streams.DataQueue(loop) buffer.feed_eof() async for _ in buffer: # NOQA assert False -async def test_data_queue_items(loop): +async def test_data_queue_items() -> None: """Tests that async looping yields objects identically""" - buffer = streams.DataQueue(loop=loop) + loop = asyncio.get_event_loop() + buffer = streams.DataQueue(loop) items = [object(), object()] buffer.feed_data(items[0], 1) @@ -1098,30 +1208,31 @@ pytest.raises(StopIteration, next, item_iter) -async def test_stream_reader_iter_any(loop): +async def test_stream_reader_iter_any() -> None: it = iter([b'line1\nline2\nline3\n']) - async for raw in create_stream(loop).iter_any(): + async for raw in (await create_stream()).iter_any(): assert raw == next(it) pytest.raises(StopIteration, next, it) -async def test_stream_reader_iter(loop): +async def test_stream_reader_iter() -> None: it = iter([b'line1\n', b'line2\n', b'line3\n']) - async for raw in create_stream(loop): + async for raw in await create_stream(): assert raw == next(it) pytest.raises(StopIteration, next, it) -async def test_stream_reader_iter_chunks_no_chunked_encoding(loop): +async def test_stream_reader_iter_chunks_no_chunked_encoding() -> None: it = iter([b'line1\nline2\nline3\n']) - async for data, end_of_chunk in create_stream(loop).iter_chunks(): + async for data, end_of_chunk in (await create_stream()).iter_chunks(): assert (data, end_of_chunk) == (next(it), False) pytest.raises(StopIteration, next, it) -async def test_stream_reader_iter_chunks_chunked_encoding(loop, protocol): +async def test_stream_reader_iter_chunks_chunked_encoding(protocol) -> None: + loop = asyncio.get_event_loop() stream = streams.StreamReader(protocol, loop=loop) for line in DATA.splitlines(keepends=True): stream.begin_http_chunk_receiving() diff -Nru python-aiohttp-3.1.3/tests/test_tcp_helpers.py python-aiohttp-3.5.1/tests/test_tcp_helpers.py --- python-aiohttp-3.1.3/tests/test_tcp_helpers.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_tcp_helpers.py 2018-12-24 20:58:54.000000000 +0000 @@ -19,7 +19,7 @@ # nodelay -def test_tcp_nodelay_exception(): +def test_tcp_nodelay_exception() -> None: transport = mock.Mock() s = mock.Mock() s.setsockopt = mock.Mock() @@ -34,7 +34,7 @@ ) -def test_tcp_nodelay_enable(): +def test_tcp_nodelay_enable() -> None: transport = mock.Mock() with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: transport.get_extra_info.return_value = s @@ -42,7 +42,7 @@ assert s.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY) -def test_tcp_nodelay_enable_and_disable(): +def test_tcp_nodelay_enable_and_disable() -> None: transport = mock.Mock() with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: transport.get_extra_info.return_value = s @@ -53,7 +53,7 @@ @pytest.mark.skipif(not has_ipv6, reason="IPv6 is not available") -def test_tcp_nodelay_enable_ipv6(): +def test_tcp_nodelay_enable_ipv6() -> None: transport = mock.Mock() with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s: transport.get_extra_info.return_value = s @@ -63,7 +63,7 @@ @pytest.mark.skipif(not hasattr(socket, 'AF_UNIX'), reason="requires unix sockets") -def test_tcp_nodelay_enable_unix(): +def test_tcp_nodelay_enable_unix() -> None: # do not set nodelay for unix socket transport = mock.Mock() s = mock.Mock(family=socket.AF_UNIX, type=socket.SOCK_STREAM) @@ -72,7 +72,7 @@ assert not s.setsockopt.called -def test_tcp_nodelay_enable_no_socket(): +def test_tcp_nodelay_enable_no_socket() -> None: transport = mock.Mock() transport.get_extra_info.return_value = None tcp_nodelay(transport, True) @@ -82,7 +82,7 @@ @pytest.mark.skipif(CORK is None, reason="TCP_CORK or TCP_NOPUSH required") -def test_tcp_cork_enable(): +def test_tcp_cork_enable() -> None: transport = mock.Mock() with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: transport.get_extra_info.return_value = s @@ -91,7 +91,7 @@ @pytest.mark.skipif(CORK is None, reason="TCP_CORK or TCP_NOPUSH required") -def test_set_cork_enable_and_disable(): +def test_set_cork_enable_and_disable() -> None: transport = mock.Mock() with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: transport.get_extra_info.return_value = s @@ -103,7 +103,7 @@ @pytest.mark.skipif(not has_ipv6, reason="IPv6 is not available") @pytest.mark.skipif(CORK is None, reason="TCP_CORK or TCP_NOPUSH required") -def test_set_cork_enable_ipv6(): +def test_set_cork_enable_ipv6() -> None: transport = mock.Mock() with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s: transport.get_extra_info.return_value = s @@ -114,7 +114,7 @@ @pytest.mark.skipif(not hasattr(socket, 'AF_UNIX'), reason="requires unix sockets") @pytest.mark.skipif(CORK is None, reason="TCP_CORK or TCP_NOPUSH required") -def test_set_cork_enable_unix(): +def test_set_cork_enable_unix() -> None: transport = mock.Mock() s = mock.Mock(family=socket.AF_UNIX, type=socket.SOCK_STREAM) transport.get_extra_info.return_value = s @@ -123,14 +123,14 @@ @pytest.mark.skipif(CORK is None, reason="TCP_CORK or TCP_NOPUSH required") -def test_set_cork_enable_no_socket(): +def test_set_cork_enable_no_socket() -> None: transport = mock.Mock() transport.get_extra_info.return_value = None tcp_cork(transport, True) @pytest.mark.skipif(CORK is None, reason="TCP_CORK or TCP_NOPUSH required") -def test_set_cork_exception(): +def test_set_cork_exception() -> None: transport = mock.Mock() s = mock.Mock() s.setsockopt = mock.Mock() diff -Nru python-aiohttp-3.1.3/tests/test_test_utils.py python-aiohttp-3.5.1/tests/test_test_utils.py --- python-aiohttp-3.1.3/tests/test_test_utils.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_test_utils.py 2018-12-24 20:58:54.000000000 +0000 @@ -2,16 +2,16 @@ from unittest import mock import pytest -from multidict import CIMultiDict +from multidict import CIMultiDict, CIMultiDictProxy from yarl import URL import aiohttp from aiohttp import web from aiohttp.test_utils import AioHTTPTestCase +from aiohttp.test_utils import RawTestServer as _RawTestServer from aiohttp.test_utils import TestClient as _TestClient from aiohttp.test_utils import TestServer as _TestServer from aiohttp.test_utils import (loop_context, make_mocked_request, - setup_test_loop, teardown_test_loop, unittest_run_loop) @@ -62,38 +62,40 @@ @pytest.fixture -def test_client(loop, app): - client = _TestClient(_TestServer(app, loop=loop), loop=loop) +def test_client(loop, app) -> None: + async def make_client(): + return _TestClient(_TestServer(app, loop=loop), loop=loop) + + client = loop.run_until_complete(make_client()) + loop.run_until_complete(client.start_server()) yield client loop.run_until_complete(client.close()) -def test_with_test_server_fails(loop): +def test_with_test_server_fails(loop) -> None: app = _create_example_app() with pytest.raises(TypeError): with _TestServer(app, loop=loop): pass -def test_with_client_fails(loop): +async def test_with_client_fails(loop) -> None: app = _create_example_app() with pytest.raises(TypeError): with _TestClient(_TestServer(app, loop=loop), loop=loop): pass -def test_aiohttp_client_close_is_idempotent(): +async def test_aiohttp_client_close_is_idempotent() -> None: """ a test client, called multiple times, should not attempt to close the server again. """ - loop = setup_test_loop() app = _create_example_app() - client = _TestClient(_TestServer(app, loop=loop), loop=loop) - loop.run_until_complete(client.close()) - loop.run_until_complete(client.close()) - teardown_test_loop(loop) + client = _TestClient(_TestServer(app)) + await client.close() + await client.close() class TestAioHTTPTestCase(AioHTTPTestCase): @@ -102,14 +104,14 @@ return _create_example_app() @unittest_run_loop - async def test_example_with_loop(self): + async def test_example_with_loop(self) -> None: request = await self.client.request("GET", "/") assert request.status == 200 text = await request.text() assert _hello_world_str == text - def test_example(self): - async def test_get_route(): + def test_example(self) -> None: + async def test_get_route() -> None: resp = await self.client.request("GET", "/") assert resp.status == 200 text = await resp.text() @@ -118,8 +120,8 @@ self.loop.run_until_complete(test_get_route()) -def test_get_route(loop, test_client): - async def test_get_route(): +def test_get_route(loop, test_client) -> None: + async def test_get_route() -> None: resp = await test_client.request("GET", "/") assert resp.status == 200 text = await resp.text() @@ -128,7 +130,7 @@ loop.run_until_complete(test_get_route()) -async def test_client_websocket(loop, test_client): +async def test_client_websocket(loop, test_client) -> None: resp = await test_client.ws_connect("/websocket") await resp.send_str("foo") msg = await resp.receive() @@ -139,7 +141,7 @@ assert msg.type == aiohttp.WSMsgType.CLOSE -async def test_client_cookie(loop, test_client): +async def test_client_cookie(loop, test_client) -> None: assert not test_client.session.cookie_jar await test_client.get("/cookie") cookies = list(test_client.session.cookie_jar) @@ -150,62 +152,68 @@ @pytest.mark.parametrize("method", [ "get", "post", "options", "post", "put", "patch", "delete" ]) -async def test_test_client_methods(method, loop, test_client): +async def test_test_client_methods(method, loop, test_client) -> None: resp = await getattr(test_client, method)("/") assert resp.status == 200 text = await resp.text() assert _hello_world_str == text -async def test_test_client_head(loop, test_client): +async def test_test_client_head(loop, test_client) -> None: resp = await test_client.head("/") assert resp.status == 200 @pytest.mark.parametrize( "headers", [{'token': 'x'}, CIMultiDict({'token': 'x'}), {}]) -def test_make_mocked_request(headers): +def test_make_mocked_request(headers) -> None: req = make_mocked_request('GET', '/', headers=headers) assert req.method == "GET" assert req.path == "/" assert isinstance(req, web.Request) - assert isinstance(req.headers, CIMultiDict) + assert isinstance(req.headers, CIMultiDictProxy) -def test_make_mocked_request_sslcontext(): +def test_make_mocked_request_sslcontext() -> None: req = make_mocked_request('GET', '/') assert req.transport.get_extra_info('sslcontext') is None -def test_make_mocked_request_unknown_extra_info(): +def test_make_mocked_request_unknown_extra_info() -> None: req = make_mocked_request('GET', '/') assert req.transport.get_extra_info('unknown_extra_info') is None -def test_make_mocked_request_app(): +def test_make_mocked_request_app() -> None: app = mock.Mock() req = make_mocked_request('GET', '/', app=app) assert req.app is app -def test_make_mocked_request_match_info(): +def test_make_mocked_request_app_can_store_values() -> None: + req = make_mocked_request('GET', '/') + req.app['a_field'] = 'a_value' + assert req.app['a_field'] == 'a_value' + + +def test_make_mocked_request_match_info() -> None: req = make_mocked_request('GET', '/', match_info={'a': '1', 'b': '2'}) assert req.match_info == {'a': '1', 'b': '2'} -def test_make_mocked_request_content(): +def test_make_mocked_request_content() -> None: payload = mock.Mock() req = make_mocked_request('GET', '/', payload=payload) assert req.content is payload -def test_make_mocked_request_transport(): +def test_make_mocked_request_transport() -> None: transport = mock.Mock() req = make_mocked_request('GET', '/', transport=transport) assert req.transport is transport -async def test_test_client_props(loop): +async def test_test_client_props(loop) -> None: app = _create_example_app() client = _TestClient(_TestServer(app, host='127.0.0.1', loop=loop), loop=loop) @@ -214,10 +222,27 @@ async with client: assert isinstance(client.port, int) assert client.server is not None + assert client.app is not None + assert client.port is None + + +async def test_test_client_raw_server_props(loop) -> None: + + async def hello(request): + return web.Response(body=_hello_world_bytes) + + client = _TestClient(_RawTestServer(hello, host='127.0.0.1', loop=loop), + loop=loop) + assert client.host == '127.0.0.1' + assert client.port is None + async with client: + assert isinstance(client.port, int) + assert client.server is not None + assert client.app is None assert client.port is None -async def test_test_server_context_manager(loop): +async def test_test_server_context_manager(loop) -> None: app = _create_example_app() async with _TestServer(app, loop=loop) as server: client = aiohttp.ClientSession(loop=loop) @@ -227,12 +252,15 @@ await client.close() -def test_client_unsupported_arg(): - with pytest.raises(TypeError): +def test_client_unsupported_arg() -> None: + with pytest.raises(TypeError) as e: _TestClient('string') + assert str(e.value) == \ + "server must be TestServer instance, found type: " + -async def test_server_make_url_yarl_compatibility(loop): +async def test_server_make_url_yarl_compatibility(loop) -> None: app = _create_example_app() async with _TestServer(app, loop=loop) as server: make_url = server.make_url @@ -243,21 +271,21 @@ make_url(URL('http://foo.com')) -def test_testcase_no_app(testdir, loop): +def test_testcase_no_app(testdir, loop) -> None: testdir.makepyfile( """ from aiohttp.test_utils import AioHTTPTestCase class InvalidTestCase(AioHTTPTestCase): - def test_noop(self): + def test_noop(self) -> None: pass """) result = testdir.runpytest() result.stdout.fnmatch_lines(["*RuntimeError*"]) -async def test_server_context_manager(app, loop): +async def test_server_context_manager(app, loop) -> None: async with _TestServer(app, loop=loop) as server: async with aiohttp.ClientSession(loop=loop) as client: async with client.head(server.make_url('/')) as resp: @@ -267,7 +295,7 @@ @pytest.mark.parametrize("method", [ "head", "get", "post", "options", "post", "put", "patch", "delete" ]) -async def test_client_context_manager_response(method, app, loop): +async def test_client_context_manager_response(method, app, loop) -> None: async with _TestClient(_TestServer(app), loop=loop) as client: async with getattr(client, method)('/') as resp: assert resp.status == 200 @@ -276,7 +304,7 @@ assert "Hello, world" in text -async def test_custom_port(loop, app, aiohttp_unused_port): +async def test_custom_port(loop, app, aiohttp_unused_port) -> None: port = aiohttp_unused_port() client = _TestClient(_TestServer(app, loop=loop, port=port), loop=loop) await client.start_server() diff -Nru python-aiohttp-3.1.3/tests/test_tracing.py python-aiohttp-3.5.1/tests/test_tracing.py --- python-aiohttp-3.1.3/tests/test_tracing.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_tracing.py 2018-12-24 20:58:54.000000000 +0000 @@ -23,22 +23,22 @@ class TestTraceConfig: - def test_trace_config_ctx_default(self): + def test_trace_config_ctx_default(self) -> None: trace_config = TraceConfig() assert isinstance(trace_config.trace_config_ctx(), SimpleNamespace) - def test_trace_config_ctx_factory(self): + def test_trace_config_ctx_factory(self) -> None: trace_config = TraceConfig(trace_config_ctx_factory=dict) assert isinstance(trace_config.trace_config_ctx(), dict) - def test_trace_config_ctx_request_ctx(self): + def test_trace_config_ctx_request_ctx(self) -> None: trace_request_ctx = Mock() trace_config = TraceConfig() trace_config_ctx = trace_config.trace_config_ctx( trace_request_ctx=trace_request_ctx) assert trace_config_ctx.trace_request_ctx is trace_request_ctx - def test_freeze(self): + def test_freeze(self) -> None: trace_config = TraceConfig() trace_config.freeze() @@ -138,7 +138,7 @@ TraceDnsCacheMissParams ) ]) - async def test_send(self, loop, signal, params, param_obj): + async def test_send(self, signal, params, param_obj) -> None: session = Mock() trace_request_ctx = Mock() callback = Mock(side_effect=asyncio.coroutine(Mock())) diff -Nru python-aiohttp-3.1.3/tests/test_urldispatch.py python-aiohttp-3.5.1/tests/test_urldispatch.py --- python-aiohttp-3.1.3/tests/test_urldispatch.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_urldispatch.py 2018-12-24 20:58:54.000000000 +0000 @@ -11,15 +11,13 @@ from aiohttp import hdrs, web from aiohttp.test_utils import make_mocked_request from aiohttp.web import HTTPMethodNotAllowed, HTTPNotFound, Response -from aiohttp.web_urldispatcher import (PATH_SEP, AbstractResource, - ResourceRoute, SystemRoute, View, +from aiohttp.web_urldispatcher import (PATH_SEP, AbstractResource, Domain, + DynamicResource, MaskDomain, + PlainResource, ResourceRoute, + StaticResource, SystemRoute, View, _default_expect_handler) -def make_request(method, path): - return make_mocked_request(method, path) - - def make_handler(): async def handler(request): @@ -29,10 +27,8 @@ @pytest.fixture -def app(loop): - app = web.Application() - app._set_loop(loop) - return app +def app(): + return web.Application() @pytest.fixture @@ -52,7 +48,7 @@ return go -def test_register_uncommon_http_methods(router): +def test_register_uncommon_http_methods(router) -> None: uncommon_http_methods = { 'PROPFIND', 'PROPPATCH', @@ -69,10 +65,10 @@ router.add_route(method, '/handler/to/path', make_handler()) -async def test_add_route_root(router): +async def test_add_route_root(router) -> None: handler = make_handler() router.add_route('GET', '/', handler) - req = make_request('GET', '/') + req = make_mocked_request('GET', '/') info = await router.resolve(req) assert info is not None assert 0 == len(info) @@ -80,10 +76,10 @@ assert info.route.name is None -async def test_add_route_simple(router): +async def test_add_route_simple(router) -> None: handler = make_handler() router.add_route('GET', '/handler/to/path', handler) - req = make_request('GET', '/handler/to/path') + req = make_mocked_request('GET', '/handler/to/path') info = await router.resolve(req) assert info is not None assert 0 == len(info) @@ -91,10 +87,10 @@ assert info.route.name is None -async def test_add_with_matchdict(router): +async def test_add_with_matchdict(router) -> None: handler = make_handler() router.add_route('GET', '/handler/{to}', handler) - req = make_request('GET', '/handler/tail') + req = make_mocked_request('GET', '/handler/tail') info = await router.resolve(req) assert info is not None assert {'to': 'tail'} == info @@ -102,10 +98,10 @@ assert info.route.name is None -async def test_add_with_matchdict_with_colon(router): +async def test_add_with_matchdict_with_colon(router) -> None: handler = make_handler() router.add_route('GET', '/handler/{to}', handler) - req = make_request('GET', '/handler/1:2:3') + req = make_mocked_request('GET', '/handler/1:2:3') info = await router.resolve(req) assert info is not None assert {'to': '1:2:3'} == info @@ -113,10 +109,10 @@ assert info.route.name is None -async def test_add_route_with_add_get_shortcut(router): +async def test_add_route_with_add_get_shortcut(router) -> None: handler = make_handler() router.add_get('/handler/to/path', handler) - req = make_request('GET', '/handler/to/path') + req = make_mocked_request('GET', '/handler/to/path') info = await router.resolve(req) assert info is not None assert 0 == len(info) @@ -124,10 +120,10 @@ assert info.route.name is None -async def test_add_route_with_add_post_shortcut(router): +async def test_add_route_with_add_post_shortcut(router) -> None: handler = make_handler() router.add_post('/handler/to/path', handler) - req = make_request('POST', '/handler/to/path') + req = make_mocked_request('POST', '/handler/to/path') info = await router.resolve(req) assert info is not None assert 0 == len(info) @@ -135,10 +131,10 @@ assert info.route.name is None -async def test_add_route_with_add_put_shortcut(router): +async def test_add_route_with_add_put_shortcut(router) -> None: handler = make_handler() router.add_put('/handler/to/path', handler) - req = make_request('PUT', '/handler/to/path') + req = make_mocked_request('PUT', '/handler/to/path') info = await router.resolve(req) assert info is not None assert 0 == len(info) @@ -146,10 +142,10 @@ assert info.route.name is None -async def test_add_route_with_add_patch_shortcut(router): +async def test_add_route_with_add_patch_shortcut(router) -> None: handler = make_handler() router.add_patch('/handler/to/path', handler) - req = make_request('PATCH', '/handler/to/path') + req = make_mocked_request('PATCH', '/handler/to/path') info = await router.resolve(req) assert info is not None assert 0 == len(info) @@ -157,10 +153,10 @@ assert info.route.name is None -async def test_add_route_with_add_delete_shortcut(router): +async def test_add_route_with_add_delete_shortcut(router) -> None: handler = make_handler() router.add_delete('/handler/to/path', handler) - req = make_request('DELETE', '/handler/to/path') + req = make_mocked_request('DELETE', '/handler/to/path') info = await router.resolve(req) assert info is not None assert 0 == len(info) @@ -168,10 +164,10 @@ assert info.route.name is None -async def test_add_route_with_add_head_shortcut(router): +async def test_add_route_with_add_head_shortcut(router) -> None: handler = make_handler() router.add_head('/handler/to/path', handler) - req = make_request('HEAD', '/handler/to/path') + req = make_mocked_request('HEAD', '/handler/to/path') info = await router.resolve(req) assert info is not None assert 0 == len(info) @@ -179,100 +175,100 @@ assert info.route.name is None -async def test_add_with_name(router): +async def test_add_with_name(router) -> None: handler = make_handler() router.add_route('GET', '/handler/to/path', handler, name='name') - req = make_request('GET', '/handler/to/path') + req = make_mocked_request('GET', '/handler/to/path') info = await router.resolve(req) assert info is not None assert 'name' == info.route.name -async def test_add_with_tailing_slash(router): +async def test_add_with_tailing_slash(router) -> None: handler = make_handler() router.add_route('GET', '/handler/to/path/', handler) - req = make_request('GET', '/handler/to/path/') + req = make_mocked_request('GET', '/handler/to/path/') info = await router.resolve(req) assert info is not None assert {} == info assert handler is info.handler -def test_add_invalid_path(router): +def test_add_invalid_path(router) -> None: handler = make_handler() with pytest.raises(ValueError): router.add_route('GET', '/{/', handler) -def test_add_url_invalid1(router): +def test_add_url_invalid1(router) -> None: handler = make_handler() with pytest.raises(ValueError): router.add_route('post', '/post/{id', handler) -def test_add_url_invalid2(router): +def test_add_url_invalid2(router) -> None: handler = make_handler() with pytest.raises(ValueError): router.add_route('post', '/post/{id{}}', handler) -def test_add_url_invalid3(router): +def test_add_url_invalid3(router) -> None: handler = make_handler() with pytest.raises(ValueError): router.add_route('post', '/post/{id{}', handler) -def test_add_url_invalid4(router): +def test_add_url_invalid4(router) -> None: handler = make_handler() with pytest.raises(ValueError): router.add_route('post', '/post/{id"}', handler) -async def test_add_url_escaping(router): +async def test_add_url_escaping(router) -> None: handler = make_handler() router.add_route('GET', '/+$', handler) - req = make_request('GET', '/+$') + req = make_mocked_request('GET', '/+$') info = await router.resolve(req) assert info is not None assert handler is info.handler -async def test_any_method(router): +async def test_any_method(router) -> None: handler = make_handler() route = router.add_route(hdrs.METH_ANY, '/', handler) - req = make_request('GET', '/') + req = make_mocked_request('GET', '/') info1 = await router.resolve(req) assert info1 is not None assert route is info1.route - req = make_request('POST', '/') + req = make_mocked_request('POST', '/') info2 = await router.resolve(req) assert info2 is not None assert info1.route is info2.route -async def test_match_second_result_in_table(router): +async def test_match_second_result_in_table(router) -> None: handler1 = make_handler() handler2 = make_handler() router.add_route('GET', '/h1', handler1) router.add_route('POST', '/h2', handler2) - req = make_request('POST', '/h2') + req = make_mocked_request('POST', '/h2') info = await router.resolve(req) assert info is not None assert {} == info assert handler2 is info.handler -async def test_raise_method_not_allowed(router): +async def test_raise_method_not_allowed(router) -> None: handler1 = make_handler() handler2 = make_handler() router.add_route('GET', '/', handler1) router.add_route('POST', '/', handler2) - req = make_request('PUT', '/') + req = make_mocked_request('PUT', '/') match_info = await router.resolve(req) assert isinstance(match_info.route, SystemRoute) @@ -287,10 +283,10 @@ assert {'POST', 'GET'} == exc.allowed_methods -async def test_raise_method_not_found(router): +async def test_raise_method_not_found(router) -> None: handler = make_handler() router.add_route('GET', '/a', handler) - req = make_request('GET', '/b') + req = make_mocked_request('GET', '/b') match_info = await router.resolve(req) assert isinstance(match_info.route, SystemRoute) @@ -303,7 +299,7 @@ assert 404 == exc.status -def test_double_add_url_with_the_same_name(router): +def test_double_add_url_with_the_same_name(router) -> None: handler1 = make_handler() handler2 = make_handler() router.add_route('GET', '/get', handler1, name='name') @@ -314,7 +310,7 @@ assert re.match(regexp, str(ctx.value)) -def test_route_plain(router): +def test_route_plain(router) -> None: handler = make_handler() route = router.add_route('GET', '/get', handler, name='name') route2 = next(iter(router['name'])) @@ -323,12 +319,12 @@ assert route is route2 -def test_route_unknown_route_name(router): +def test_route_unknown_route_name(router) -> None: with pytest.raises(KeyError): router['unknown'] -def test_route_dynamic(router): +def test_route_dynamic(router) -> None: handler = make_handler() route = router.add_route('GET', '/get/{name}', handler, name='name') @@ -339,7 +335,7 @@ assert route is route2 -def test_add_static(router): +def test_add_static(router) -> None: resource = router.add_static('/st', os.path.dirname(aiohttp.__file__), name='static') @@ -349,7 +345,7 @@ assert len(resource) == 2 -def test_add_static_append_version(router): +def test_add_static_append_version(router) -> None: resource = router.add_static('/st', os.path.dirname(__file__), name='static') @@ -360,7 +356,7 @@ assert expect_url == str(url) -def test_add_static_append_version_set_from_constructor(router): +def test_add_static_append_version_set_from_constructor(router) -> None: resource = router.add_static('/st', os.path.dirname(__file__), append_version=True, @@ -371,7 +367,7 @@ assert expect_url == str(url) -def test_add_static_append_version_override_constructor(router): +def test_add_static_append_version_override_constructor(router) -> None: resource = router.add_static('/st', os.path.dirname(__file__), append_version=True, @@ -382,7 +378,7 @@ assert expect_url == str(url) -def test_add_static_append_version_filename_without_slash(router): +def test_add_static_append_version_filename_without_slash(router) -> None: resource = router.add_static('/st', os.path.dirname(__file__), name='static') @@ -393,7 +389,7 @@ assert expect_url == str(url) -def test_add_static_append_version_non_exists_file(router): +def test_add_static_append_version_non_exists_file(router) -> None: resource = router.add_static('/st', os.path.dirname(__file__), name='static') @@ -401,7 +397,8 @@ assert '/st/non_exists_file' == str(url) -def test_add_static_append_version_non_exists_file_without_slash(router): +def test_add_static_append_version_non_exists_file_without_slash( + router) -> None: resource = router.add_static('/st', os.path.dirname(__file__), name='static') @@ -409,7 +406,7 @@ assert '/st/non_exists_file' == str(url) -def test_add_static_append_version_follow_symlink(router, tmpdir): +def test_add_static_append_version_follow_symlink(router, tmpdir) -> None: """ Tests the access to a symlink, in static folder with apeend_version """ @@ -430,7 +427,7 @@ assert expect_url == str(url) -def test_add_static_append_version_not_follow_symlink(router, tmpdir): +def test_add_static_append_version_not_follow_symlink(router, tmpdir) -> None: """ Tests the access to a symlink, in static folder with apeend_version """ @@ -448,21 +445,21 @@ assert '/st/append_version_symlink/data.unknown_mime_type' == str(url) -def test_plain_not_match(router): +def test_plain_not_match(router) -> None: handler = make_handler() router.add_route('GET', '/get/path', handler, name='name') route = router['name'] assert route._match('/another/path') is None -def test_dynamic_not_match(router): +def test_dynamic_not_match(router) -> None: handler = make_handler() router.add_route('GET', '/get/{name}', handler, name='name') route = router['name'] assert route._match('/another/path') is None -async def test_static_not_match(router): +async def test_static_not_match(router) -> None: router.add_static('/pre', os.path.dirname(aiohttp.__file__), name='name') resource = router['name'] @@ -471,28 +468,28 @@ assert (None, set()) == ret -def test_dynamic_with_trailing_slash(router): +def test_dynamic_with_trailing_slash(router) -> None: handler = make_handler() router.add_route('GET', '/get/{name}/', handler, name='name') route = router['name'] assert {'name': 'John'} == route._match('/get/John/') -def test_len(router): +def test_len(router) -> None: handler = make_handler() router.add_route('GET', '/get1', handler, name='name1') router.add_route('GET', '/get2', handler, name='name2') assert 2 == len(router) -def test_iter(router): +def test_iter(router) -> None: handler = make_handler() router.add_route('GET', '/get1', handler, name='name1') router.add_route('GET', '/get2', handler, name='name2') assert {'name1', 'name2'} == set(iter(router)) -def test_contains(router): +def test_contains(router) -> None: handler = make_handler() router.add_route('GET', '/get1', handler, name='name1') router.add_route('GET', '/get2', handler, name='name2') @@ -500,59 +497,59 @@ assert 'name3' not in router -def test_static_repr(router): +def test_static_repr(router) -> None: router.add_static('/get', os.path.dirname(aiohttp.__file__), name='name') assert re.match(r" None: route = router.add_static('/prefix', os.path.dirname(aiohttp.__file__)) assert '/prefix' == route._prefix -def test_static_remove_trailing_slash(router): +def test_static_remove_trailing_slash(router) -> None: route = router.add_static('/prefix/', os.path.dirname(aiohttp.__file__)) assert '/prefix' == route._prefix -async def test_add_route_with_re(router): +async def test_add_route_with_re(router) -> None: handler = make_handler() router.add_route('GET', r'/handler/{to:\d+}', handler) - req = make_request('GET', '/handler/1234') + req = make_mocked_request('GET', '/handler/1234') info = await router.resolve(req) assert info is not None assert {'to': '1234'} == info router.add_route('GET', r'/handler/{name}.html', handler) - req = make_request('GET', '/handler/test.html') + req = make_mocked_request('GET', '/handler/test.html') info = await router.resolve(req) assert {'name': 'test'} == info -async def test_add_route_with_re_and_slashes(router): +async def test_add_route_with_re_and_slashes(router) -> None: handler = make_handler() router.add_route('GET', r'/handler/{to:[^/]+/?}', handler) - req = make_request('GET', '/handler/1234/') + req = make_mocked_request('GET', '/handler/1234/') info = await router.resolve(req) assert info is not None assert {'to': '1234/'} == info router.add_route('GET', r'/handler/{to:.+}', handler) - req = make_request('GET', '/handler/1234/5/6/7') + req = make_mocked_request('GET', '/handler/1234/5/6/7') info = await router.resolve(req) assert info is not None assert {'to': '1234/5/6/7'} == info -async def test_add_route_with_re_not_match(router): +async def test_add_route_with_re_not_match(router) -> None: handler = make_handler() router.add_route('GET', r'/handler/{to:\d+}', handler) - req = make_request('GET', '/handler/tail') + req = make_mocked_request('GET', '/handler/tail') match_info = await router.resolve(req) assert isinstance(match_info.route, SystemRoute) assert {} == match_info @@ -560,16 +557,16 @@ await match_info.handler(req) -async def test_add_route_with_re_including_slashes(router): +async def test_add_route_with_re_including_slashes(router) -> None: handler = make_handler() router.add_route('GET', r'/handler/{to:.+}/tail', handler) - req = make_request('GET', '/handler/re/with/slashes/tail') + req = make_mocked_request('GET', '/handler/re/with/slashes/tail') info = await router.resolve(req) assert info is not None assert {'to': 're/with/slashes'} == info -def test_add_route_with_invalid_re(router): +def test_add_route_with_invalid_re(router) -> None: handler = make_handler() with pytest.raises(ValueError) as ctx: router.add_route('GET', r'/handler/{to:+++}', handler) @@ -582,25 +579,25 @@ assert ctx.value.__cause__ is None -def test_route_dynamic_with_regex_spec(router): +def test_route_dynamic_with_regex_spec(router) -> None: handler = make_handler() - route = router.add_route('GET', '/get/{num:^\d+}', handler, + route = router.add_route('GET', r'/get/{num:^\d+}', handler, name='name') url = route.url_for(num='123') assert '/get/123' == str(url) -def test_route_dynamic_with_regex_spec_and_trailing_slash(router): +def test_route_dynamic_with_regex_spec_and_trailing_slash(router) -> None: handler = make_handler() - route = router.add_route('GET', '/get/{num:^\d+}/', handler, + route = router.add_route('GET', r'/get/{num:^\d+}/', handler, name='name') url = route.url_for(num='123') assert '/get/123/' == str(url) -def test_route_dynamic_with_regex(router): +def test_route_dynamic_with_regex(router) -> None: handler = make_handler() route = router.add_route('GET', r'/{one}/{two:.+}', handler) @@ -608,7 +605,7 @@ assert '/1/2' == str(url) -def test_route_dynamic_quoting(router): +def test_route_dynamic_quoting(router) -> None: handler = make_handler() route = router.add_route('GET', r'/{arg}', handler) @@ -616,50 +613,50 @@ assert '/1%202/%D1%82%D0%B5%D0%BA%D1%81%D1%82' == str(url) -async def test_regular_match_info(router): +async def test_regular_match_info(router) -> None: handler = make_handler() router.add_route('GET', '/get/{name}', handler) - req = make_request('GET', '/get/john') + req = make_mocked_request('GET', '/get/john') match_info = await router.resolve(req) assert {'name': 'john'} == match_info assert re.match(">", repr(match_info)) -async def test_match_info_with_plus(router): +async def test_match_info_with_plus(router) -> None: handler = make_handler() router.add_route('GET', '/get/{version}', handler) - req = make_request('GET', '/get/1.0+test') + req = make_mocked_request('GET', '/get/1.0+test') match_info = await router.resolve(req) assert {'version': '1.0+test'} == match_info -async def test_not_found_repr(router): - req = make_request('POST', '/path/to') +async def test_not_found_repr(router) -> None: + req = make_mocked_request('POST', '/path/to') match_info = await router.resolve(req) assert "" == repr(match_info) -async def test_not_allowed_repr(router): +async def test_not_allowed_repr(router) -> None: handler = make_handler() router.add_route('GET', '/path/to', handler) handler2 = make_handler() router.add_route('POST', '/path/to', handler2) - req = make_request('PUT', '/path/to') + req = make_mocked_request('PUT', '/path/to') match_info = await router.resolve(req) assert "" == repr(match_info) -def test_default_expect_handler(router): +def test_default_expect_handler(router) -> None: route = router.add_route('GET', '/', make_handler()) assert route._expect_handler is _default_expect_handler -def test_custom_expect_handler_plain(router): +def test_custom_expect_handler_plain(router) -> None: async def handler(request): pass @@ -670,7 +667,7 @@ assert isinstance(route, ResourceRoute) -def test_custom_expect_handler_dynamic(router): +def test_custom_expect_handler_dynamic(router) -> None: async def handler(request): pass @@ -681,7 +678,7 @@ assert isinstance(route, ResourceRoute) -def test_expect_handler_non_coroutine(router): +def test_expect_handler_non_coroutine(router) -> None: def handler(request): pass @@ -691,37 +688,37 @@ expect_handler=handler) -async def test_dynamic_match_non_ascii(router): +async def test_dynamic_match_non_ascii(router) -> None: handler = make_handler() router.add_route('GET', '/{var}', handler) - req = make_request( + req = make_mocked_request( 'GET', '/%D1%80%D1%83%D1%81%20%D1%82%D0%B5%D0%BA%D1%81%D1%82') match_info = await router.resolve(req) assert {'var': 'рус текст'} == match_info -async def test_dynamic_match_with_static_part(router): +async def test_dynamic_match_with_static_part(router) -> None: handler = make_handler() router.add_route('GET', '/{name}.html', handler) - req = make_request('GET', '/file.html') + req = make_mocked_request('GET', '/file.html') match_info = await router.resolve(req) assert {'name': 'file'} == match_info -async def test_dynamic_match_two_part2(router): +async def test_dynamic_match_two_part2(router) -> None: handler = make_handler() router.add_route('GET', '/{name}.{ext}', handler) - req = make_request('GET', '/file.html') + req = make_mocked_request('GET', '/file.html') match_info = await router.resolve(req) assert {'name': 'file', 'ext': 'html'} == match_info -async def test_dynamic_match_unquoted_path(router): +async def test_dynamic_match_unquoted_path(router) -> None: handler = make_handler() router.add_route('GET', '/{path}/{subpath}', handler) resource_id = 'my%2Fpath%7Cwith%21some%25strange%24characters' - req = make_request('GET', '/path/{0}'.format(resource_id)) + req = make_mocked_request('GET', '/path/{0}'.format(resource_id)) match_info = await router.resolve(req) assert match_info == { 'path': 'path', @@ -729,13 +726,13 @@ } -def test_add_route_not_started_with_slash(router): +def test_add_route_not_started_with_slash(router) -> None: with pytest.raises(ValueError): handler = make_handler() router.add_route('GET', 'invalid_path', handler) -def test_add_route_invalid_method(router): +def test_add_route_invalid_method(router) -> None: sample_bad_methods = { 'BAD METHOD', @@ -752,34 +749,34 @@ router.add_route(bad_method, '/path', handler) -def test_routes_view_len(router, fill_routes): +def test_routes_view_len(router, fill_routes) -> None: fill_routes() assert 4 == len(router.routes()) -def test_routes_view_iter(router, fill_routes): +def test_routes_view_iter(router, fill_routes) -> None: routes = fill_routes() assert list(routes) == list(router.routes()) -def test_routes_view_contains(router, fill_routes): +def test_routes_view_contains(router, fill_routes) -> None: routes = fill_routes() for route in routes: assert route in router.routes() -def test_routes_abc(router): +def test_routes_abc(router) -> None: assert isinstance(router.routes(), Sized) assert isinstance(router.routes(), Iterable) assert isinstance(router.routes(), Container) -def test_named_resources_abc(router): +def test_named_resources_abc(router) -> None: assert isinstance(router.named_resources(), Mapping) assert not isinstance(router.named_resources(), MutableMapping) -def test_named_resources(router): +def test_named_resources(router) -> None: route1 = router.add_route('GET', '/plain', make_handler(), name='route1') route2 = router.add_route('GET', '/variable/{name}', @@ -797,7 +794,7 @@ AbstractResource) -def test_resource_iter(router): +def test_resource_iter(router) -> None: async def handler(request): pass resource = router.add_resource('/path') @@ -807,7 +804,7 @@ assert [r1, r2] == list(resource) -def test_deprecate_bare_generators(router): +def test_deprecate_bare_generators(router) -> None: resource = router.add_resource('/path') def gen(request): @@ -817,14 +814,14 @@ resource.add_route('GET', gen) -def test_view_route(router): +def test_view_route(router) -> None: resource = router.add_resource('/path') route = resource.add_route('GET', View) assert View is route.handler -def test_resource_route_match(router): +def test_resource_route_match(router) -> None: async def handler(request): pass resource = router.add_resource('/path') @@ -832,7 +829,7 @@ assert {} == route.resource._match('/path') -def test_error_on_double_route_adding(router): +def test_error_on_double_route_adding(router) -> None: async def handler(request): pass resource = router.add_resource('/path') @@ -842,7 +839,7 @@ resource.add_route('GET', handler) -def test_error_on_adding_route_after_wildcard(router): +def test_error_on_adding_route_after_wildcard(router) -> None: async def handler(request): pass resource = router.add_resource('/path') @@ -852,44 +849,44 @@ resource.add_route('GET', handler) -async def test_http_exception_is_none_when_resolved(router): +async def test_http_exception_is_none_when_resolved(router) -> None: handler = make_handler() router.add_route('GET', '/', handler) - req = make_request('GET', '/') + req = make_mocked_request('GET', '/') info = await router.resolve(req) assert info.http_exception is None -async def test_http_exception_is_not_none_when_not_resolved(router): +async def test_http_exception_is_not_none_when_not_resolved(router) -> None: handler = make_handler() router.add_route('GET', '/', handler) - req = make_request('GET', '/abc') + req = make_mocked_request('GET', '/abc') info = await router.resolve(req) assert info.http_exception.status == 404 -async def test_match_info_get_info_plain(router): +async def test_match_info_get_info_plain(router) -> None: handler = make_handler() router.add_route('GET', '/', handler) - req = make_request('GET', '/') + req = make_mocked_request('GET', '/') info = await router.resolve(req) assert info.get_info() == {'path': '/'} -async def test_match_info_get_info_dynamic(router): +async def test_match_info_get_info_dynamic(router) -> None: handler = make_handler() router.add_route('GET', '/{a}', handler) - req = make_request('GET', '/value') + req = make_mocked_request('GET', '/value') info = await router.resolve(req) assert info.get_info() == { 'pattern': re.compile(PATH_SEP+'(?P[^{}/]+)'), 'formatter': '/{a}'} -async def test_match_info_get_info_dynamic2(router): +async def test_match_info_get_info_dynamic2(router) -> None: handler = make_handler() router.add_route('GET', '/{a}/{b}', handler) - req = make_request('GET', '/path/to') + req = make_mocked_request('GET', '/path/to') info = await router.resolve(req) assert info.get_info() == { 'pattern': re.compile(PATH_SEP + @@ -899,35 +896,35 @@ 'formatter': '/{a}/{b}'} -def test_static_resource_get_info(router): +def test_static_resource_get_info(router) -> None: directory = pathlib.Path(aiohttp.__file__).parent resource = router.add_static('/st', directory) assert resource.get_info() == {'directory': directory, 'prefix': '/st'} -async def test_system_route_get_info(router): +async def test_system_route_get_info(router) -> None: handler = make_handler() router.add_route('GET', '/', handler) - req = make_request('GET', '/abc') + req = make_mocked_request('GET', '/abc') info = await router.resolve(req) assert info.get_info()['http_exception'].status == 404 -def test_resources_view_len(router): +def test_resources_view_len(router) -> None: router.add_resource('/plain') router.add_resource('/variable/{name}') assert 2 == len(router.resources()) -def test_resources_view_iter(router): +def test_resources_view_iter(router) -> None: resource1 = router.add_resource('/plain') resource2 = router.add_resource('/variable/{name}') resources = [resource1, resource2] assert list(resources) == list(router.resources()) -def test_resources_view_contains(router): +def test_resources_view_contains(router) -> None: resource1 = router.add_resource('/plain') resource2 = router.add_resource('/variable/{name}') resources = [resource1, resource2] @@ -935,13 +932,13 @@ assert resource in router.resources() -def test_resources_abc(router): +def test_resources_abc(router) -> None: assert isinstance(router.resources(), Sized) assert isinstance(router.resources(), Iterable) assert isinstance(router.resources(), Container) -def test_static_route_user_home(router): +def test_static_route_user_home(router) -> None: here = pathlib.Path(aiohttp.__file__).parent home = pathlib.Path(os.path.expanduser('~')) if not str(here).startswith(str(home)): # pragma: no cover @@ -951,13 +948,13 @@ assert here == route.get_info()['directory'] -def test_static_route_points_to_file(router): +def test_static_route_points_to_file(router) -> None: here = pathlib.Path(aiohttp.__file__).parent / '__init__.py' with pytest.raises(ValueError): router.add_static('/st', here) -async def test_404_for_static_resource(router): +async def test_404_for_static_resource(router) -> None: resource = router.add_static('/st', os.path.dirname(aiohttp.__file__)) ret = await resource.resolve( @@ -965,7 +962,7 @@ assert (None, set()) == ret -async def test_405_for_resource_adapter(router): +async def test_405_for_resource_adapter(router) -> None: resource = router.add_static('/st', os.path.dirname(aiohttp.__file__)) ret = await resource.resolve( @@ -973,7 +970,7 @@ assert (None, {'HEAD', 'GET'}) == ret -async def test_check_allowed_method_for_found_resource(router): +async def test_check_allowed_method_for_found_resource(router) -> None: handler = make_handler() resource = router.add_resource('/') resource.add_route('GET', handler) @@ -982,46 +979,142 @@ assert {'GET'} == ret[1] -def test_url_for_in_static_resource(router): +def test_url_for_in_static_resource(router) -> None: resource = router.add_static('/static', os.path.dirname(aiohttp.__file__)) assert URL('/static/file.txt') == resource.url_for(filename='file.txt') -def test_url_for_in_static_resource_pathlib(router): +def test_url_for_in_static_resource_pathlib(router) -> None: resource = router.add_static('/static', os.path.dirname(aiohttp.__file__)) assert URL('/static/file.txt') == resource.url_for( filename=pathlib.Path('file.txt')) -def test_url_for_in_resource_route(router): +def test_url_for_in_resource_route(router) -> None: route = router.add_route('GET', '/get/{name}', make_handler(), name='name') assert URL('/get/John') == route.url_for(name='John') -def test_subapp_get_info(app, loop): +def test_subapp_get_info(app) -> None: subapp = web.Application() resource = subapp.add_subapp('/pre', subapp) assert resource.get_info() == {'prefix': '/pre', 'app': subapp} -def test_subapp_url_for(app, loop): +@pytest.mark.parametrize('domain,error', [ + (None, TypeError), + ('', ValueError), + ('http://dom', ValueError), + ('*.example.com', ValueError), + ('example$com', ValueError), +]) +def test_domain_validation_error(domain, error): + with pytest.raises(error): + Domain(domain) + + +def test_domain_valid(): + assert Domain('example.com:81').canonical == 'example.com:81' + assert MaskDomain('*.example.com').canonical == r'.*\.example\.com' + assert Domain('пуни.код').canonical == 'xn--h1ajfq.xn--d1alm' + + +@pytest.mark.parametrize('a,b,result', [ + ('example.com', 'example.com', True), + ('example.com:81', 'example.com:81', True), + ('example.com:81', 'example.com', False), + ('пуникод', 'xn--d1ahgkhc2a', True), + ('*.example.com', 'jpg.example.com', True), + ('*.example.com', 'a.example.com', True), + ('*.example.com', 'example.com', False), +]) +def test_match_domain(a, b, result): + if '*' in a: + rule = MaskDomain(a) + else: + rule = Domain(a) + assert rule.match_domain(b) is result + + +def test_add_subapp_errors(app): + with pytest.raises(TypeError): + app.add_subapp(1, web.Application()) + + +def test_subapp_rule_resource(app): + subapp = web.Application() + subapp.router.add_get('/', make_handler()) + rule = Domain('example.com') + assert rule.get_info() == {'domain': 'example.com'} + resource = app.add_domain('example.com', subapp) + assert resource.canonical == 'example.com' + assert resource.get_info() == {'rule': resource._rule, 'app': subapp} + resource.add_prefix('/a') + resource.raw_match('/b') + assert len(resource) + assert list(resource) + assert repr(resource).startswith(' None: subapp = web.Application() resource = app.add_subapp('/pre', subapp) with pytest.raises(RuntimeError): resource.url_for() -def test_subapp_repr(app, loop): +def test_subapp_repr(app) -> None: subapp = web.Application() resource = app.add_subapp('/pre', subapp) assert repr(resource).startswith( ' None: subapp = web.Application() subapp.router.add_get('/', make_handler(), allow_head=False) subapp.router.add_post('/', make_handler()) @@ -1029,7 +1122,7 @@ assert len(resource) == 2 -def test_subapp_iter(app, loop): +def test_subapp_iter(app) -> None: subapp = web.Application() r1 = subapp.router.add_get('/', make_handler(), allow_head=False) r2 = subapp.router.add_post('/', make_handler()) @@ -1037,32 +1130,32 @@ assert list(resource) == [r1, r2] -def test_invalid_route_name(router): +def test_invalid_route_name(router) -> None: with pytest.raises(ValueError): router.add_get('/', make_handler(), name='invalid name') -def test_frozen_router(router): +def test_frozen_router(router) -> None: router.freeze() with pytest.raises(RuntimeError): router.add_get('/', make_handler()) -def test_frozen_router_subapp(app, loop): +def test_frozen_router_subapp(app) -> None: subapp = web.Application() subapp.freeze() with pytest.raises(RuntimeError): - app.add_subapp('/', subapp) + app.add_subapp('/pre', subapp) -def test_frozen_app_on_subapp(app, loop): +def test_frozen_app_on_subapp(app) -> None: app.freeze() subapp = web.Application() with pytest.raises(RuntimeError): - app.add_subapp('/', subapp) + app.add_subapp('/pre', subapp) -def test_set_options_route(router): +def test_set_options_route(router) -> None: resource = router.add_static('/static', os.path.dirname(aiohttp.__file__)) options = None @@ -1080,24 +1173,24 @@ resource.set_options_route(make_handler()) -def test_dynamic_url_with_name_started_from_undescore(router): +def test_dynamic_url_with_name_started_from_underscore(router) -> None: route = router.add_route('GET', '/get/{_name}', make_handler()) assert URL('/get/John') == route.url_for(_name='John') -def test_cannot_add_subapp_with_empty_prefix(app, loop): +def test_cannot_add_subapp_with_empty_prefix(app) -> None: subapp = web.Application() with pytest.raises(ValueError): app.add_subapp('', subapp) -def test_cannot_add_subapp_with_slash_prefix(app, loop): +def test_cannot_add_subapp_with_slash_prefix(app) -> None: subapp = web.Application() with pytest.raises(ValueError): app.add_subapp('/', subapp) -async def test_convert_empty_path_to_slash_on_freezing(router): +async def test_convert_empty_path_to_slash_on_freezing(router) -> None: handler = make_handler() route = router.add_get('', handler) resource = route.resource @@ -1106,9 +1199,42 @@ assert resource.get_info() == {'path': '/'} -def test_deprecate_non_coroutine(router): +def test_deprecate_non_coroutine(router) -> None: def handler(request): pass with pytest.warns(DeprecationWarning): router.add_route('GET', '/handler', handler) + + +def test_plain_resource_canonical() -> None: + canonical = '/plain/path' + res = PlainResource(path=canonical) + assert res.canonical == canonical + + +def test_dynamic_resource_canonical() -> None: + canonicals = { + '/get/{name}': '/get/{name}', + r'/get/{num:^\d+}': '/get/{num}', + r'/handler/{to:\d+}': r'/handler/{to}', + r'/{one}/{two:.+}': r'/{one}/{two}', + } + for pattern, canonical in canonicals.items(): + res = DynamicResource(path=pattern) + assert res.canonical == canonical + + +def test_static_resource_canonical() -> None: + prefix = '/prefix' + directory = str(os.path.dirname(aiohttp.__file__)) + canonical = prefix + res = StaticResource(prefix=prefix, directory=directory) + assert res.canonical == canonical + + +def test_prefixed_subapp_resource_canonical(app) -> None: + canonical = '/prefix' + subapp = web.Application() + res = subapp.add_subapp(canonical, subapp) + assert res.canonical == canonical diff -Nru python-aiohttp-3.1.3/tests/test_web_app.py python-aiohttp-3.5.1/tests/test_web_app.py --- python-aiohttp-3.1.3/tests/test_web_app.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_web_app.py 2018-12-24 20:58:54.000000000 +0000 @@ -10,77 +10,92 @@ from aiohttp.test_utils import make_mocked_coro -def test_app_ctor(loop): +async def test_app_ctor() -> None: + loop = asyncio.get_event_loop() with pytest.warns(DeprecationWarning): app = web.Application(loop=loop) - assert loop is app.loop + with pytest.warns(DeprecationWarning): + assert loop is app.loop assert app.logger is log.web_logger -def test_app_call(): +def test_app_call() -> None: app = web.Application() assert app is app() -def test_app_default_loop(): +def test_app_default_loop() -> None: app = web.Application() - assert app.loop is None + with pytest.warns(DeprecationWarning): + assert app.loop is None -def test_set_loop(loop): +async def test_set_loop() -> None: + loop = asyncio.get_event_loop() app = web.Application() app._set_loop(loop) - assert app.loop is loop + with pytest.warns(DeprecationWarning): + assert app.loop is loop -def test_set_loop_default_loop(loop): +def test_set_loop_default_loop() -> None: + loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) app = web.Application() app._set_loop(None) - assert app.loop is loop + with pytest.warns(DeprecationWarning): + assert app.loop is loop + asyncio.set_event_loop(None) -def test_set_loop_with_different_loops(loop): +def test_set_loop_with_different_loops() -> None: + loop = asyncio.new_event_loop() app = web.Application() app._set_loop(loop) - assert app.loop is loop + with pytest.warns(DeprecationWarning): + assert app.loop is loop with pytest.raises(RuntimeError): app._set_loop(loop=object()) @pytest.mark.parametrize('debug', [True, False]) -def test_app_make_handler_debug_exc(loop, mocker, debug): - app = web.Application(debug=debug) +async def test_app_make_handler_debug_exc(mocker, debug) -> None: + with pytest.warns(DeprecationWarning): + app = web.Application(debug=debug) srv = mocker.patch('aiohttp.web_app.Server') - app.make_handler(loop=loop) + with pytest.warns(DeprecationWarning): + assert app.debug == debug + + app._make_handler() srv.assert_called_with(app._handle, request_factory=app._make_request, access_log_class=mock.ANY, - loop=loop, + loop=asyncio.get_event_loop(), debug=debug) -def test_app_make_handler_args(loop, mocker): +async def test_app_make_handler_args(mocker) -> None: app = web.Application(handler_args={'test': True}) srv = mocker.patch('aiohttp.web_app.Server') - app.make_handler(loop=loop) + app._make_handler() srv.assert_called_with(app._handle, request_factory=app._make_request, access_log_class=mock.ANY, - loop=loop, debug=mock.ANY, test=True) + loop=asyncio.get_event_loop(), + debug=mock.ANY, test=True) -def test_app_make_handler_access_log_class(loop, mocker): +async def test_app_make_handler_access_log_class(mocker) -> None: class Logger: pass app = web.Application() with pytest.raises(TypeError): - app.make_handler(access_log_class=Logger, loop=loop) + app._make_handler(access_log_class=Logger) class Logger(AbstractAccessLogger): @@ -89,14 +104,30 @@ srv = mocker.patch('aiohttp.web_app.Server') - app.make_handler(access_log_class=Logger, loop=loop) + app._make_handler(access_log_class=Logger) + srv.assert_called_with(app._handle, + access_log_class=Logger, + request_factory=app._make_request, + loop=asyncio.get_event_loop(), + debug=mock.ANY) + + app = web.Application(handler_args={'access_log_class': Logger}) + app._make_handler(access_log_class=Logger) srv.assert_called_with(app._handle, access_log_class=Logger, request_factory=app._make_request, - loop=loop, debug=mock.ANY) + loop=asyncio.get_event_loop(), + debug=mock.ANY) -async def test_app_register_on_finish(): +async def test_app_make_handler_raises_deprecation_warning() -> None: + app = web.Application() + + with pytest.warns(DeprecationWarning): + app.make_handler() + + +async def test_app_register_on_finish() -> None: app = web.Application() cb1 = make_mocked_coro(None) cb2 = make_mocked_coro(None) @@ -108,12 +139,12 @@ cb2.assert_called_once_with(app) -async def test_app_register_coro(loop): +async def test_app_register_coro() -> None: app = web.Application() - fut = loop.create_future() + fut = asyncio.get_event_loop().create_future() async def cb(app): - await asyncio.sleep(0.001, loop=loop) + await asyncio.sleep(0.001) fut.set_result(123) app.on_cleanup.append(cb) @@ -123,20 +154,21 @@ assert 123 == fut.result() -def test_non_default_router(): +def test_non_default_router() -> None: router = mock.Mock(spec=AbstractRouter) - app = web.Application(router=router) + with pytest.warns(DeprecationWarning): + app = web.Application(router=router) assert router is app.router -def test_logging(): +def test_logging() -> None: logger = mock.Mock() app = web.Application() app.logger = logger assert app.logger is logger -async def test_on_shutdown(): +async def test_on_shutdown() -> None: app = web.Application() called = False @@ -151,9 +183,8 @@ assert called -async def test_on_startup(loop): +async def test_on_startup() -> None: app = web.Application() - app._set_loop(loop) long_running1_called = False long_running2_called = False @@ -174,8 +205,7 @@ assert app is app_param all_long_running_called = True return await asyncio.gather(long_running1(app_param), - long_running2(app_param), - loop=app_param.loop) + long_running2(app_param)) app.on_startup.append(on_startup_all_long_running) app.freeze() @@ -186,7 +216,7 @@ assert all_long_running_called -def test_app_delitem(): +def test_app_delitem() -> None: app = web.Application() app['key'] = 'value' assert len(app) == 1 @@ -194,7 +224,7 @@ assert len(app) == 0 -def test_app_freeze(): +def test_app_freeze() -> None: app = web.Application() subapp = mock.Mock() subapp._middlewares = () @@ -207,7 +237,7 @@ assert len(subapp.freeze.call_args_list) == 1 -def test_equality(): +def test_equality() -> None: app1 = web.Application() app2 = web.Application() @@ -215,7 +245,7 @@ assert app1 != app2 -def test_app_run_middlewares(): +def test_app_run_middlewares() -> None: root = web.Application() sub = web.Application() @@ -240,17 +270,18 @@ assert root._run_middlewares is True -def test_subapp_frozen_after_adding(): +def test_subapp_pre_frozen_after_adding() -> None: app = web.Application() subapp = web.Application() app.add_subapp('/prefix', subapp) - assert subapp.frozen + assert subapp.pre_frozen + assert not subapp.frozen @pytest.mark.skipif(not PY_36, reason="Python 3.6+ required") -def test_app_inheritance(): +def test_app_inheritance() -> None: with pytest.warns(DeprecationWarning): class A(web.Application): pass @@ -258,13 +289,13 @@ @pytest.mark.skipif(not DEBUG, reason="The check is applied in DEBUG mode only") -def test_app_custom_attr(): +def test_app_custom_attr() -> None: app = web.Application() with pytest.warns(DeprecationWarning): app.custom = None -async def test_cleanup_ctx(): +async def test_cleanup_ctx() -> None: app = web.Application() out = [] @@ -285,7 +316,7 @@ assert out == ['pre_1', 'pre_2', 'post_2', 'post_1'] -async def test_cleanup_ctx_exception_on_startup(): +async def test_cleanup_ctx_exception_on_startup() -> None: app = web.Application() out = [] @@ -313,7 +344,7 @@ assert out == ['pre_1', 'pre_2', 'post_1'] -async def test_cleanup_ctx_exception_on_cleanup(): +async def test_cleanup_ctx_exception_on_cleanup() -> None: app = web.Application() out = [] @@ -341,7 +372,7 @@ assert out == ['pre_1', 'pre_2', 'pre_3', 'post_3', 'post_2', 'post_1'] -async def test_cleanup_ctx_exception_on_cleanup_multiple(): +async def test_cleanup_ctx_exception_on_cleanup_multiple() -> None: app = web.Application() out = [] @@ -370,7 +401,7 @@ assert out == ['pre_1', 'pre_2', 'pre_3', 'post_3', 'post_2', 'post_1'] -async def test_cleanup_ctx_multiple_yields(): +async def test_cleanup_ctx_multiple_yields() -> None: app = web.Application() out = [] @@ -391,3 +422,141 @@ await app.cleanup() assert "has more than one 'yield'" in str(ctx.value) assert out == ['pre_1', 'post_1'] + + +async def test_subapp_chained_config_dict_visibility(aiohttp_client) -> None: + + async def main_handler(request): + assert request.config_dict['key1'] == 'val1' + assert 'key2' not in request.config_dict + return web.Response(status=200) + + root = web.Application() + root['key1'] = 'val1' + root.add_routes([web.get('/', main_handler)]) + + async def sub_handler(request): + assert request.config_dict['key1'] == 'val1' + assert request.config_dict['key2'] == 'val2' + return web.Response(status=201) + + sub = web.Application() + sub['key2'] = 'val2' + sub.add_routes([web.get('/', sub_handler)]) + root.add_subapp('/sub', sub) + + client = await aiohttp_client(root) + + resp = await client.get('/') + assert resp.status == 200 + resp = await client.get('/sub/') + assert resp.status == 201 + + +async def test_subapp_chained_config_dict_overriding(aiohttp_client) -> None: + + async def main_handler(request): + assert request.config_dict['key'] == 'val1' + return web.Response(status=200) + + root = web.Application() + root['key'] = 'val1' + root.add_routes([web.get('/', main_handler)]) + + async def sub_handler(request): + assert request.config_dict['key'] == 'val2' + return web.Response(status=201) + + sub = web.Application() + sub['key'] = 'val2' + sub.add_routes([web.get('/', sub_handler)]) + root.add_subapp('/sub', sub) + + client = await aiohttp_client(root) + + resp = await client.get('/') + assert resp.status == 200 + resp = await client.get('/sub/') + assert resp.status == 201 + + +async def test_subapp_on_startup(aiohttp_client) -> None: + + subapp = web.Application() + + startup_called = False + + async def on_startup(app): + nonlocal startup_called + startup_called = True + app['startup'] = True + + subapp.on_startup.append(on_startup) + + ctx_pre_called = False + ctx_post_called = False + + @async_generator + async def cleanup_ctx(app): + nonlocal ctx_pre_called, ctx_post_called + ctx_pre_called = True + app['cleanup'] = True + await yield_(None) + ctx_post_called = True + + subapp.cleanup_ctx.append(cleanup_ctx) + + shutdown_called = False + + async def on_shutdown(app): + nonlocal shutdown_called + shutdown_called = True + + subapp.on_shutdown.append(on_shutdown) + + cleanup_called = False + + async def on_cleanup(app): + nonlocal cleanup_called + cleanup_called = True + + subapp.on_cleanup.append(on_cleanup) + + app = web.Application() + + app.add_subapp('/subapp', subapp) + + assert not startup_called + assert not ctx_pre_called + assert not ctx_post_called + assert not shutdown_called + assert not cleanup_called + + assert subapp.on_startup.frozen + assert subapp.cleanup_ctx.frozen + assert subapp.on_shutdown.frozen + assert subapp.on_cleanup.frozen + assert subapp.router.frozen + + client = await aiohttp_client(app) + + assert startup_called + assert ctx_pre_called + assert not ctx_post_called + assert not shutdown_called + assert not cleanup_called + + await client.close() + + assert startup_called + assert ctx_pre_called + assert ctx_post_called + assert shutdown_called + assert cleanup_called + + +def test_app_iter(): + app = web.Application() + app['a'] = '1' + app['b'] = '2' + assert sorted(list(app)) == ['a', 'b'] diff -Nru python-aiohttp-3.1.3/tests/test_web_cli.py python-aiohttp-3.5.1/tests/test_web_cli.py --- python-aiohttp-3.1.3/tests/test_web_cli.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_web_cli.py 2018-12-24 20:58:54.000000000 +0000 @@ -3,7 +3,7 @@ from aiohttp import web -def test_entry_func_empty(mocker): +def test_entry_func_empty(mocker) -> None: error = mocker.patch("aiohttp.web.ArgumentParser.error", side_effect=SystemExit) argv = [""] @@ -16,7 +16,7 @@ ) -def test_entry_func_only_module(mocker): +def test_entry_func_only_module(mocker) -> None: argv = ["test"] error = mocker.patch("aiohttp.web.ArgumentParser.error", side_effect=SystemExit) @@ -29,7 +29,7 @@ ) -def test_entry_func_only_function(mocker): +def test_entry_func_only_function(mocker) -> None: argv = [":test"] error = mocker.patch("aiohttp.web.ArgumentParser.error", side_effect=SystemExit) @@ -42,7 +42,7 @@ ) -def test_entry_func_only_seperator(mocker): +def test_entry_func_only_separator(mocker) -> None: argv = [":"] error = mocker.patch("aiohttp.web.ArgumentParser.error", side_effect=SystemExit) @@ -55,7 +55,7 @@ ) -def test_entry_func_relative_module(mocker): +def test_entry_func_relative_module(mocker) -> None: argv = [".a.b:c"] error = mocker.patch("aiohttp.web.ArgumentParser.error", @@ -66,7 +66,7 @@ error.assert_called_with("relative module names not supported") -def test_entry_func_non_existent_module(mocker): +def test_entry_func_non_existent_module(mocker) -> None: argv = ["alpha.beta:func"] mocker.patch("aiohttp.web.import_module", @@ -80,7 +80,7 @@ error.assert_called_with('unable to import alpha.beta: Test Error') -def test_entry_func_non_existent_attribute(mocker): +def test_entry_func_non_existent_attribute(mocker) -> None: argv = ["alpha.beta:func"] import_module = mocker.patch("aiohttp.web.import_module") error = mocker.patch("aiohttp.web.ArgumentParser.error", @@ -96,7 +96,7 @@ ) -def test_path_when_unsupported(mocker, monkeypatch): +def test_path_when_unsupported(mocker, monkeypatch) -> None: argv = "--path=test_path.sock alpha.beta:func".split() mocker.patch("aiohttp.web.import_module") monkeypatch.delattr("socket.AF_UNIX", raising=False) @@ -110,7 +110,7 @@ " operating environment") -def test_entry_func_call(mocker): +def test_entry_func_call(mocker) -> None: mocker.patch("aiohttp.web.run_app") import_module = mocker.patch("aiohttp.web.import_module") argv = ("-H testhost -P 6666 --extra-optional-eins alpha.beta:func " @@ -126,7 +126,7 @@ ) -def test_running_application(mocker): +def test_running_application(mocker) -> None: run_app = mocker.patch("aiohttp.web.run_app") import_module = mocker.patch("aiohttp.web.import_module") exit = mocker.patch("aiohttp.web.ArgumentParser.exit", diff -Nru python-aiohttp-3.1.3/tests/test_web_exceptions.py python-aiohttp-3.5.1/tests/test_web_exceptions.py --- python-aiohttp-3.1.3/tests/test_web_exceptions.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_web_exceptions.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,5 +1,6 @@ import collections import re +from traceback import format_exception from unittest import mock import pytest @@ -14,7 +15,7 @@ @pytest.fixture -def request(buf): +def http_request(buf): method = 'GET' path = '/' writer = mock.Mock() @@ -25,7 +26,7 @@ return helpers.noop() async def write_headers(status_line, headers): - headers = status_line + ''.join( + headers = status_line + '\r\n' + ''.join( [k + ': ' + v + '\r\n' for k, v in headers.items()]) headers = headers.encode('utf-8') + b'\r\n' buf.extend(headers) @@ -43,7 +44,7 @@ return req -def test_all_http_exceptions_exported(): +def test_all_http_exceptions_exported() -> None: assert 'HTTPException' in web.__all__ for name in dir(web): if name.startswith('_'): @@ -53,9 +54,9 @@ assert name in web.__all__ -async def test_HTTPOk(buf, request): +async def test_HTTPOk(buf, http_request) -> None: resp = web.HTTPOk() - await resp.prepare(request) + await resp.prepare(http_request) await resp.write_eof() txt = buf.decode('utf8') assert re.match(('HTTP/1.1 200 OK\r\n' @@ -66,7 +67,7 @@ '200: OK'), txt) -def test_terminal_classes_has_status_code(): +def test_terminal_classes_has_status_code() -> None: terminals = set() for name in dir(web): obj = getattr(web, name) @@ -86,11 +87,11 @@ assert 1 == codes.most_common(1)[0][1] -async def test_HTTPFound(buf, request): +async def test_HTTPFound(buf, http_request) -> None: resp = web.HTTPFound(location='/redirect') assert '/redirect' == resp.location assert '/redirect' == resp.headers['location'] - await resp.prepare(request) + await resp.prepare(http_request) await resp.write_eof() txt = buf.decode('utf8') assert re.match('HTTP/1.1 302 Found\r\n' @@ -102,7 +103,7 @@ '302: Found', txt) -def test_HTTPFound_empty_location(): +def test_HTTPFound_empty_location() -> None: with pytest.raises(ValueError): web.HTTPFound(location='') @@ -110,12 +111,12 @@ web.HTTPFound(location=None) -async def test_HTTPMethodNotAllowed(buf, request): +async def test_HTTPMethodNotAllowed(buf, http_request) -> None: resp = web.HTTPMethodNotAllowed('get', ['POST', 'PUT']) assert 'GET' == resp.method - assert ['POST', 'PUT'] == resp.allowed_methods + assert {'POST', 'PUT'} == resp.allowed_methods assert 'POST,PUT' == resp.headers['allow'] - await resp.prepare(request) + await resp.prepare(http_request) await resp.write_eof() txt = buf.decode('utf8') assert re.match('HTTP/1.1 405 Method Not Allowed\r\n' @@ -127,7 +128,7 @@ '405: Method Not Allowed', txt) -def test_override_body_with_text(): +def test_override_body_with_text() -> None: resp = web.HTTPNotFound(text="Page not found") assert 404 == resp.status assert "Page not found".encode('utf-8') == resp.body @@ -136,10 +137,11 @@ assert "utf-8" == resp.charset -def test_override_body_with_binary(): +def test_override_body_with_binary() -> None: txt = "Page not found" - resp = web.HTTPNotFound(body=txt.encode('utf-8'), - content_type="text/html") + with pytest.warns(DeprecationWarning): + resp = web.HTTPNotFound(body=txt.encode('utf-8'), + content_type="text/html") assert 404 == resp.status assert txt.encode('utf-8') == resp.body assert txt == resp.text @@ -147,28 +149,39 @@ assert resp.charset is None -def test_default_body(): +def test_default_body() -> None: resp = web.HTTPOk() assert b'200: OK' == resp.body -def test_empty_body_204(): +def test_empty_body_204() -> None: resp = web.HTTPNoContent() assert resp.body is None -def test_empty_body_205(): +def test_empty_body_205() -> None: resp = web.HTTPNoContent() assert resp.body is None -def test_empty_body_304(): +def test_empty_body_304() -> None: resp = web.HTTPNoContent() resp.body is None -def test_link_header_451(buf, request): +def test_link_header_451(buf) -> None: resp = web.HTTPUnavailableForLegalReasons(link='http://warning.or.kr/') assert 'http://warning.or.kr/' == resp.link assert '; rel="blocked-by"' == resp.headers['Link'] + + +def test_HTTPException_retains_cause() -> None: + with pytest.raises(web.HTTPException) as ei: + try: + raise Exception('CustomException') + except Exception as exc: + raise web.HTTPException() from exc + tb = ''.join(format_exception(ei.type, ei.value, ei.tb)) + assert 'CustomException' in tb + assert 'direct cause' in tb diff -Nru python-aiohttp-3.1.3/tests/test_web_functional.py python-aiohttp-3.5.1/tests/test_web_functional.py --- python-aiohttp-3.1.3/tests/test_web_functional.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_web_functional.py 2018-12-24 20:58:54.000000000 +0000 @@ -8,7 +8,7 @@ import pytest from async_generator import async_generator, yield_ -from multidict import MultiDict +from multidict import CIMultiDictProxy, MultiDict from yarl import URL import aiohttp @@ -19,7 +19,7 @@ try: import ssl except ImportError: - ssl = False + ssl = None # type: ignore @pytest.fixture @@ -32,7 +32,7 @@ return here / 'sample.key' -async def test_simple_get(aiohttp_client): +async def test_simple_get(aiohttp_client) -> None: async def handler(request): body = await request.read() @@ -49,7 +49,7 @@ assert 'OK' == txt -async def test_simple_get_with_text(aiohttp_client): +async def test_simple_get_with_text(aiohttp_client) -> None: async def handler(request): body = await request.read() @@ -66,7 +66,9 @@ assert 'OK' == txt -async def test_handler_returns_not_response(aiohttp_server, aiohttp_client): +async def test_handler_returns_not_response(aiohttp_server, + aiohttp_client) -> None: + asyncio.get_event_loop().set_debug(True) logger = mock.Mock() async def handler(request): @@ -77,13 +79,35 @@ server = await aiohttp_server(app, logger=logger) client = await aiohttp_client(server) - resp = await client.get('/') - assert 500 == resp.status + with pytest.raises(aiohttp.ServerDisconnectedError): + await client.get('/') - assert logger.exception.called + logger.exception.assert_called_with('Unhandled runtime exception', + exc_info=mock.ANY) -async def test_head_returns_empty_body(aiohttp_client): +async def test_handler_returns_none(aiohttp_server, + aiohttp_client) -> None: + asyncio.get_event_loop().set_debug(True) + logger = mock.Mock() + + async def handler(request): + return None + + app = web.Application() + app.router.add_get('/', handler) + server = await aiohttp_server(app, logger=logger) + client = await aiohttp_client(server) + + with pytest.raises(aiohttp.ServerDisconnectedError): + await client.get('/') + + # Actual error text is placed in exc_info + logger.exception.assert_called_with('Unhandled runtime exception', + exc_info=mock.ANY) + + +async def test_head_returns_empty_body(aiohttp_client) -> None: async def handler(request): return web.Response(body=b'test') @@ -98,7 +122,7 @@ assert '' == txt -async def test_response_before_complete(aiohttp_client): +async def test_response_before_complete(aiohttp_client) -> None: async def handler(request): return web.Response(body=b'OK') @@ -115,7 +139,7 @@ assert 'OK' == text -async def test_post_form(aiohttp_client): +async def test_post_form(aiohttp_client) -> None: async def handler(request): data = await request.post() @@ -132,7 +156,7 @@ assert 'OK' == txt -async def test_post_text(aiohttp_client): +async def test_post_text(aiohttp_client) -> None: async def handler(request): data = await request.text() @@ -151,7 +175,7 @@ assert 'русский' == txt -async def test_post_json(aiohttp_client): +async def test_post_json(aiohttp_client) -> None: dct = {'key': 'текст'} @@ -176,7 +200,7 @@ assert dct == data -async def test_multipart(aiohttp_client): +async def test_multipart(aiohttp_client) -> None: with multipart.MultipartWriter() as writer: writer.append('test') writer.append_json({'passed': True}) @@ -210,7 +234,7 @@ await resp.release() -async def test_multipart_content_transfer_encoding(aiohttp_client): +async def test_multipart_content_transfer_encoding(aiohttp_client) -> None: """For issue #1168""" with multipart.MultipartWriter() as writer: writer.append(b'\x00' * 10, @@ -240,7 +264,7 @@ await resp.release() -async def test_render_redirect(aiohttp_client): +async def test_render_redirect(aiohttp_client) -> None: async def handler(request): raise web.HTTPMovedPermanently(location='/path') @@ -256,7 +280,7 @@ assert '/path' == resp.headers['location'] -async def test_post_single_file(aiohttp_client): +async def test_post_single_file(aiohttp_client) -> None: here = pathlib.Path(__file__).parent @@ -286,7 +310,7 @@ assert 200 == resp.status -async def test_files_upload_with_same_key(aiohttp_client): +async def test_files_upload_with_same_key(aiohttp_client) -> None: async def handler(request): data = await request.post() @@ -319,7 +343,7 @@ assert 200 == resp.status -async def test_post_files(aiohttp_client): +async def test_post_files(aiohttp_client) -> None: here = pathlib.Path(__file__).parent @@ -349,7 +373,7 @@ assert 200 == resp.status -async def test_release_post_data(aiohttp_client): +async def test_release_post_data(aiohttp_client) -> None: async def handler(request): await request.release() @@ -365,7 +389,8 @@ assert 200 == resp.status -async def test_POST_DATA_with_content_transfer_encoding(aiohttp_client): +async def test_POST_DATA_with_content_transfer_encoding( + aiohttp_client) -> None: async def handler(request): data = await request.post() @@ -384,7 +409,7 @@ assert 200 == resp.status -async def test_post_form_with_duplicate_keys(aiohttp_client): +async def test_post_form_with_duplicate_keys(aiohttp_client) -> None: async def handler(request): data = await request.post() @@ -400,12 +425,12 @@ assert 200 == resp.status -def test_repr_for_application(): +def test_repr_for_application() -> None: app = web.Application() assert "".format(id(app)) == repr(app) -async def test_expect_default_handler_unknown(aiohttp_client): +async def test_expect_default_handler_unknown(aiohttp_client) -> None: """Test default Expect handler for unknown Expect value. A server that does not understand or is unable to comply with any of @@ -430,7 +455,7 @@ assert 417 == resp.status -async def test_100_continue(aiohttp_client): +async def test_100_continue(aiohttp_client) -> None: async def handler(request): data = await request.post() @@ -449,7 +474,7 @@ assert 200 == resp.status -async def test_100_continue_custom(aiohttp_client): +async def test_100_continue_custom(aiohttp_client) -> None: expect_received = False @@ -477,7 +502,7 @@ assert expect_received -async def test_100_continue_custom_response(aiohttp_client): +async def test_100_continue_custom_response(aiohttp_client) -> None: async def handler(request): data = await request.post() @@ -508,7 +533,7 @@ assert 403 == resp.status -async def test_100_continue_for_not_found(aiohttp_client): +async def test_100_continue_for_not_found(aiohttp_client) -> None: app = web.Application() client = await aiohttp_client(app) @@ -517,7 +542,7 @@ assert 404 == resp.status -async def test_100_continue_for_not_allowed(aiohttp_client): +async def test_100_continue_for_not_allowed(aiohttp_client) -> None: async def handler(request): return web.Response() @@ -530,7 +555,7 @@ assert 405 == resp.status -async def test_http11_keep_alive_default(aiohttp_client): +async def test_http11_keep_alive_default(aiohttp_client) -> None: async def handler(request): return web.Response() @@ -546,7 +571,7 @@ @pytest.mark.xfail -async def test_http10_keep_alive_default(aiohttp_client): +async def test_http10_keep_alive_default(aiohttp_client) -> None: async def handler(request): return web.Response() @@ -561,7 +586,7 @@ assert resp.headers['Connection'] == 'keep-alive' -async def test_http10_keep_alive_with_headers_close(aiohttp_client): +async def test_http10_keep_alive_with_headers_close(aiohttp_client) -> None: async def handler(request): await request.read() @@ -578,7 +603,7 @@ assert 'Connection' not in resp.headers -async def test_http10_keep_alive_with_headers(aiohttp_client): +async def test_http10_keep_alive_with_headers(aiohttp_client) -> None: async def handler(request): await request.read() @@ -595,7 +620,7 @@ assert resp.headers['Connection'] == 'keep-alive' -async def test_upload_file(aiohttp_client): +async def test_upload_file(aiohttp_client) -> None: here = pathlib.Path(__file__).parent fname = here / 'aiohttp.png' @@ -616,7 +641,7 @@ assert 200 == resp.status -async def test_upload_file_object(aiohttp_client): +async def test_upload_file_object(aiohttp_client) -> None: here = pathlib.Path(__file__).parent fname = here / 'aiohttp.png' with fname.open('rb') as f: @@ -637,7 +662,7 @@ assert 200 == resp.status -async def test_empty_content_for_query_without_body(aiohttp_client): +async def test_empty_content_for_query_without_body(aiohttp_client) -> None: async def handler(request): assert not request.body_exists @@ -654,7 +679,7 @@ assert 200 == resp.status -async def test_empty_content_for_query_with_body(aiohttp_client): +async def test_empty_content_for_query_with_body(aiohttp_client) -> None: async def handler(request): assert request.body_exists @@ -672,7 +697,7 @@ assert 200 == resp.status -async def test_get_with_empty_arg(aiohttp_client): +async def test_get_with_empty_arg(aiohttp_client) -> None: async def handler(request): assert 'arg' in request.query @@ -687,7 +712,7 @@ assert 200 == resp.status -async def test_large_header(aiohttp_client): +async def test_large_header(aiohttp_client) -> None: async def handler(request): return web.Response() @@ -701,7 +726,7 @@ assert 400 == resp.status -async def test_large_header_allowed(aiohttp_client, aiohttp_server): +async def test_large_header_allowed(aiohttp_client, aiohttp_server) -> None: async def handler(request): return web.Response() @@ -716,7 +741,7 @@ assert 200 == resp.status -async def test_get_with_empty_arg_with_equal(aiohttp_client): +async def test_get_with_empty_arg_with_equal(aiohttp_client) -> None: async def handler(request): assert 'arg' in request.query @@ -731,7 +756,7 @@ assert 200 == resp.status -async def test_response_with_async_gen(aiohttp_client, fname): +async def test_response_with_async_gen(aiohttp_client, fname) -> None: with fname.open('rb') as f: data = f.read() @@ -761,7 +786,7 @@ assert resp.headers.get('Content-Length') == str(len(resp_data)) -async def test_response_with_streamer(aiohttp_client, fname): +async def test_response_with_streamer(aiohttp_client, fname) -> None: with fname.open('rb') as f: data = f.read() @@ -792,7 +817,8 @@ assert resp.headers.get('Content-Length') == str(len(resp_data)) -async def test_response_with_async_gen_no_params(aiohttp_client, fname): +async def test_response_with_async_gen_no_params(aiohttp_client, + fname) -> None: with fname.open('rb') as f: data = f.read() @@ -822,7 +848,7 @@ assert resp.headers.get('Content-Length') == str(len(resp_data)) -async def test_response_with_streamer_no_params(aiohttp_client, fname): +async def test_response_with_streamer_no_params(aiohttp_client, fname) -> None: with fname.open('rb') as f: data = f.read() @@ -853,7 +879,7 @@ assert resp.headers.get('Content-Length') == str(len(resp_data)) -async def test_response_with_file(aiohttp_client, fname): +async def test_response_with_file(aiohttp_client, fname) -> None: with fname.open('rb') as f: data = f.read() @@ -876,7 +902,7 @@ 'attachment; filename="sample.key"; filename*=utf-8\'\'sample.key') -async def test_response_with_file_ctype(aiohttp_client, fname): +async def test_response_with_file_ctype(aiohttp_client, fname) -> None: with fname.open('rb') as f: data = f.read() @@ -899,7 +925,7 @@ 'attachment; filename="sample.key"; filename*=utf-8\'\'sample.key') -async def test_response_with_payload_disp(aiohttp_client, fname): +async def test_response_with_payload_disp(aiohttp_client, fname) -> None: with fname.open('rb') as f: data = f.read() @@ -924,7 +950,7 @@ 'inline; filename="test.txt"; filename*=utf-8\'\'test.txt') -async def test_response_with_payload_stringio(aiohttp_client, fname): +async def test_response_with_payload_stringio(aiohttp_client, fname) -> None: async def handler(request): return web.Response(body=io.StringIO('test')) @@ -939,7 +965,7 @@ assert resp_data == b'test' -async def test_response_with_precompressed_body_gzip(aiohttp_client): +async def test_response_with_precompressed_body_gzip(aiohttp_client) -> None: async def handler(request): headers = {'Content-Encoding': 'gzip'} @@ -958,7 +984,8 @@ assert resp.headers.get('Content-Encoding') == 'gzip' -async def test_response_with_precompressed_body_deflate(aiohttp_client): +async def test_response_with_precompressed_body_deflate( + aiohttp_client) -> None: async def handler(request): headers = {'Content-Encoding': 'deflate'} @@ -977,7 +1004,7 @@ assert resp.headers.get('Content-Encoding') == 'deflate' -async def test_bad_request_payload(aiohttp_client): +async def test_bad_request_payload(aiohttp_client) -> None: async def handler(request): assert request.method == 'POST' @@ -996,7 +1023,7 @@ assert 200 == resp.status -async def test_stream_response_multiple_chunks(aiohttp_client): +async def test_stream_response_multiple_chunks(aiohttp_client) -> None: async def handler(request): resp = web.StreamResponse() @@ -1017,7 +1044,7 @@ assert b'xyz' == data -async def test_start_without_routes(aiohttp_client): +async def test_start_without_routes(aiohttp_client) -> None: app = web.Application() client = await aiohttp_client(app) @@ -1026,7 +1053,7 @@ assert 404 == resp.status -async def test_requests_count(aiohttp_client): +async def test_requests_count(aiohttp_client) -> None: async def handler(request): return web.Response() @@ -1049,7 +1076,7 @@ assert client.server.handler.requests_count == 3 -async def test_redirect_url(aiohttp_client): +async def test_redirect_url(aiohttp_client) -> None: async def redirector(request): raise web.HTTPFound(location=URL('/redirected')) @@ -1066,7 +1093,7 @@ assert resp.status == 200 -async def test_simple_subapp(aiohttp_client): +async def test_simple_subapp(aiohttp_client) -> None: async def handler(request): return web.Response(text="OK") @@ -1083,7 +1110,7 @@ assert 'OK' == txt -async def test_subapp_reverse_url(aiohttp_client): +async def test_subapp_reverse_url(aiohttp_client) -> None: async def handler(request): raise web.HTTPMovedPermanently( @@ -1106,7 +1133,7 @@ assert resp.url.path == '/path/final' -async def test_subapp_reverse_variable_url(aiohttp_client): +async def test_subapp_reverse_variable_url(aiohttp_client) -> None: async def handler(request): raise web.HTTPMovedPermanently( @@ -1129,7 +1156,7 @@ assert resp.url.path == '/path/final' -async def test_subapp_reverse_static_url(aiohttp_client): +async def test_subapp_reverse_static_url(aiohttp_client) -> None: fname = 'aiohttp.png' async def handler(request): @@ -1152,7 +1179,7 @@ assert body == f.read() -async def test_subapp_app(aiohttp_client): +async def test_subapp_app(aiohttp_client) -> None: async def handler(request): assert request.app is subapp @@ -1170,7 +1197,7 @@ assert 'OK' == txt -async def test_subapp_not_found(aiohttp_client): +async def test_subapp_not_found(aiohttp_client) -> None: async def handler(request): return web.Response(text='OK') @@ -1185,7 +1212,7 @@ assert resp.status == 404 -async def test_subapp_not_found2(aiohttp_client): +async def test_subapp_not_found2(aiohttp_client) -> None: async def handler(request): return web.Response(text='OK') @@ -1200,7 +1227,7 @@ assert resp.status == 404 -async def test_subapp_not_allowed(aiohttp_client): +async def test_subapp_not_allowed(aiohttp_client) -> None: async def handler(request): return web.Response(text='OK') @@ -1216,7 +1243,7 @@ assert resp.headers['Allow'] == 'GET,HEAD' -async def test_subapp_cannot_add_app_in_handler(aiohttp_client): +async def test_subapp_cannot_add_app_in_handler(aiohttp_client) -> None: async def handler(request): request.match_info.add_app(app) @@ -1232,7 +1259,7 @@ assert resp.status == 500 -async def test_subapp_middlewares(aiohttp_client): +async def test_subapp_middlewares(aiohttp_client) -> None: order = [] async def handler(request): @@ -1263,7 +1290,7 @@ (2, subapp2), (2, subapp1), (2, app)] == order -async def test_subapp_on_response_prepare(aiohttp_client): +async def test_subapp_on_response_prepare(aiohttp_client) -> None: order = [] async def handler(request): @@ -1292,7 +1319,7 @@ assert [app, subapp1, subapp2] == order -async def test_subapp_on_startup(aiohttp_server): +async def test_subapp_on_startup(aiohttp_server) -> None: order = [] async def on_signal(app): @@ -1312,7 +1339,7 @@ assert [app, subapp1, subapp2] == order -async def test_subapp_on_shutdown(aiohttp_server): +async def test_subapp_on_shutdown(aiohttp_server) -> None: order = [] async def on_signal(app): @@ -1333,7 +1360,7 @@ assert [app, subapp1, subapp2] == order -async def test_subapp_on_cleanup(aiohttp_server): +async def test_subapp_on_cleanup(aiohttp_server) -> None: order = [] async def on_signal(app): @@ -1403,7 +1430,7 @@ assert expected == values -async def test_custom_date_header(aiohttp_client): +async def test_custom_date_header(aiohttp_client) -> None: async def handler(request): return web.Response(headers={'Date': 'Sun, 30 Oct 2016 03:13:52 GMT'}) @@ -1417,7 +1444,7 @@ assert resp.headers['Date'] == 'Sun, 30 Oct 2016 03:13:52 GMT' -async def test_response_prepared_with_clone(aiohttp_client): +async def test_response_prepared_with_clone(aiohttp_client) -> None: async def handler(request): cloned = request.clone() @@ -1433,7 +1460,7 @@ assert 200 == resp.status -async def test_app_max_client_size(aiohttp_client): +async def test_app_max_client_size(aiohttp_client) -> None: async def handler(request): await request.post() @@ -1448,10 +1475,11 @@ resp = await client.post('/', data=data) assert 413 == resp.status resp_text = await resp.text() - assert 'Request Entity Too Large' in resp_text + assert 'Maximum request body size 1048576 exceeded, ' \ + 'actual body size 1048591' in resp_text -async def test_app_max_client_size_adjusted(aiohttp_client): +async def test_app_max_client_size_adjusted(aiohttp_client) -> None: async def handler(request): await request.post() @@ -1473,10 +1501,11 @@ resp = await client.post('/', data=too_large_data) assert 413 == resp.status resp_text = await resp.text() - assert 'Request Entity Too Large' in resp_text + assert 'Maximum request body size 2097152 exceeded, ' \ + 'actual body size 2097166' in resp_text -async def test_app_max_client_size_none(aiohttp_client): +async def test_app_max_client_size_none(aiohttp_client) -> None: async def handler(request): await request.post() @@ -1501,33 +1530,30 @@ assert resp_text == 'ok' -async def test_post_max_client_size(aiohttp_client): +async def test_post_max_client_size(aiohttp_client) -> None: async def handler(request): - try: - await request.post() - except ValueError: - return web.Response() - raise web.HTTPBadRequest() + await request.post() + return web.Response() app = web.Application(client_max_size=10) app.router.add_post('/', handler) client = await aiohttp_client(app) - data = {"long_string": 1024 * 'x', 'file': io.BytesIO(b'test')} + data = {'long_string': 1024 * 'x', 'file': io.BytesIO(b'test')} resp = await client.post('/', data=data) - assert 200 == resp.status + assert 413 == resp.status + resp_text = await resp.text() + assert 'Maximum request body size 10 exceeded, ' \ + 'actual body size 1024' in resp_text -async def test_post_max_client_size_for_file(aiohttp_client): +async def test_post_max_client_size_for_file(aiohttp_client) -> None: async def handler(request): - try: - await request.post() - except ValueError: - return web.Response() - raise web.HTTPBadRequest() + await request.post() + return web.Response() app = web.Application(client_max_size=2) app.router.add_post('/', handler) @@ -1536,10 +1562,10 @@ data = {'file': io.BytesIO(b'test')} resp = await client.post('/', data=data) - assert 200 == resp.status + assert 413 == resp.status -async def test_response_with_bodypart(aiohttp_client): +async def test_response_with_bodypart(aiohttp_client) -> None: async def handler(request): reader = await request.multipart() @@ -1563,7 +1589,57 @@ {'name': 'file', 'filename': 'file', 'filename*': 'file'}) -async def test_request_clone(aiohttp_client): +async def test_response_with_bodypart_named(aiohttp_client, tmpdir) -> None: + + async def handler(request): + reader = await request.multipart() + part = await reader.next() + return web.Response(body=part) + + app = web.Application(client_max_size=2) + app.router.add_post('/', handler) + client = await aiohttp_client(app) + + f = tmpdir.join('foobar.txt') + f.write_text('test', encoding='utf8') + data = {'file': open(str(f), 'rb')} + resp = await client.post('/', data=data) + + assert 200 == resp.status + body = await resp.read() + assert body == b'test' + + disp = multipart.parse_content_disposition( + resp.headers['content-disposition']) + assert disp == ( + 'attachment', + {'name': 'file', 'filename': 'foobar.txt', 'filename*': 'foobar.txt'} + ) + + +async def test_response_with_bodypart_invalid_name(aiohttp_client) -> None: + + async def handler(request): + reader = await request.multipart() + part = await reader.next() + return web.Response(body=part) + + app = web.Application(client_max_size=2) + app.router.add_post('/', handler) + client = await aiohttp_client(app) + + with aiohttp.MultipartWriter() as mpwriter: + mpwriter.append(b'test') + resp = await client.post('/', data=mpwriter) + + assert 200 == resp.status + body = await resp.read() + assert body == b'test' + + assert 'content-disposition' not in resp.headers + + +async def test_request_clone(aiohttp_client) -> None: async def handler(request): r2 = request.clone(method='POST') @@ -1579,7 +1655,7 @@ assert 200 == resp.status -async def test_await(aiohttp_server): +async def test_await(aiohttp_server) -> None: async def handler(request): resp = web.StreamResponse(headers={'content-length': str(4)}) @@ -1605,7 +1681,7 @@ assert resp.connection is None -async def test_response_context_manager(aiohttp_server): +async def test_response_context_manager(aiohttp_server) -> None: async def handler(request): return web.Response() @@ -1620,7 +1696,7 @@ assert resp.connection is None -async def test_response_context_manager_error(aiohttp_server): +async def test_response_context_manager_error(aiohttp_server) -> None: async def handler(request): return web.Response(text='some text') @@ -1657,7 +1733,8 @@ assert resp.connection is None -async def test_context_manager_close_on_release(aiohttp_server, mocker): +async def test_context_manager_close_on_release(aiohttp_server, + mocker) -> None: async def handler(request): resp = web.StreamResponse() @@ -1682,7 +1759,7 @@ assert proto.close.called -async def test_iter_any(aiohttp_server): +async def test_iter_any(aiohttp_server) -> None: data = b'0123456789' * 1024 @@ -1702,7 +1779,7 @@ assert resp.status == 200 -async def test_request_tracing(aiohttp_server): +async def test_request_tracing(aiohttp_server) -> None: on_request_start = mock.Mock(side_effect=asyncio.coroutine(mock.Mock())) on_request_end = mock.Mock(side_effect=asyncio.coroutine(mock.Mock())) @@ -1777,7 +1854,7 @@ await client.close() -async def test_return_http_exception_deprecated(aiohttp_client): +async def test_return_http_exception_deprecated(aiohttp_client) -> None: async def handler(request): return web.HTTPForbidden() @@ -1790,7 +1867,7 @@ await client.get('/') -async def test_request_path(aiohttp_client): +async def test_request_path(aiohttp_client) -> None: async def handler(request): assert request.path_qs == '/path%20to?a=1' @@ -1808,7 +1885,7 @@ assert 'OK' == txt -async def test_app_add_routes(aiohttp_client): +async def test_app_add_routes(aiohttp_client) -> None: async def handler(request): return web.Response() @@ -1819,3 +1896,31 @@ client = await aiohttp_client(app) resp = await client.get('/get') assert resp.status == 200 + + +async def test_request_headers_type(aiohttp_client) -> None: + + async def handler(request): + assert isinstance(request.headers, CIMultiDictProxy) + return web.Response() + + app = web.Application() + app.add_routes([web.get('/get', handler)]) + + client = await aiohttp_client(app) + resp = await client.get('/get') + assert resp.status == 200 + + +async def test_signal_on_error_handler(aiohttp_client) -> None: + + async def on_prepare(request, response): + response.headers['X-Custom'] = 'val' + + app = web.Application() + app.on_response_prepare.append(on_prepare) + + client = await aiohttp_client(app) + resp = await client.get('/') + assert resp.status == 404 + assert resp.headers['X-Custom'] == 'val' diff -Nru python-aiohttp-3.1.3/tests/test_web_log.py python-aiohttp-3.5.1/tests/test_web_log.py --- python-aiohttp-3.1.3/tests/test_web_log.py 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_web_log.py 2018-12-24 20:58:54.000000000 +0000 @@ -0,0 +1,159 @@ +import datetime +import platform +from unittest import mock + +import pytest + +from aiohttp.abc import AbstractAccessLogger +from aiohttp.web_log import AccessLogger + + +IS_PYPY = platform.python_implementation() == 'PyPy' + + +def test_access_logger_format() -> None: + log_format = '%T "%{ETag}o" %X {X} %%P' + mock_logger = mock.Mock() + access_logger = AccessLogger(mock_logger, log_format) + expected = '%s "%s" %%X {X} %%%s' + assert expected == access_logger._log_format + + +@pytest.mark.skip( + IS_PYPY, + """ + Because of patching :py:class:`datetime.datetime`, under PyPy it + fails in :py:func:`isinstance` call in + :py:meth:`datetime.datetime.__sub__` (called from + :py:meth:`aiohttp.AccessLogger._format_t`): + + *** TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types + + (Pdb) from datetime import datetime + (Pdb) isinstance(now, datetime) + *** TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types + (Pdb) datetime.__class__ + + (Pdb) isinstance(now, datetime.__class__) + False + + Ref: https://bitbucket.org/pypy/pypy/issues/1187/call-to-isinstance-in-__sub__-self-other + Ref: https://github.com/celery/celery/issues/811 + Ref: https://stackoverflow.com/a/46102240/595220 + """, # noqa: E501 +) +def test_access_logger_atoms(mocker) -> None: + utcnow = datetime.datetime(1843, 1, 1, 0, 30) + mock_datetime = mocker.patch("aiohttp.datetime.datetime") + mock_getpid = mocker.patch("os.getpid") + mock_datetime.utcnow.return_value = utcnow + mock_getpid.return_value = 42 + log_format = '%a %t %P %r %s %b %T %Tf %D "%{H1}i" "%{H2}i"' + mock_logger = mock.Mock() + access_logger = AccessLogger(mock_logger, log_format) + request = mock.Mock(headers={'H1': 'a', 'H2': 'b'}, + method="GET", path_qs="/path", + version=(1, 1), + remote="127.0.0.2") + response = mock.Mock(headers={}, body_length=42, status=200) + access_logger.log(request, response, 3.1415926) + assert not mock_logger.exception.called + expected = ('127.0.0.2 [01/Jan/1843:00:29:56 +0000] <42> ' + 'GET /path HTTP/1.1 200 42 3 3.141593 3141593 "a" "b"') + extra = { + 'first_request_line': 'GET /path HTTP/1.1', + 'process_id': '<42>', + 'remote_address': '127.0.0.2', + 'request_start_time': '[01/Jan/1843:00:29:56 +0000]', + 'request_time': 3, + 'request_time_frac': '3.141593', + 'request_time_micro': 3141593, + 'response_size': 42, + 'response_status': 200, + 'request_header': {'H1': 'a', 'H2': 'b'}, + } + + mock_logger.info.assert_called_with(expected, extra=extra) + + +def test_access_logger_dicts() -> None: + log_format = '%{User-Agent}i %{Content-Length}o %{None}i' + mock_logger = mock.Mock() + access_logger = AccessLogger(mock_logger, log_format) + request = mock.Mock(headers={"User-Agent": "Mock/1.0"}, version=(1, 1), + remote="127.0.0.2") + response = mock.Mock(headers={"Content-Length": 123}) + access_logger.log(request, response, 0.0) + assert not mock_logger.error.called + expected = 'Mock/1.0 123 -' + extra = { + 'request_header': {"User-Agent": "Mock/1.0", 'None': '-'}, + 'response_header': {'Content-Length': 123} + } + + mock_logger.info.assert_called_with(expected, extra=extra) + + +def test_access_logger_unix_socket() -> None: + log_format = '|%a|' + mock_logger = mock.Mock() + access_logger = AccessLogger(mock_logger, log_format) + request = mock.Mock(headers={"User-Agent": "Mock/1.0"}, version=(1, 1), + remote="") + response = mock.Mock() + access_logger.log(request, response, 0.0) + assert not mock_logger.error.called + expected = '||' + mock_logger.info.assert_called_with(expected, extra={'remote_address': ''}) + + +def test_logger_no_message() -> None: + mock_logger = mock.Mock() + access_logger = AccessLogger(mock_logger, + "%r %{content-type}i") + extra_dict = { + 'first_request_line': '-', + 'request_header': {'content-type': '(no headers)'} + } + + access_logger.log(None, None, 0.0) + mock_logger.info.assert_called_with("- (no headers)", extra=extra_dict) + + +def test_logger_internal_error() -> None: + mock_logger = mock.Mock() + access_logger = AccessLogger(mock_logger, "%D") + access_logger.log(None, None, 'invalid') + mock_logger.exception.assert_called_with("Error in logging") + + +def test_logger_no_transport() -> None: + mock_logger = mock.Mock() + access_logger = AccessLogger(mock_logger, "%a") + access_logger.log(None, None, 0) + mock_logger.info.assert_called_with("-", extra={'remote_address': '-'}) + + +def test_logger_abc() -> None: + class Logger(AbstractAccessLogger): + def log(self, request, response, time): + 1 / 0 + + mock_logger = mock.Mock() + access_logger = Logger(mock_logger, None) + + with pytest.raises(ZeroDivisionError): + access_logger.log(None, None, None) + + class Logger(AbstractAccessLogger): + def log(self, request, response, time): + self.logger.info(self.log_format.format( + request=request, + response=response, + time=time + )) + + mock_logger = mock.Mock() + access_logger = Logger(mock_logger, '{request} {response} {time}') + access_logger.log('request', 'response', 1) + mock_logger.info.assert_called_with('request response 1') diff -Nru python-aiohttp-3.1.3/tests/test_web_middleware.py python-aiohttp-3.5.1/tests/test_web_middleware.py --- python-aiohttp-3.1.3/tests/test_web_middleware.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_web_middleware.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,11 +1,12 @@ import re import pytest +from yarl import URL from aiohttp import web -async def test_middleware_modifies_response(loop, aiohttp_client): +async def test_middleware_modifies_response(loop, aiohttp_client) -> None: async def handler(request): return web.Response(body=b'OK') @@ -27,7 +28,7 @@ assert 'OK[MIDDLEWARE]' == txt -async def test_middleware_handles_exception(loop, aiohttp_client): +async def test_middleware_handles_exception(loop, aiohttp_client) -> None: async def handler(request): raise RuntimeError('Error text') @@ -48,7 +49,7 @@ assert 'Error text[MIDDLEWARE]' == txt -async def test_middleware_chain(loop, aiohttp_client): +async def test_middleware_chain(loop, aiohttp_client) -> None: async def handler(request): return web.Response(text='OK') @@ -86,6 +87,8 @@ 'GET', '/resource1/a/b', handler) app.router.add_route( 'GET', '/resource2/a/b/', handler) + app.router.add_route( + 'GET', '/resource2/a/b%2Fc/', handler) app.middlewares.extend(extra_middlewares) return aiohttp_client(app, server_kwargs={'skip_url_asserts': True}) return wrapper @@ -101,7 +104,9 @@ ('/resource1?p1=1&p2=2', 200), ('/resource1/?p1=1&p2=2', 404), ('/resource2?p1=1&p2=2', 200), - ('/resource2/?p1=1&p2=2', 200) + ('/resource2/?p1=1&p2=2', 200), + ('/resource2/a/b%2Fc', 200), + ('/resource2/a/b%2Fc/', 200) ]) async def test_add_trailing_when_necessary( self, path, status, cli): @@ -111,6 +116,30 @@ resp = await client.get(path) assert resp.status == status + assert resp.url.query == URL(path).query + + @pytest.mark.parametrize("path, status", [ + ('/resource1', 200), + ('/resource1/', 200), + ('/resource2', 404), + ('/resource2/', 200), + ('/resource1?p1=1&p2=2', 200), + ('/resource1/?p1=1&p2=2', 200), + ('/resource2?p1=1&p2=2', 404), + ('/resource2/?p1=1&p2=2', 200), + ('/resource2/a/b%2Fc', 404), + ('/resource2/a/b%2Fc/', 200) + ]) + async def test_remove_trailing_when_necessary(self, path, + status, cli) -> None: + extra_middlewares = [ + web.normalize_path_middleware( + append_slash=False, remove_slash=True, merge_slashes=False)] + client = await cli(extra_middlewares) + + resp = await client.get(path) + assert resp.status == status + assert resp.url.query == URL(path).query @pytest.mark.parametrize("path, status", [ ('/resource1', 200), @@ -120,7 +149,9 @@ ('/resource1?p1=1&p2=2', 200), ('/resource1/?p1=1&p2=2', 404), ('/resource2?p1=1&p2=2', 404), - ('/resource2/?p1=1&p2=2', 200) + ('/resource2/?p1=1&p2=2', 200), + ('/resource2/a/b%2Fc', 404), + ('/resource2/a/b%2Fc/', 200) ]) async def test_no_trailing_slash_when_disabled( self, path, status, cli): @@ -131,6 +162,7 @@ resp = await client.get(path) assert resp.status == status + assert resp.url.query == URL(path).query @pytest.mark.parametrize("path, status", [ ('/resource1/a/b', 200), @@ -146,13 +178,14 @@ ('/////resource1/a///b?p=1', 200), ('/////resource1/a//b/?p=1', 404), ]) - async def test_merge_slash(self, path, status, cli): + async def test_merge_slash(self, path, status, cli) -> None: extra_middlewares = [ web.normalize_path_middleware(append_slash=False)] client = await cli(extra_middlewares) resp = await client.get(path) assert resp.status == status + assert resp.url.query == URL(path).query @pytest.mark.parametrize("path, status", [ ('/resource1/a/b', 200), @@ -186,16 +219,64 @@ ('/////resource2/a///b?p=1', 200), ('/////resource2/a///b/?p=1', 200) ]) - async def test_append_and_merge_slash(self, path, status, cli): + async def test_append_and_merge_slash(self, path, status, cli) -> None: extra_middlewares = [ web.normalize_path_middleware()] client = await cli(extra_middlewares) resp = await client.get(path) assert resp.status == status + assert resp.url.query == URL(path).query + + @pytest.mark.parametrize("path, status", [ + ('/resource1/a/b', 200), + ('/resource1/a/b/', 200), + ('//resource2//a//b', 404), + ('//resource2//a//b/', 200), + ('///resource1//a//b', 200), + ('///resource1//a//b/', 200), + ('/////resource1/a///b', 200), + ('/////resource1/a///b/', 200), + ('/////resource1/a///b///', 200), + ('/resource2/a/b', 404), + ('//resource2//a//b', 404), + ('//resource2//a//b/', 200), + ('///resource2//a//b', 404), + ('///resource2//a//b/', 200), + ('/////resource2/a///b', 404), + ('/////resource2/a///b/', 200), + ('/resource1/a/b?p=1', 200), + ('/resource1/a/b/?p=1', 200), + ('//resource2//a//b?p=1', 404), + ('//resource2//a//b/?p=1', 200), + ('///resource1//a//b?p=1', 200), + ('///resource1//a//b/?p=1', 200), + ('/////resource1/a///b?p=1', 200), + ('/////resource1/a///b/?p=1', 200), + ('/resource2/a/b?p=1', 404), + ('//resource2//a//b?p=1', 404), + ('//resource2//a//b/?p=1', 200), + ('///resource2//a//b?p=1', 404), + ('///resource2//a//b/?p=1', 200), + ('/////resource2/a///b?p=1', 404), + ('/////resource2/a///b/?p=1', 200) + ]) + async def test_remove_and_merge_slash(self, path, status, cli) -> None: + extra_middlewares = [ + web.normalize_path_middleware( + append_slash=False, remove_slash=True)] + + client = await cli(extra_middlewares) + resp = await client.get(path) + assert resp.status == status + assert resp.url.query == URL(path).query + + async def test_cannot_remove_and_add_slash(self) -> None: + with pytest.raises(AssertionError): + web.normalize_path_middleware(append_slash=True, remove_slash=True) -async def test_old_style_middleware(loop, aiohttp_client): +async def test_old_style_middleware(loop, aiohttp_client) -> None: async def handler(request): return web.Response(body=b'OK') @@ -228,7 +309,7 @@ msg) -async def test_mixed_middleware(loop, aiohttp_client): +async def test_mixed_middleware(loop, aiohttp_client) -> None: async def handler(request): return web.Response(body=b'OK') @@ -281,7 +362,7 @@ assert re.match(p1, str(w.list[1].message)) -async def test_old_style_middleware_class(loop, aiohttp_client): +async def test_old_style_middleware_class(loop, aiohttp_client) -> None: async def handler(request): return web.Response(body=b'OK') @@ -313,7 +394,7 @@ 'at 0x[0-9a-fA-F]+>" deprecated, see #2252$', msg) -async def test_new_style_middleware_class(loop, aiohttp_client): +async def test_new_style_middleware_class(loop, aiohttp_client) -> None: async def handler(request): return web.Response(body=b'OK') @@ -339,7 +420,7 @@ assert len(warning_checker) == 0 -async def test_new_style_middleware_method(loop, aiohttp_client): +async def test_new_style_middleware_method(loop, aiohttp_client) -> None: async def handler(request): return web.Response(body=b'OK') diff -Nru python-aiohttp-3.1.3/tests/test_web_protocol.py python-aiohttp-3.5.1/tests/test_web_protocol.py --- python-aiohttp-3.1.3/tests/test_web_protocol.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_web_protocol.py 2018-12-24 20:58:54.000000000 +0000 @@ -30,7 +30,9 @@ @pytest.fixture def manager(request_handler, loop): - return web.Server(request_handler, loop=loop) + async def maker(): + return web.Server(request_handler) + return loop.run_until_complete(maker()) @pytest.fixture @@ -98,7 +100,8 @@ mocker.patch('aiohttp.helpers.ceil').side_effect = ceil -async def test_shutdown(srv, loop, transport): +async def test_shutdown(srv, transport) -> None: + loop = asyncio.get_event_loop() assert transport is srv.transport srv._keepalive = True @@ -117,11 +120,11 @@ assert srv.transport is None assert not srv._task_handler - await asyncio.sleep(0.1, loop=loop) + await asyncio.sleep(0.1) assert task_handler.done() -async def test_double_shutdown(srv, transport): +async def test_double_shutdown(srv, transport) -> None: await srv.shutdown() assert transport.close.called assert srv.transport is None @@ -132,7 +135,8 @@ assert srv.transport is None -async def test_shutdown_wait_error_handler(loop, srv, transport): +async def test_shutdown_wait_error_handler(srv, transport) -> None: + loop = asyncio.get_event_loop() async def _error_handle(): pass @@ -142,14 +146,14 @@ assert srv._error_handler.done() -async def test_close_after_response(srv, loop, transport): +async def test_close_after_response(srv, transport) -> None: srv.data_received( b'GET / HTTP/1.0\r\n' b'Host: example.com\r\n' b'Content-Length: 0\r\n\r\n') h = srv._task_handler - await asyncio.sleep(0.1, loop=loop) + await asyncio.sleep(0.1) assert srv._waiter is None assert srv._task_handler is None @@ -159,13 +163,13 @@ assert h.done() -def test_connection_made(make_srv): +def test_connection_made(make_srv) -> None: srv = make_srv() srv.connection_made(mock.Mock()) assert not srv._force_close -def test_connection_made_with_tcp_keepaplive(make_srv, transport): +def test_connection_made_with_tcp_keepaplive(make_srv, transport) -> None: srv = make_srv() sock = mock.Mock() @@ -175,7 +179,7 @@ socket.SO_KEEPALIVE, 1) -def test_connection_made_without_tcp_keepaplive(make_srv): +def test_connection_made_without_tcp_keepaplive(make_srv) -> None: srv = make_srv(tcp_keepalive=False) sock = mock.Mock() @@ -185,14 +189,14 @@ assert not sock.setsockopt.called -def test_eof_received(make_srv): +def test_eof_received(make_srv) -> None: srv = make_srv() srv.connection_made(mock.Mock()) srv.eof_received() # assert srv.reader._eof -async def test_connection_lost(srv, loop): +async def test_connection_lost(srv) -> None: srv.data_received( b'GET / HTTP/1.1\r\n' b'Host: example.com\r\n' @@ -200,7 +204,7 @@ srv._keepalive = True handle = srv._task_handler - await asyncio.sleep(0, loop=loop) # wait for .start() starting + await asyncio.sleep(0) # wait for .start() starting srv.connection_lost(None) assert srv._force_close @@ -210,7 +214,7 @@ assert not srv._task_handler -def test_srv_keep_alive(srv): +def test_srv_keep_alive(srv) -> None: assert not srv._keepalive srv.keep_alive(True) @@ -220,7 +224,7 @@ assert not srv._keepalive -def test_srv_keep_alive_disable(srv): +def test_srv_keep_alive_disable(srv) -> None: handle = srv._keepalive_handle = mock.Mock() srv.keep_alive(False) @@ -229,24 +233,24 @@ handle.cancel.assert_called_with() -async def test_simple(srv, loop, buf): +async def test_simple(srv, buf) -> None: srv.data_received( b'GET / HTTP/1.1\r\n\r\n') - await asyncio.sleep(0, loop=loop) + await asyncio.sleep(0.05) assert buf.startswith(b'HTTP/1.1 200 OK\r\n') -async def test_bad_method(srv, loop, buf): +async def test_bad_method(srv, buf) -> None: srv.data_received( - b'!@#$ / HTTP/1.0\r\n' + b':BAD; / HTTP/1.0\r\n' b'Host: example.com\r\n\r\n') - await asyncio.sleep(0, loop=loop) + await asyncio.sleep(0) assert buf.startswith(b'HTTP/1.0 400 Bad Request\r\n') -async def test_data_received_error(srv, loop, buf): +async def test_data_received_error(srv, buf) -> None: transport = srv.transport srv._request_parser = mock.Mock() srv._request_parser.feed_data.side_effect = TypeError @@ -255,31 +259,31 @@ b'!@#$ / HTTP/1.0\r\n' b'Host: example.com\r\n\r\n') - await asyncio.sleep(0, loop=loop) + await asyncio.sleep(0) assert buf.startswith(b'HTTP/1.0 500 Internal Server Error\r\n') assert transport.close.called assert srv._error_handler is None -async def test_line_too_long(srv, loop, buf): +async def test_line_too_long(srv, buf) -> None: srv.data_received(b''.join([b'a' for _ in range(10000)]) + b'\r\n\r\n') - await asyncio.sleep(0, loop=loop) + await asyncio.sleep(0) assert buf.startswith(b'HTTP/1.0 400 Bad Request\r\n') -async def test_invalid_content_length(srv, loop, buf): +async def test_invalid_content_length(srv, buf) -> None: srv.data_received( b'GET / HTTP/1.0\r\n' b'Host: example.com\r\n' b'Content-Length: sdgg\r\n\r\n') - await asyncio.sleep(0, loop=loop) + await asyncio.sleep(0) assert buf.startswith(b'HTTP/1.0 400 Bad Request\r\n') async def test_handle_error__utf( - make_srv, buf, transport, loop, request_handler + make_srv, buf, transport, request_handler ): request_handler.side_effect = RuntimeError('что-то пошло не так') @@ -292,7 +296,7 @@ b'GET / HTTP/1.0\r\n' b'Host: example.com\r\n' b'Content-Length: 0\r\n\r\n') - await asyncio.sleep(0, loop=loop) + await asyncio.sleep(0) assert b'HTTP/1.0 500 Internal Server Error' in buf assert b'Content-Type: text/html; charset=utf-8' in buf @@ -305,7 +309,7 @@ async def test_unhandled_runtime_error( - make_srv, loop, transport, request_handler + make_srv, transport, request_handler ): async def handle(request): @@ -332,7 +336,7 @@ async def test_handle_uncompleted( - make_srv, loop, transport, handle_with_error, request_handler): + make_srv, transport, handle_with_error, request_handler): closed = False def close(): @@ -359,7 +363,7 @@ async def test_handle_uncompleted_pipe( - make_srv, loop, transport, request_handler, handle_with_error): + make_srv, transport, request_handler, handle_with_error): closed = False normal_completed = False @@ -376,7 +380,7 @@ async def handle(request): nonlocal normal_completed normal_completed = True - await asyncio.sleep(0.05, loop=loop) + await asyncio.sleep(0.05) return web.Response() # normal @@ -385,7 +389,7 @@ b'GET / HTTP/1.1\r\n' b'Host: example.com\r\n' b'Content-Length: 0\r\n\r\n') - await asyncio.sleep(0, loop=loop) + await asyncio.sleep(0) # with exception request_handler.side_effect = handle_with_error() @@ -396,7 +400,7 @@ assert srv._task_handler - await asyncio.sleep(0, loop=loop) + await asyncio.sleep(0) await srv._task_handler assert normal_completed @@ -406,7 +410,7 @@ "Error handling request", exc_info=mock.ANY) -async def test_lingering(srv, loop, transport): +async def test_lingering(srv, transport) -> None: assert not transport.close.called async def handle(message, request, writer): @@ -418,70 +422,88 @@ b'Host: example.com\r\n' b'Content-Length: 3\r\n\r\n') - await asyncio.sleep(0.05, loop=loop) + await asyncio.sleep(0.05) assert not transport.close.called srv.data_received(b'123') - await asyncio.sleep(0, loop=loop) + await asyncio.sleep(0) transport.close.assert_called_with() -async def test_lingering_disabled(make_srv, loop, transport, request_handler): +async def test_lingering_disabled(make_srv, + transport, request_handler) -> None: async def handle_request(request): - await asyncio.sleep(0, loop=loop) + await asyncio.sleep(0) srv = make_srv(lingering_time=0) srv.connection_made(transport) request_handler.side_effect = handle_request - await asyncio.sleep(0, loop=loop) + await asyncio.sleep(0) assert not transport.close.called srv.data_received( b'GET / HTTP/1.0\r\n' b'Host: example.com\r\n' b'Content-Length: 50\r\n\r\n') - await asyncio.sleep(0, loop=loop) + await asyncio.sleep(0) assert not transport.close.called - await asyncio.sleep(0, loop=loop) + await asyncio.sleep(0.05) transport.close.assert_called_with() async def test_lingering_timeout( - make_srv, loop, transport, ceil, request_handler + make_srv, transport, ceil, request_handler ): async def handle_request(request): - await asyncio.sleep(0, loop=loop) + await asyncio.sleep(0) srv = make_srv(lingering_time=1e-30) srv.connection_made(transport) request_handler.side_effect = handle_request - await asyncio.sleep(0, loop=loop) + await asyncio.sleep(0.05) assert not transport.close.called srv.data_received( b'GET / HTTP/1.0\r\n' b'Host: example.com\r\n' b'Content-Length: 50\r\n\r\n') - await asyncio.sleep(0, loop=loop) + await asyncio.sleep(0) assert not transport.close.called - await asyncio.sleep(0, loop=loop) + await asyncio.sleep(0.05) transport.close.assert_called_with() -def test_handle_cancel(make_srv, loop, transport): +async def test_handle_payload_access_error( + make_srv, transport, request_handler +): + srv = make_srv(lingering_time=0) + srv.connection_made(transport) + srv.data_received( + b'POST /test HTTP/1.1\r\n' + b'Content-Length: 9\r\n\r\n' + b'some data' + ) + # start request_handler task + await asyncio.sleep(0.05) + + with pytest.raises(web.PayloadAccessError): + await request_handler.call_args[0][0].content.read() + + +async def test_handle_cancel(make_srv, transport) -> None: log = mock.Mock() srv = make_srv(logger=log, debug=True) srv.connection_made(transport) async def handle_request(message, payload, writer): - await asyncio.sleep(10, loop=loop) + await asyncio.sleep(10) srv.handle_request = handle_request @@ -493,12 +515,11 @@ b'Content-Length: 10\r\n' b'Host: example.com\r\n\r\n') - loop.run_until_complete( - asyncio.gather(srv._task_handler, cancel(), loop=loop)) + await asyncio.gather(srv._task_handler, cancel()) assert log.debug.called -def test_handle_cancelled(make_srv, loop, transport): +async def test_handle_cancelled(make_srv, transport) -> None: log = mock.Mock() srv = make_srv(logger=log, debug=True) @@ -506,35 +527,47 @@ srv.handle_request = mock.Mock() # start request_handler task - loop.run_until_complete(asyncio.sleep(0, loop=loop)) + await asyncio.sleep(0) srv.data_received( b'GET / HTTP/1.0\r\n' b'Host: example.com\r\n\r\n') r_handler = srv._task_handler - assert loop.run_until_complete(r_handler) is None + assert (await r_handler) is None -async def test_handle_400(srv, loop, buf, transport): +async def test_handle_400(srv, buf, transport) -> None: srv.data_received(b'GET / HT/asd\r\n\r\n') - await asyncio.sleep(0, loop=loop) + await asyncio.sleep(0) assert b'400 Bad Request' in buf -def test_handle_500(srv, loop, buf, transport, request_handler): +async def test_handle_500(srv, buf, transport, request_handler) -> None: request_handler.side_effect = ValueError srv.data_received( b'GET / HTTP/1.0\r\n' b'Host: example.com\r\n\r\n') - loop.run_until_complete(srv._task_handler) + await srv._task_handler assert b'500 Internal Server Error' in buf -async def test_keep_alive(make_srv, loop, transport, ceil): +async def test_handle_504(srv, buf, request_handler) -> None: + request_handler.side_effect = asyncio.TimeoutError + + srv.data_received( + b'GET / HTTP/1.0\r\n' + b'Host: example.com\r\n\r\n') + await srv._task_handler + + assert b'504 Gateway Timeout' in buf + + +async def test_keep_alive(make_srv, transport, ceil) -> None: + loop = asyncio.get_event_loop() srv = make_srv(keepalive_timeout=0.05) srv.KEEPALIVE_RESCHEDULE_DELAY = 0.1 srv.connection_made(transport) @@ -549,18 +582,20 @@ b'Host: example.com\r\n' b'Content-Length: 0\r\n\r\n') - await asyncio.sleep(0, loop=loop) - waiter = srv._waiter - assert waiter + waiter = None + while waiter is None: + await asyncio.sleep(0) + waiter = srv._waiter assert srv._keepalive_handle is not None assert not transport.close.called - await asyncio.sleep(0.2, loop=loop) + await asyncio.sleep(0.2) assert transport.close.called assert waiter.cancelled -def test_srv_process_request_without_timeout(make_srv, loop, transport): +async def test_srv_process_request_without_timeout(make_srv, + transport) -> None: srv = make_srv() srv.connection_made(transport) @@ -568,24 +603,25 @@ b'GET / HTTP/1.0\r\n' b'Host: example.com\r\n\r\n') - loop.run_until_complete(srv._task_handler) + await srv._task_handler assert transport.close.called -def test_keep_alive_timeout_default(srv): +def test_keep_alive_timeout_default(srv) -> None: assert 75 == srv.keepalive_timeout -def test_keep_alive_timeout_nondefault(make_srv): +def test_keep_alive_timeout_nondefault(make_srv) -> None: srv = make_srv(keepalive_timeout=10) assert 10 == srv.keepalive_timeout -async def test_supports_connect_method(srv, loop, transport, request_handler): +async def test_supports_connect_method(srv, + transport, request_handler) -> None: srv.data_received( b'CONNECT aiohttp.readthedocs.org:80 HTTP/1.0\r\n' b'Content-Length: 0\r\n\r\n') - await asyncio.sleep(0.1, loop=loop) + await asyncio.sleep(0.1) assert request_handler.called assert isinstance( @@ -593,18 +629,18 @@ streams.StreamReader) -async def test_content_length_0(srv, loop, request_handler): +async def test_content_length_0(srv, request_handler) -> None: srv.data_received( b'GET / HTTP/1.1\r\n' b'Host: example.org\r\n' b'Content-Length: 0\r\n\r\n') - await asyncio.sleep(0, loop=loop) + await asyncio.sleep(0) assert request_handler.called assert request_handler.call_args[0][0].content == streams.EMPTY_PAYLOAD -def test_rudimentary_transport(srv, loop): +def test_rudimentary_transport(srv) -> None: transport = mock.Mock() srv.connection_made(transport) @@ -627,9 +663,10 @@ assert not srv._reading_paused -async def test_close(srv, loop, transport): +async def test_close(srv, transport) -> None: transport.close.side_effect = partial(srv.connection_lost, None) srv.connection_made(transport) + await asyncio.sleep(0) srv.handle_request = mock.Mock() srv.handle_request.side_effect = helpers.noop @@ -645,19 +682,19 @@ b'Host: example.com\r\n' b'Content-Length: 0\r\n\r\n') - await asyncio.sleep(0, loop=loop) + await asyncio.sleep(0.05) assert srv._task_handler assert srv._waiter srv.close() - await asyncio.sleep(0, loop=loop) + await asyncio.sleep(0) assert srv._task_handler is None assert srv.transport is None assert transport.close.called async def test_pipeline_multiple_messages( - srv, loop, transport, request_handler + srv, transport, request_handler ): transport.close.side_effect = partial(srv.connection_lost, None) @@ -685,14 +722,14 @@ assert len(srv._messages) == 2 assert srv._waiter is not None - await asyncio.sleep(0, loop=loop) + await asyncio.sleep(0.05) assert srv._task_handler is not None assert srv._waiter is not None assert processed == 2 async def test_pipeline_response_order( - srv, loop, buf, transport, request_handler + srv, buf, transport, request_handler ): transport.close.side_effect = partial(srv.connection_lost, None) srv._keepalive = True @@ -701,7 +738,7 @@ async def handle1(request): nonlocal processed - await asyncio.sleep(0.01, loop=loop) + await asyncio.sleep(0.01) resp = web.StreamResponse() await resp.prepare(request) await resp.write(b'test1') @@ -714,7 +751,7 @@ b'GET / HTTP/1.1\r\n' b'Host: example.com\r\n' b'Content-Length: 0\r\n\r\n') - await asyncio.sleep(0, loop=loop) + await asyncio.sleep(0) # second @@ -732,15 +769,15 @@ b'GET / HTTP/1.1\r\n' b'Host: example.com\r\n' b'Content-Length: 0\r\n\r\n') - await asyncio.sleep(0, loop=loop) + await asyncio.sleep(0) assert srv._task_handler is not None - await asyncio.sleep(0.1, loop=loop) + await asyncio.sleep(0.1) assert processed == [1, 2] -def test_data_received_close(srv): +def test_data_received_close(srv) -> None: srv.close() srv.data_received( b'GET / HTTP/1.1\r\n' @@ -750,7 +787,7 @@ assert not srv._messages -def test_data_received_force_close(srv): +def test_data_received_force_close(srv) -> None: srv.force_close() srv.data_received( b'GET / HTTP/1.1\r\n' @@ -760,7 +797,8 @@ assert not srv._messages -async def test__process_keepalive(loop, srv): +async def test__process_keepalive(srv) -> None: + loop = asyncio.get_event_loop() # wait till the waiter is waiting await asyncio.sleep(0) @@ -775,7 +813,8 @@ assert srv._force_close -async def test__process_keepalive_schedule_next(loop, srv): +async def test__process_keepalive_schedule_next(srv) -> None: + loop = asyncio.get_event_loop() # wait till the waiter is waiting await asyncio.sleep(0) @@ -792,16 +831,17 @@ ) -def test__process_keepalive_force_close(loop, srv): +async def test__process_keepalive_force_close(srv) -> None: + loop = asyncio.get_event_loop() srv._force_close = True with mock.patch.object(loop, "call_at") as call_at_patched: srv._process_keepalive() assert not call_at_patched.called -def test_two_data_received_without_waking_up_start_task(srv, loop): +async def test_two_data_received_without_waking_up_start_task(srv) -> None: # make a chance to srv.start() method start waiting for srv._waiter - loop.run_until_complete(asyncio.sleep(0.01)) + await asyncio.sleep(0.01) assert srv._waiter is not None srv.data_received( @@ -817,3 +857,4 @@ assert len(srv._messages) == 2 assert srv._waiter.done() + await asyncio.sleep(0.01) diff -Nru python-aiohttp-3.1.3/tests/test_web_request_handler.py python-aiohttp-3.5.1/tests/test_web_request_handler.py --- python-aiohttp-3.1.3/tests/test_web_request_handler.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_web_request_handler.py 2018-12-24 20:58:54.000000000 +0000 @@ -8,8 +8,8 @@ return web.Response() -def test_repr(loop): - manager = web.Server(serve, loop=loop) +async def test_repr() -> None: + manager = web.Server(serve) handler = manager() assert '' == repr(handler) @@ -18,8 +18,8 @@ assert '' == repr(handler) -def test_connections(loop): - manager = web.Server(serve, loop=loop) +async def test_connections() -> None: + manager = web.Server(serve) assert manager.connections == [] handler = object() @@ -31,8 +31,8 @@ assert manager.connections == [] -async def test_shutdown_no_timeout(loop): - manager = web.Server(serve, loop=loop) +async def test_shutdown_no_timeout() -> None: + manager = web.Server(serve) handler = mock.Mock() handler.shutdown = make_mocked_coro(mock.Mock()) @@ -46,8 +46,8 @@ handler.shutdown.assert_called_with(None) -async def test_shutdown_timeout(loop): - manager = web.Server(serve, loop=loop) +async def test_shutdown_timeout() -> None: + manager = web.Server(serve) handler = mock.Mock() handler.shutdown = make_mocked_coro(mock.Mock()) diff -Nru python-aiohttp-3.1.3/tests/test_web_request.py python-aiohttp-3.5.1/tests/test_web_request.py --- python-aiohttp-3.1.3/tests/test_web_request.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_web_request.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,5 +1,6 @@ +import asyncio import socket -from collections import MutableMapping +from collections.abc import MutableMapping from unittest import mock import pytest @@ -18,7 +19,7 @@ return mock.Mock(_reading_paused=False) -def test_ctor(): +def test_ctor() -> None: req = make_mocked_request('GET', '/path/to?a=1&b=2') assert 'GET' == req.method @@ -29,7 +30,6 @@ assert 'a=1&b=2' == req.query_string assert CIMultiDict() == req.headers assert () == req.raw_headers - assert req.message == req._message get = req.query assert MultiDict([('a', '1'), ('b', '2')]) == get @@ -54,25 +54,31 @@ assert req.task is req._task -def test_doubleslashes(): +def test_deprecated_message() -> None: + req = make_mocked_request('GET', '/path/to?a=1&b=2') + with pytest.warns(DeprecationWarning): + assert req.message == req._message + + +def test_doubleslashes() -> None: # NB: //foo/bar is an absolute URL with foo netloc and /bar path req = make_mocked_request('GET', '/bar//foo/') assert '/bar//foo/' == req.path -def test_content_type_not_specified(): +def test_content_type_not_specified() -> None: req = make_mocked_request('Get', '/') assert 'application/octet-stream' == req.content_type -def test_content_type_from_spec(): +def test_content_type_from_spec() -> None: req = make_mocked_request('Get', '/', CIMultiDict([('CONTENT-TYPE', 'application/json')])) assert 'application/json' == req.content_type -def test_content_type_from_spec_with_charset(): +def test_content_type_from_spec_with_charset() -> None: req = make_mocked_request( 'Get', '/', CIMultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')])) @@ -80,7 +86,7 @@ assert 'UTF-8' == req.charset -def test_calc_content_type_on_getting_charset(): +def test_calc_content_type_on_getting_charset() -> None: req = make_mocked_request( 'Get', '/', CIMultiDict([('CONTENT-TYPE', 'text/html; charset=UTF-8')])) @@ -88,30 +94,30 @@ assert 'text/html' == req.content_type -def test_urlencoded_querystring(): +def test_urlencoded_querystring() -> None: req = make_mocked_request( 'GET', '/yandsearch?text=%D1%82%D0%B5%D0%BA%D1%81%D1%82') assert {'text': 'текст'} == req.query -def test_non_ascii_path(): +def test_non_ascii_path() -> None: req = make_mocked_request('GET', '/путь') assert '/путь' == req.path -def test_non_ascii_raw_path(): +def test_non_ascii_raw_path() -> None: req = make_mocked_request('GET', '/путь') assert '/путь' == req.raw_path -def test_content_length(): +def test_content_length() -> None: req = make_mocked_request('Get', '/', CIMultiDict([('CONTENT-LENGTH', '123')])) assert 123 == req.content_length -def test_range_to_slice_head(): +def test_range_to_slice_head() -> None: def bytes_gen(size): for i in range(size): yield i % 256 @@ -124,7 +130,7 @@ assert req.content[req.http_range] == payload[:500] -def test_range_to_slice_mid(): +def test_range_to_slice_mid() -> None: def bytes_gen(size): for i in range(size): yield i % 256 @@ -137,7 +143,7 @@ assert req.content[req.http_range] == payload[500:1000] -def test_range_to_slice_tail_start(): +def test_range_to_slice_tail_start() -> None: def bytes_gen(size): for i in range(size): yield i % 256 @@ -150,7 +156,7 @@ assert req.content[req.http_range] == payload[-500:] -def test_range_to_slice_tail_stop(): +def test_range_to_slice_tail_stop() -> None: def bytes_gen(size): for i in range(size): yield i % 256 @@ -163,24 +169,24 @@ assert req.content[req.http_range] == payload[-500:] -def test_non_keepalive_on_http10(): +def test_non_keepalive_on_http10() -> None: req = make_mocked_request('GET', '/', version=HttpVersion(1, 0)) assert not req.keep_alive -def test_non_keepalive_on_closing(): +def test_non_keepalive_on_closing() -> None: req = make_mocked_request('GET', '/', closing=True) assert not req.keep_alive -async def test_call_POST_on_GET_request(): +async def test_call_POST_on_GET_request() -> None: req = make_mocked_request('GET', '/') ret = await req.post() assert CIMultiDict() == ret -async def test_call_POST_on_weird_content_type(): +async def test_call_POST_on_weird_content_type() -> None: req = make_mocked_request( 'POST', '/', headers=CIMultiDict({'CONTENT-TYPE': 'something/weird'})) @@ -189,7 +195,7 @@ assert CIMultiDict() == ret -async def test_call_POST_twice(): +async def test_call_POST_twice() -> None: req = make_mocked_request('GET', '/') ret1 = await req.post() @@ -197,7 +203,7 @@ assert ret1 is ret2 -def test_no_request_cookies(): +def test_no_request_cookies() -> None: req = make_mocked_request('GET', '/') assert req.cookies == {} @@ -206,7 +212,7 @@ assert cookies is req.cookies -def test_request_cookie(): +def test_request_cookie() -> None: headers = CIMultiDict(COOKIE='cookie1=value1; cookie2=value2') req = make_mocked_request('GET', '/', headers=headers) @@ -214,7 +220,7 @@ 'cookie2': 'value2'} -def test_request_cookie__set_item(): +def test_request_cookie__set_item() -> None: headers = CIMultiDict(COOKIE='name=value') req = make_mocked_request('GET', '/', headers=headers) @@ -224,19 +230,19 @@ req.cookies['my'] = 'value' -def test_match_info(): +def test_match_info() -> None: req = make_mocked_request('GET', '/') assert req._match_info is req.match_info -def test_request_is_mutable_mapping(): +def test_request_is_mutable_mapping() -> None: req = make_mocked_request('GET', '/') assert isinstance(req, MutableMapping) req['key'] = 'value' assert 'value' == req['key'] -def test_request_delitem(): +def test_request_delitem() -> None: req = make_mocked_request('GET', '/') req['key'] = 'value' assert 'value' == req['key'] @@ -244,44 +250,44 @@ assert 'key' not in req -def test_request_len(): +def test_request_len() -> None: req = make_mocked_request('GET', '/') assert len(req) == 0 req['key'] = 'value' assert len(req) == 1 -def test_request_iter(): +def test_request_iter() -> None: req = make_mocked_request('GET', '/') req['key'] = 'value' req['key2'] = 'value2' assert set(req) == {'key', 'key2'} -def test___repr__(): +def test___repr__() -> None: req = make_mocked_request('GET', '/path/to') assert "" == repr(req) -def test___repr___non_ascii_path(): +def test___repr___non_ascii_path() -> None: req = make_mocked_request('GET', '/path/\U0001f415\U0001f308') assert "" == repr(req) -def test_http_scheme(): +def test_http_scheme() -> None: req = make_mocked_request('GET', '/', headers={'Host': 'example.com'}) assert "http" == req.scheme assert req.secure is False -def test_https_scheme_by_ssl_transport(): +def test_https_scheme_by_ssl_transport() -> None: req = make_mocked_request('GET', '/', headers={'Host': 'example.com'}, sslcontext=True) assert "https" == req.scheme assert req.secure is True -def test_single_forwarded_header(): +def test_single_forwarded_header() -> None: header = 'by=identifier;for=identifier;host=identifier;proto=identifier' req = make_mocked_request('GET', '/', headers=CIMultiDict({'Forwarded': header})) @@ -291,7 +297,22 @@ assert req.forwarded[0]['proto'] == 'identifier' -def test_single_forwarded_header_camelcase(): +@pytest.mark.parametrize( + "forward_for_in, forward_for_out", + [ + ("1.2.3.4:1234", "1.2.3.4:1234"), + ("1.2.3.4", "1.2.3.4"), + ('"[2001:db8:cafe::17]:1234"', '[2001:db8:cafe::17]:1234'), + ('"[2001:db8:cafe::17]"', '[2001:db8:cafe::17]'), + ]) +def test_forwarded_node_identifier(forward_for_in, forward_for_out) -> None: + header = 'for={}'.format(forward_for_in) + req = make_mocked_request('GET', '/', + headers=CIMultiDict({'Forwarded': header})) + assert req.forwarded == ({'for': forward_for_out},) + + +def test_single_forwarded_header_camelcase() -> None: header = 'bY=identifier;fOr=identifier;HOst=identifier;pRoTO=identifier' req = make_mocked_request('GET', '/', headers=CIMultiDict({'Forwarded': header})) @@ -301,14 +322,14 @@ assert req.forwarded[0]['proto'] == 'identifier' -def test_single_forwarded_header_single_param(): +def test_single_forwarded_header_single_param() -> None: header = 'BY=identifier' req = make_mocked_request('GET', '/', headers=CIMultiDict({'Forwarded': header})) assert req.forwarded[0]['by'] == 'identifier' -def test_single_forwarded_header_multiple_param(): +def test_single_forwarded_header_multiple_param() -> None: header = 'By=identifier1,BY=identifier2, By=identifier3 , BY=identifier4' req = make_mocked_request('GET', '/', headers=CIMultiDict({'Forwarded': header})) @@ -319,15 +340,15 @@ assert req.forwarded[3]['by'] == 'identifier4' -def test_single_forwarded_header_quoted_escaped(): - header = 'BY=identifier;pROTO="\lala lan\d\~ 123\!&"' +def test_single_forwarded_header_quoted_escaped() -> None: + header = r'BY=identifier;pROTO="\lala lan\d\~ 123\!&"' req = make_mocked_request('GET', '/', headers=CIMultiDict({'Forwarded': header})) assert req.forwarded[0]['by'] == 'identifier' assert req.forwarded[0]['proto'] == 'lala land~ 123!&' -def test_single_forwarded_header_custom_param(): +def test_single_forwarded_header_custom_param() -> None: header = r'BY=identifier;PROTO=https;SOME="other, \"value\""' req = make_mocked_request('GET', '/', headers=CIMultiDict({'Forwarded': header})) @@ -337,7 +358,7 @@ assert req.forwarded[0]['some'] == 'other, "value"' -def test_single_forwarded_header_empty_params(): +def test_single_forwarded_header_empty_params() -> None: # This is allowed by the grammar given in RFC 7239 header = ';For=identifier;;PROTO=https;;;' req = make_mocked_request('GET', '/', @@ -346,14 +367,14 @@ assert req.forwarded[0]['proto'] == 'https' -def test_single_forwarded_header_bad_separator(): +def test_single_forwarded_header_bad_separator() -> None: header = 'BY=identifier PROTO=https' req = make_mocked_request('GET', '/', headers=CIMultiDict({'Forwarded': header})) assert 'proto' not in req.forwarded[0] -def test_single_forwarded_header_injection1(): +def test_single_forwarded_header_injection1() -> None: # We might receive a header like this if we're sitting behind a reverse # proxy that blindly appends a forwarded-element without checking # the syntax of existing field-values. We should be able to recover @@ -366,7 +387,7 @@ assert req.forwarded[1]['for'] == '_real' -def test_single_forwarded_header_injection2(): +def test_single_forwarded_header_injection2() -> None: header = 'very bad syntax, for=_real' req = make_mocked_request('GET', '/', headers=CIMultiDict({'Forwarded': header})) @@ -375,14 +396,14 @@ assert req.forwarded[1]['for'] == '_real' -def test_single_forwarded_header_long_quoted_string(): +def test_single_forwarded_header_long_quoted_string() -> None: header = 'for="' + '\\\\' * 5000 + '"' req = make_mocked_request('GET', '/', headers=CIMultiDict({'Forwarded': header})) assert req.forwarded[0]['for'] == '\\' * 5000 -def test_multiple_forwarded_headers(): +def test_multiple_forwarded_headers() -> None: headers = CIMultiDict() headers.add('Forwarded', 'By=identifier1;for=identifier2, BY=identifier3') headers.add('Forwarded', 'By=identifier4;fOr=identifier5') @@ -395,7 +416,7 @@ assert req.forwarded[2]['for'] == 'identifier5' -def test_multiple_forwarded_headers_bad_syntax(): +def test_multiple_forwarded_headers_bad_syntax() -> None: headers = CIMultiDict() headers.add('Forwarded', 'for=_1;by=_2') headers.add('Forwarded', 'invalid value') @@ -409,7 +430,7 @@ assert req.forwarded[3]['by'] == '_4' -def test_multiple_forwarded_headers_injection(): +def test_multiple_forwarded_headers_injection() -> None: headers = CIMultiDict() # This could be sent by an attacker, hoping to "shadow" the second header. headers.add('Forwarded', 'for=_injected;by="') @@ -422,77 +443,77 @@ assert req.forwarded[1]['by'] == '_actual_proxy' -def test_host_by_host_header(): +def test_host_by_host_header() -> None: req = make_mocked_request('GET', '/', headers=CIMultiDict({'Host': 'example.com'})) assert req.host == 'example.com' -def test_raw_headers(): +def test_raw_headers() -> None: req = make_mocked_request('GET', '/', headers=CIMultiDict({'X-HEADER': 'aaa'})) assert req.raw_headers == ((b'X-HEADER', b'aaa'),) -def test_rel_url(): +def test_rel_url() -> None: req = make_mocked_request('GET', '/path') assert URL('/path') == req.rel_url -def test_url_url(): +def test_url_url() -> None: req = make_mocked_request('GET', '/path', headers={'HOST': 'example.com'}) assert URL('http://example.com/path') == req.url -def test_clone(): +def test_clone() -> None: req = make_mocked_request('GET', '/path') req2 = req.clone() assert req2.method == 'GET' assert req2.rel_url == URL('/path') -def test_clone_client_max_size(): +def test_clone_client_max_size() -> None: req = make_mocked_request('GET', '/path', client_max_size=1024) req2 = req.clone() assert req._client_max_size == req2._client_max_size assert req2._client_max_size == 1024 -def test_clone_method(): +def test_clone_method() -> None: req = make_mocked_request('GET', '/path') req2 = req.clone(method='POST') assert req2.method == 'POST' assert req2.rel_url == URL('/path') -def test_clone_rel_url(): +def test_clone_rel_url() -> None: req = make_mocked_request('GET', '/path') req2 = req.clone(rel_url=URL('/path2')) assert req2.rel_url == URL('/path2') -def test_clone_rel_url_str(): +def test_clone_rel_url_str() -> None: req = make_mocked_request('GET', '/path') req2 = req.clone(rel_url='/path2') assert req2.rel_url == URL('/path2') -def test_clone_headers(): +def test_clone_headers() -> None: req = make_mocked_request('GET', '/path', headers={'A': 'B'}) req2 = req.clone(headers=CIMultiDict({'B': 'C'})) assert req2.headers == CIMultiDict({'B': 'C'}) assert req2.raw_headers == ((b'B', b'C'),) -def test_clone_headers_dict(): +def test_clone_headers_dict() -> None: req = make_mocked_request('GET', '/path', headers={'A': 'B'}) req2 = req.clone(headers={'B': 'C'}) assert req2.headers == CIMultiDict({'B': 'C'}) assert req2.raw_headers == ((b'B', b'C'),) -async def test_cannot_clone_after_read(loop, protocol): - payload = StreamReader(protocol, loop=loop) +async def test_cannot_clone_after_read(protocol) -> None: + payload = StreamReader(protocol) payload.feed_data(b'data') payload.feed_eof() req = make_mocked_request('GET', '/path', payload=payload) @@ -501,8 +522,8 @@ req.clone() -async def test_make_too_big_request(loop, protocol): - payload = StreamReader(protocol, loop=loop) +async def test_make_too_big_request(protocol) -> None: + payload = StreamReader(protocol) large_file = 1024 ** 2 * b'x' too_large_file = large_file + b'x' payload.feed_data(too_large_file) @@ -514,8 +535,8 @@ assert err.value.status_code == 413 -async def test_make_too_big_request_adjust_limit(loop, protocol): - payload = StreamReader(protocol, loop=loop) +async def test_make_too_big_request_adjust_limit(protocol) -> None: + payload = StreamReader(protocol) large_file = 1024 ** 2 * b'x' too_large_file = large_file + b'x' payload.feed_data(too_large_file) @@ -527,8 +548,8 @@ assert len(txt) == 1024**2 + 1 -async def test_multipart_formdata(loop, protocol): - payload = StreamReader(protocol, loop=loop) +async def test_multipart_formdata(protocol) -> None: + payload = StreamReader(protocol) payload.feed_data(b"""-----------------------------326931944431359\r Content-Disposition: form-data; name="a"\r \r @@ -548,8 +569,8 @@ assert dict(result) == {'a': 'b', 'c': 'd'} -async def test_make_too_big_request_limit_None(loop, protocol): - payload = StreamReader(protocol, loop=loop) +async def test_make_too_big_request_limit_None(protocol) -> None: + payload = StreamReader(protocol) large_file = 1024 ** 2 * b'x' too_large_file = large_file + b'x' payload.feed_data(too_large_file) @@ -561,21 +582,21 @@ assert len(txt) == 1024**2 + 1 -def test_remote_peername_tcp(): +def test_remote_peername_tcp() -> None: transp = mock.Mock() transp.get_extra_info.return_value = ('10.10.10.10', 1234) req = make_mocked_request('GET', '/', transport=transp) assert req.remote == '10.10.10.10' -def test_remote_peername_unix(): +def test_remote_peername_unix() -> None: transp = mock.Mock() transp.get_extra_info.return_value = '/path/to/sock' req = make_mocked_request('GET', '/', transport=transp) assert req.remote == '/path/to/sock' -def test_save_state_on_clone(): +def test_save_state_on_clone() -> None: req = make_mocked_request('GET', '/') req['key'] = 'val' req2 = req.clone() @@ -584,19 +605,19 @@ assert req2['key'] == 'val2' -def test_clone_scheme(): +def test_clone_scheme() -> None: req = make_mocked_request('GET', '/') req2 = req.clone(scheme='https') assert req2.scheme == 'https' -def test_clone_host(): +def test_clone_host() -> None: req = make_mocked_request('GET', '/') req2 = req.clone(host='example.com') assert req2.host == 'example.com' -def test_clone_remote(): +def test_clone_remote() -> None: req = make_mocked_request('GET', '/') req2 = req.clone(remote='11.11.11.11') assert req2.remote == '11.11.11.11' @@ -604,13 +625,41 @@ @pytest.mark.skipif(not DEBUG, reason="The check is applied in DEBUG mode only") -def test_request_custom_attr(): +def test_request_custom_attr() -> None: req = make_mocked_request('GET', '/') with pytest.warns(DeprecationWarning): req.custom = None -def test_remote_with_closed_transport(): +def test_remote_with_closed_transport() -> None: + transp = mock.Mock() + transp.get_extra_info.return_value = ('10.10.10.10', 1234) + req = make_mocked_request('GET', '/', transport=transp) + req._protocol = None + assert req.remote == '10.10.10.10' + + +def test_url_http_with_closed_transport() -> None: req = make_mocked_request('GET', '/') req._protocol = None - assert req.remote is None + assert str(req.url).startswith('http://') + + +def test_url_https_with_closed_transport() -> None: + req = make_mocked_request('GET', '/', sslcontext=True) + req._protocol = None + assert str(req.url).startswith('https://') + + +def test_eq() -> None: + req1 = make_mocked_request('GET', '/path/to?a=1&b=2') + req2 = make_mocked_request('GET', '/path/to?a=1&b=2') + assert req1 != req2 + assert req1 == req1 + + +async def test_loop_prop() -> None: + loop = asyncio.get_event_loop() + req = make_mocked_request('GET', '/path', loop=loop) + with pytest.warns(DeprecationWarning): + assert req.loop is loop diff -Nru python-aiohttp-3.1.3/tests/test_web_response.py python-aiohttp-3.5.1/tests/test_web_response.py --- python-aiohttp-3.1.3/tests/test_web_response.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_web_response.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,11 +1,13 @@ import collections import datetime +import gzip import json import re +from concurrent.futures import ThreadPoolExecutor from unittest import mock import pytest -from multidict import CIMultiDict +from multidict import CIMultiDict, CIMultiDictProxy from aiohttp import HttpVersion, HttpVersion10, HttpVersion11, hdrs, signals from aiohttp.payload import BytesPayload @@ -46,7 +48,7 @@ buf.extend(chunk) async def write_headers(status_line, headers): - headers = status_line + ''.join( + headers = status_line + '\r\n' + ''.join( [k + ': ' + v + '\r\n' for k, v in headers.items()]) headers = headers.encode('utf-8') + b'\r\n' buf.extend(headers) @@ -65,7 +67,7 @@ return writer -def test_stream_response_ctor(): +def test_stream_response_ctor() -> None: resp = StreamResponse() assert 200 == resp.status assert resp.keep_alive is None @@ -77,52 +79,60 @@ assert resp.task is req.task -def test_stream_response_hashable(): +def test_stream_response_hashable() -> None: # should not raise exception hash(StreamResponse()) -def test_stream_response_is_mutable_mapping(): +def test_stream_response_eq() -> None: + resp1 = StreamResponse() + resp2 = StreamResponse() + + assert resp1 == resp1 + assert not resp1 == resp2 + + +def test_stream_response_is_mutable_mapping() -> None: resp = StreamResponse() assert isinstance(resp, collections.MutableMapping) resp['key'] = 'value' assert 'value' == resp['key'] -def test_stream_response_delitem(): +def test_stream_response_delitem() -> None: resp = StreamResponse() resp['key'] = 'value' del resp['key'] assert 'key' not in resp -def test_stream_response_len(): +def test_stream_response_len() -> None: resp = StreamResponse() assert len(resp) == 0 resp['key'] = 'value' assert len(resp) == 1 -def test_request_iter(): +def test_request_iter() -> None: resp = StreamResponse() resp['key'] = 'value' resp['key2'] = 'value2' assert set(resp) == {'key', 'key2'} -def test_content_length(): +def test_content_length() -> None: resp = StreamResponse() assert resp.content_length is None -def test_content_length_setter(): +def test_content_length_setter() -> None: resp = StreamResponse() resp.content_length = 234 assert 234 == resp.content_length -def test_content_length_setter_with_enable_chunked_encoding(): +def test_content_length_setter_with_enable_chunked_encoding() -> None: resp = StreamResponse() resp.enable_chunked_encoding() @@ -130,7 +140,7 @@ resp.content_length = 234 -def test_drop_content_length_header_on_setting_len_to_None(): +def test_drop_content_length_header_on_setting_len_to_None() -> None: resp = StreamResponse() resp.content_length = 1 @@ -139,7 +149,7 @@ assert 'Content-Length' not in resp.headers -def test_set_content_length_to_None_on_non_set(): +def test_set_content_length_to_None_on_non_set() -> None: resp = StreamResponse() resp.content_length = None @@ -148,14 +158,14 @@ assert 'Content-Length' not in resp.headers -def test_setting_content_type(): +def test_setting_content_type() -> None: resp = StreamResponse() resp.content_type = 'text/html' assert 'text/html' == resp.headers['content-type'] -def test_setting_charset(): +def test_setting_charset() -> None: resp = StreamResponse() resp.content_type = 'text/html' @@ -163,13 +173,13 @@ assert 'text/html; charset=koi8-r' == resp.headers['content-type'] -def test_default_charset(): +def test_default_charset() -> None: resp = StreamResponse() assert resp.charset is None -def test_reset_charset(): +def test_reset_charset() -> None: resp = StreamResponse() resp.content_type = 'text/html' @@ -177,7 +187,7 @@ assert resp.charset is None -def test_reset_charset_after_setting(): +def test_reset_charset_after_setting() -> None: resp = StreamResponse() resp.content_type = 'text/html' @@ -186,19 +196,19 @@ assert resp.charset is None -def test_charset_without_content_type(): +def test_charset_without_content_type() -> None: resp = StreamResponse() with pytest.raises(RuntimeError): resp.charset = 'koi8-r' -def test_last_modified_initial(): +def test_last_modified_initial() -> None: resp = StreamResponse() assert resp.last_modified is None -def test_last_modified_string(): +def test_last_modified_string() -> None: resp = StreamResponse() dt = datetime.datetime(1990, 1, 2, 3, 4, 5, 0, datetime.timezone.utc) @@ -206,7 +216,7 @@ assert resp.last_modified == dt -def test_last_modified_timestamp(): +def test_last_modified_timestamp() -> None: resp = StreamResponse() dt = datetime.datetime(1970, 1, 1, 0, 0, 0, 0, datetime.timezone.utc) @@ -218,7 +228,7 @@ assert resp.last_modified == dt -def test_last_modified_datetime(): +def test_last_modified_datetime() -> None: resp = StreamResponse() dt = datetime.datetime(2001, 2, 3, 4, 5, 6, 0, datetime.timezone.utc) @@ -226,7 +236,7 @@ assert resp.last_modified == dt -def test_last_modified_reset(): +def test_last_modified_reset() -> None: resp = StreamResponse() resp.last_modified = 0 @@ -234,7 +244,7 @@ assert resp.last_modified is None -async def test_start(): +async def test_start() -> None: req = make_request('GET', '/') resp = StreamResponse() assert resp.keep_alive is None @@ -253,7 +263,7 @@ assert msg is msg3 -async def test_chunked_encoding(): +async def test_chunked_encoding() -> None: req = make_request('GET', '/') resp = StreamResponse() assert not resp.chunked @@ -265,7 +275,7 @@ assert msg.chunked -def test_enable_chunked_encoding_with_content_length(): +def test_enable_chunked_encoding_with_content_length() -> None: resp = StreamResponse() resp.content_length = 234 @@ -273,7 +283,7 @@ resp.enable_chunked_encoding() -async def test_chunk_size(): +async def test_chunk_size() -> None: req = make_request('GET', '/') resp = StreamResponse() assert not resp.chunked @@ -288,7 +298,7 @@ assert msg.filter is not None -async def test_chunked_encoding_forbidden_for_http_10(): +async def test_chunked_encoding_forbidden_for_http_10() -> None: req = make_request('GET', '/', version=HttpVersion10) resp = StreamResponse() resp.enable_chunked_encoding() @@ -299,7 +309,7 @@ str(ctx.value)) -async def test_compression_no_accept(): +async def test_compression_no_accept() -> None: req = make_request('GET', '/') resp = StreamResponse() assert not resp.chunked @@ -312,13 +322,14 @@ assert not msg.enable_compression.called -async def test_force_compression_no_accept_backwards_compat(): +async def test_force_compression_no_accept_backwards_compat() -> None: req = make_request('GET', '/') resp = StreamResponse() assert not resp.chunked assert not resp.compression - resp.enable_compression(force=True) + with pytest.warns(DeprecationWarning): + resp.enable_compression(force=True) assert resp.compression msg = await resp.prepare(req) @@ -326,19 +337,20 @@ assert msg.filter is not None -async def test_force_compression_false_backwards_compat(): +async def test_force_compression_false_backwards_compat() -> None: req = make_request('GET', '/') resp = StreamResponse() assert not resp.compression - resp.enable_compression(force=False) + with pytest.warns(DeprecationWarning): + resp.enable_compression(force=False) assert resp.compression msg = await resp.prepare(req) assert not msg.enable_compression.called -async def test_compression_default_coding(): +async def test_compression_default_coding() -> None: req = make_request( 'GET', '/', headers=CIMultiDict({hdrs.ACCEPT_ENCODING: 'gzip, deflate'})) @@ -356,7 +368,7 @@ assert msg.filter is not None -async def test_force_compression_deflate(): +async def test_force_compression_deflate() -> None: req = make_request( 'GET', '/', headers=CIMultiDict({hdrs.ACCEPT_ENCODING: 'gzip, deflate'})) @@ -370,7 +382,7 @@ assert 'deflate' == resp.headers.get(hdrs.CONTENT_ENCODING) -async def test_force_compression_no_accept_deflate(): +async def test_force_compression_no_accept_deflate() -> None: req = make_request('GET', '/') resp = StreamResponse() @@ -382,7 +394,7 @@ assert 'deflate' == resp.headers.get(hdrs.CONTENT_ENCODING) -async def test_force_compression_gzip(): +async def test_force_compression_gzip() -> None: req = make_request( 'GET', '/', headers=CIMultiDict({hdrs.ACCEPT_ENCODING: 'gzip, deflate'})) @@ -396,7 +408,7 @@ assert 'gzip' == resp.headers.get(hdrs.CONTENT_ENCODING) -async def test_force_compression_no_accept_gzip(): +async def test_force_compression_no_accept_gzip() -> None: req = make_request('GET', '/') resp = StreamResponse() @@ -408,7 +420,33 @@ assert 'gzip' == resp.headers.get(hdrs.CONTENT_ENCODING) -async def test_change_content_length_if_compression_enabled(): +async def test_change_content_threaded_compression_enabled() -> None: + req = make_request('GET', '/') + body_thread_size = 1024 + body = b'answer' * body_thread_size + resp = Response(body=body, + zlib_executor_size=body_thread_size) + resp.enable_compression(ContentCoding.gzip) + + await resp.prepare(req) + assert gzip.decompress(resp._compressed_body) == body + + +async def test_change_content_threaded_compression_enabled_explicit() -> None: + req = make_request('GET', '/') + body_thread_size = 1024 + body = b'answer' * body_thread_size + with ThreadPoolExecutor(1) as executor: + resp = Response(body=body, + zlib_executor_size=body_thread_size, + zlib_executor=executor) + resp.enable_compression(ContentCoding.gzip) + + await resp.prepare(req) + assert gzip.decompress(resp._compressed_body) == body + + +async def test_change_content_length_if_compression_enabled() -> None: req = make_request('GET', '/') resp = Response(body=b'answer') resp.enable_compression(ContentCoding.gzip) @@ -418,7 +456,7 @@ resp.content_length != len(b'answer') -async def test_set_content_length_if_compression_enabled(): +async def test_set_content_length_if_compression_enabled() -> None: writer = mock.Mock() async def write_headers(status_line, headers): @@ -437,7 +475,7 @@ assert resp.content_length == 26 -async def test_remove_content_length_if_compression_enabled_http11(): +async def test_remove_content_length_if_compression_enabled_http11() -> None: writer = mock.Mock() async def write_headers(status_line, headers): @@ -453,7 +491,7 @@ assert resp.content_length is None -async def test_remove_content_length_if_compression_enabled_http10(): +async def test_remove_content_length_if_compression_enabled_http10() -> None: writer = mock.Mock() async def write_headers(status_line, headers): @@ -470,7 +508,7 @@ assert resp.content_length is None -async def test_force_compression_identity(): +async def test_force_compression_identity() -> None: writer = mock.Mock() async def write_headers(status_line, headers): @@ -487,7 +525,7 @@ assert resp.content_length == 123 -async def test_force_compression_identity_response(): +async def test_force_compression_identity_response() -> None: writer = mock.Mock() async def write_headers(status_line, headers): @@ -503,7 +541,7 @@ assert resp.content_length == 6 -async def test_rm_content_length_if_compression_enabled_on_payload_http11(): +async def test_rm_content_length_if_compression_http11() -> None: writer = mock.Mock() async def write_headers(status_line, headers): @@ -521,7 +559,7 @@ assert resp.content_length is None -async def test_rm_content_length_if_compression_enabled_on_payload_http10(): +async def test_rm_content_length_if_compression_http10() -> None: writer = mock.Mock() async def write_headers(status_line, headers): @@ -537,7 +575,7 @@ assert resp.content_length is None -async def test_content_length_on_chunked(): +async def test_content_length_on_chunked() -> None: req = make_request('GET', '/') resp = Response(body=b'answer') assert resp.content_length == 6 @@ -546,7 +584,7 @@ await resp.prepare(req) -async def test_write_non_byteish(): +async def test_write_non_byteish() -> None: resp = StreamResponse() await resp.prepare(make_request('GET', '/')) @@ -554,14 +592,14 @@ await resp.write(123) -async def test_write_before_start(): +async def test_write_before_start() -> None: resp = StreamResponse() with pytest.raises(RuntimeError): await resp.write(b'data') -async def test_cannot_write_after_eof(): +async def test_cannot_write_after_eof() -> None: resp = StreamResponse() req = make_request('GET', '/') await resp.prepare(req) @@ -575,7 +613,7 @@ assert not req.writer.write.called -async def test___repr___after_eof(): +async def test___repr___after_eof() -> None: resp = StreamResponse() await resp.prepare(make_request('GET', '/')) @@ -588,14 +626,14 @@ assert resp_repr == '' -async def test_cannot_write_eof_before_headers(): +async def test_cannot_write_eof_before_headers() -> None: resp = StreamResponse() with pytest.raises(AssertionError): await resp.write_eof() -async def test_cannot_write_eof_twice(): +async def test_cannot_write_eof_twice() -> None: resp = StreamResponse() writer = mock.Mock() resp_impl = await resp.prepare(make_request('GET', '/')) @@ -612,7 +650,7 @@ assert not writer.write.called -def test_force_close(): +def test_force_close() -> None: resp = StreamResponse() assert resp.keep_alive is None @@ -620,14 +658,14 @@ assert resp.keep_alive is False -async def test_response_output_length(): +async def test_response_output_length() -> None: resp = StreamResponse() await resp.prepare(make_request('GET', '/')) with pytest.warns(DeprecationWarning): assert resp.output_length -def test_response_cookies(): +def test_response_cookies() -> None: resp = StreamResponse() assert resp.cookies == {} @@ -653,7 +691,7 @@ assert str(resp.cookies) == expected -def test_response_cookie_path(): +def test_response_cookie_path() -> None: resp = StreamResponse() assert resp.cookies == {} @@ -676,7 +714,7 @@ 'version=2.0') -def test_response_cookie__issue_del_cookie(): +def test_response_cookie__issue_del_cookie() -> None: resp = StreamResponse() assert resp.cookies == {} @@ -688,7 +726,7 @@ assert re.match(expected, str(resp.cookies)) -def test_cookie_set_after_del(): +def test_cookie_set_after_del() -> None: resp = StreamResponse() resp.del_cookie('name') @@ -698,7 +736,7 @@ assert str(resp.cookies) == expected -def test_set_status_with_reason(): +def test_set_status_with_reason() -> None: resp = StreamResponse() resp.set_status(200, "Everithing is fine!") @@ -706,7 +744,7 @@ assert "Everithing is fine!" == resp.reason -async def test_start_force_close(): +async def test_start_force_close() -> None: req = make_request('GET', '/') resp = StreamResponse() resp.force_close() @@ -716,26 +754,26 @@ assert not resp.keep_alive -async def test___repr__(): +async def test___repr__() -> None: req = make_request('GET', '/path/to') resp = StreamResponse(reason=301) await resp.prepare(req) assert "" == repr(resp) -def test___repr___not_prepared(): +def test___repr___not_prepared() -> None: resp = StreamResponse(reason=301) assert "" == repr(resp) -async def test_keep_alive_http10_default(): +async def test_keep_alive_http10_default() -> None: req = make_request('GET', '/', version=HttpVersion10) resp = StreamResponse() await resp.prepare(req) assert not resp.keep_alive -async def test_keep_alive_http10_switched_on(): +async def test_keep_alive_http10_switched_on() -> None: headers = CIMultiDict(Connection='keep-alive') req = make_request('GET', '/', version=HttpVersion10, headers=headers) req._message = req._message._replace(should_close=False) @@ -744,7 +782,7 @@ assert resp.keep_alive -async def test_keep_alive_http09(): +async def test_keep_alive_http09() -> None: headers = CIMultiDict(Connection='keep-alive') req = make_request('GET', '/', version=HttpVersion(0, 9), headers=headers) resp = StreamResponse() @@ -752,7 +790,7 @@ assert not resp.keep_alive -async def test_prepare_twice(): +async def test_prepare_twice() -> None: req = make_request('GET', '/') resp = StreamResponse() @@ -761,7 +799,7 @@ assert impl1 is impl2 -async def test_prepare_calls_signal(): +async def test_prepare_calls_signal() -> None: app = mock.Mock() sig = make_mocked_coro() on_response_prepare = signals.Signal(app) @@ -778,7 +816,7 @@ # Response class -def test_response_ctor(): +def test_response_ctor() -> None: resp = Response() assert 200 == resp.status @@ -788,7 +826,7 @@ assert 'CONTENT-LENGTH' not in resp.headers -async def test_ctor_with_headers_and_status(): +async def test_ctor_with_headers_and_status() -> None: resp = Response(body=b'body', status=201, headers={'Age': '12', 'DATE': 'date'}) @@ -802,7 +840,7 @@ assert resp.headers['CONTENT-LENGTH'] == '4' -def test_ctor_content_type(): +def test_ctor_content_type() -> None: resp = Response(content_type='application/json') assert 200 == resp.status @@ -812,12 +850,12 @@ resp.headers) -def test_ctor_text_body_combined(): +def test_ctor_text_body_combined() -> None: with pytest.raises(ValueError): Response(body=b'123', text='test text') -async def test_ctor_text(): +async def test_ctor_text() -> None: resp = Response(text='test text') assert 200 == resp.status @@ -835,31 +873,31 @@ assert resp.headers['CONTENT-LENGTH'] == '9' -def test_ctor_charset(): +def test_ctor_charset() -> None: resp = Response(text='текст', charset='koi8-r') assert 'текст'.encode('koi8-r') == resp.body assert 'koi8-r' == resp.charset -def test_ctor_charset_default_utf8(): +def test_ctor_charset_default_utf8() -> None: resp = Response(text='test test', charset=None) assert 'utf-8' == resp.charset -def test_ctor_charset_in_content_type(): +def test_ctor_charset_in_content_type() -> None: with pytest.raises(ValueError): Response(text='test test', content_type='text/plain; charset=utf-8') -def test_ctor_charset_without_text(): +def test_ctor_charset_without_text() -> None: resp = Response(content_type='text/plain', charset='koi8-r') assert 'koi8-r' == resp.charset -def test_ctor_content_type_with_extra(): +def test_ctor_content_type_with_extra() -> None: resp = Response(text='test test', content_type='text/plain; version=0.0.4') assert resp.content_type == 'text/plain' @@ -867,31 +905,31 @@ 'text/plain; version=0.0.4; charset=utf-8' -def test_ctor_both_content_type_param_and_header_with_text(): +def test_ctor_both_content_type_param_and_header_with_text() -> None: with pytest.raises(ValueError): Response(headers={'Content-Type': 'application/json'}, content_type='text/html', text='text') -def test_ctor_both_charset_param_and_header_with_text(): +def test_ctor_both_charset_param_and_header_with_text() -> None: with pytest.raises(ValueError): Response(headers={'Content-Type': 'application/json'}, charset='koi8-r', text='text') -def test_ctor_both_content_type_param_and_header(): +def test_ctor_both_content_type_param_and_header() -> None: with pytest.raises(ValueError): Response(headers={'Content-Type': 'application/json'}, content_type='text/html') -def test_ctor_both_charset_param_and_header(): +def test_ctor_both_charset_param_and_header() -> None: with pytest.raises(ValueError): Response(headers={'Content-Type': 'application/json'}, charset='koi8-r') -async def test_assign_nonbyteish_body(): +async def test_assign_nonbyteish_body() -> None: resp = Response(body=b'data') with pytest.raises(ValueError): @@ -906,7 +944,7 @@ assert 4 == resp.content_length -def test_assign_nonstr_text(): +def test_assign_nonstr_text() -> None: resp = Response(text='test') with pytest.raises(AssertionError): @@ -915,13 +953,13 @@ assert 4 == resp.content_length -def test_response_set_content_length(): +def test_response_set_content_length() -> None: resp = Response() with pytest.raises(RuntimeError): resp.content_length = 1 -async def test_send_headers_for_empty_body(buf, writer): +async def test_send_headers_for_empty_body(buf, writer) -> None: req = make_request('GET', '/', writer=writer) resp = Response() @@ -935,7 +973,7 @@ 'Server: .+\r\n\r\n', txt) -async def test_render_with_body(buf, writer): +async def test_render_with_body(buf, writer) -> None: req = make_request('GET', '/', writer=writer) resp = Response(body=b'data') @@ -951,7 +989,7 @@ 'data', txt) -async def test_send_set_cookie_header(buf, writer): +async def test_send_set_cookie_header(buf, writer) -> None: resp = Response() resp.cookies['name'] = 'value' req = make_request('GET', '/', writer=writer) @@ -968,7 +1006,7 @@ 'Server: .+\r\n\r\n', txt) -async def test_consecutive_write_eof(): +async def test_consecutive_write_eof() -> None: writer = mock.Mock() writer.write_eof = make_mocked_coro() writer.write_headers = make_mocked_coro() @@ -982,7 +1020,7 @@ writer.write_eof.assert_called_once_with(data) -def test_set_text_with_content_type(): +def test_set_text_with_content_type() -> None: resp = Response() resp.content_type = "text/html" resp.text = "text" @@ -992,7 +1030,7 @@ assert "text/html" == resp.content_type -def test_set_text_with_charset(): +def test_set_text_with_charset() -> None: resp = Response() resp.content_type = 'text/plain' resp.charset = "KOI8-R" @@ -1003,62 +1041,62 @@ assert "koi8-r" == resp.charset -def test_default_content_type_in_stream_response(): +def test_default_content_type_in_stream_response() -> None: resp = StreamResponse() assert resp.content_type == 'application/octet-stream' -def test_default_content_type_in_response(): +def test_default_content_type_in_response() -> None: resp = Response() assert resp.content_type == 'application/octet-stream' -def test_content_type_with_set_text(): +def test_content_type_with_set_text() -> None: resp = Response(text='text') assert resp.content_type == 'text/plain' -def test_content_type_with_set_body(): +def test_content_type_with_set_body() -> None: resp = Response(body=b'body') assert resp.content_type == 'application/octet-stream' -def test_started_when_not_started(): +def test_started_when_not_started() -> None: resp = StreamResponse() assert not resp.prepared -async def test_started_when_started(): +async def test_started_when_started() -> None: resp = StreamResponse() await resp.prepare(make_request('GET', '/')) assert resp.prepared -async def test_drain_before_start(): +async def test_drain_before_start() -> None: resp = StreamResponse() with pytest.raises(AssertionError): await resp.drain() -async def test_changing_status_after_prepare_raises(): +async def test_changing_status_after_prepare_raises() -> None: resp = StreamResponse() await resp.prepare(make_request('GET', '/')) with pytest.raises(AssertionError): resp.set_status(400) -def test_nonstr_text_in_ctor(): +def test_nonstr_text_in_ctor() -> None: with pytest.raises(TypeError): Response(text=b'data') -def test_text_in_ctor_with_content_type(): +def test_text_in_ctor_with_content_type() -> None: resp = Response(text='data', content_type='text/html') assert 'data' == resp.text assert 'text/html' == resp.content_type -def test_text_in_ctor_with_content_type_header(): +def test_text_in_ctor_with_content_type_header() -> None: resp = Response(text='текст', headers={'Content-Type': 'text/html; charset=koi8-r'}) assert 'текст'.encode('koi8-r') == resp.body @@ -1066,7 +1104,7 @@ assert 'koi8-r' == resp.charset -def test_text_in_ctor_with_content_type_header_multidict(): +def test_text_in_ctor_with_content_type_header_multidict() -> None: headers = CIMultiDict({'Content-Type': 'text/html; charset=koi8-r'}) resp = Response(text='текст', headers=headers) @@ -1075,7 +1113,7 @@ assert 'koi8-r' == resp.charset -def test_body_in_ctor_with_content_type_header_multidict(): +def test_body_in_ctor_with_content_type_header_multidict() -> None: headers = CIMultiDict({'Content-Type': 'text/html; charset=koi8-r'}) resp = Response(body='текст'.encode('koi8-r'), headers=headers) @@ -1084,28 +1122,35 @@ assert 'koi8-r' == resp.charset -def test_text_with_empty_payload(): +def test_text_with_empty_payload() -> None: resp = Response(status=200) assert resp.body is None assert resp.text is None -def test_response_with_content_length_header_without_body(): +def test_response_with_content_length_header_without_body() -> None: resp = Response(headers={'Content-Length': 123}) assert resp.content_length == 123 +def test_response_with_immutable_headers() -> None: + resp = Response(text='text', + headers=CIMultiDictProxy(CIMultiDict({'Header': 'Value'}))) + assert resp.headers == {'Header': 'Value', + 'Content-Type': 'text/plain; charset=utf-8'} + + class TestJSONResponse: - def test_content_type_is_application_json_by_default(self): + def test_content_type_is_application_json_by_default(self) -> None: resp = json_response('') assert 'application/json' == resp.content_type - def test_passing_text_only(self): + def test_passing_text_only(self) -> None: resp = json_response(text=json.dumps('jaysawn')) assert resp.text == json.dumps('jaysawn') - def test_data_and_text_raises_value_error(self): + def test_data_and_text_raises_value_error(self) -> None: with pytest.raises(ValueError) as excinfo: json_response(data='foo', text='bar') expected_message = ( @@ -1113,7 +1158,7 @@ ) assert expected_message == excinfo.value.args[0] - def test_data_and_body_raises_value_error(self): + def test_data_and_body_raises_value_error(self) -> None: with pytest.raises(ValueError) as excinfo: json_response(data='foo', body=b'bar') expected_message = ( @@ -1121,11 +1166,11 @@ ) assert expected_message == excinfo.value.args[0] - def test_text_is_json_encoded(self): + def test_text_is_json_encoded(self) -> None: resp = json_response({'foo': 42}) assert json.dumps({'foo': 42}) == resp.text - def test_content_type_is_overrideable(self): + def test_content_type_is_overrideable(self) -> None: resp = json_response({'foo': 42}, content_type='application/vnd.json+api') assert 'application/vnd.json+api' == resp.content_type diff -Nru python-aiohttp-3.1.3/tests/test_web_runner.py python-aiohttp-3.5.1/tests/test_web_runner.py --- python-aiohttp-3.1.3/tests/test_web_runner.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_web_runner.py 2018-12-24 20:58:54.000000000 +0000 @@ -5,6 +5,7 @@ import pytest from aiohttp import web +from aiohttp.test_utils import get_unused_port_socket @pytest.fixture @@ -26,7 +27,7 @@ loop.run_until_complete(runner.cleanup()) -async def test_site_for_nonfrozen_app(make_runner): +async def test_site_for_nonfrozen_app(make_runner) -> None: runner = make_runner() with pytest.raises(RuntimeError): web.TCPSite(runner) @@ -35,7 +36,7 @@ @pytest.mark.skipif(platform.system() == "Windows", reason="the test is not valid for Windows") -async def test_runner_setup_handle_signals(make_runner): +async def test_runner_setup_handle_signals(make_runner) -> None: runner = make_runner(handle_signals=True) await runner.setup() assert signal.getsignal(signal.SIGTERM) is not signal.SIG_DFL @@ -45,7 +46,7 @@ @pytest.mark.skipif(platform.system() == "Windows", reason="the test is not valid for Windows") -async def test_runner_setup_without_signal_handling(make_runner): +async def test_runner_setup_without_signal_handling(make_runner) -> None: runner = make_runner(handle_signals=False) await runner.setup() assert signal.getsignal(signal.SIGTERM) is signal.SIG_DFL @@ -53,10 +54,11 @@ assert signal.getsignal(signal.SIGTERM) is signal.SIG_DFL -async def test_site_double_added(make_runner): +async def test_site_double_added(make_runner) -> None: + _sock = get_unused_port_socket('127.0.0.1') runner = make_runner() await runner.setup() - site = web.TCPSite(runner) + site = web.SockSite(runner, _sock) await site.start() with pytest.raises(RuntimeError): await site.start() @@ -64,7 +66,7 @@ assert len(runner.sites) == 1 -async def test_site_stop_not_started(make_runner): +async def test_site_stop_not_started(make_runner) -> None: runner = make_runner() await runner.setup() site = web.TCPSite(runner) @@ -74,13 +76,13 @@ assert len(runner.sites) == 0 -async def test_custom_log_format(make_runner): +async def test_custom_log_format(make_runner) -> None: runner = make_runner(access_log_format='abc') await runner.setup() assert runner.server._kwargs['access_log_format'] == 'abc' -async def test_unreg_site(make_runner): +async def test_unreg_site(make_runner) -> None: runner = make_runner() await runner.setup() site = web.TCPSite(runner) @@ -88,11 +90,27 @@ runner._unreg_site(site) -async def test_app_property(make_runner, app): +async def test_app_property(make_runner, app) -> None: runner = make_runner() assert runner.app is app -def test_non_app(): +def test_non_app() -> None: with pytest.raises(TypeError): web.AppRunner(object()) + + +@pytest.mark.skipif(platform.system() == "Windows", + reason="Unix socket support is required") +async def test_addresses(make_runner, shorttmpdir) -> None: + _sock = get_unused_port_socket('127.0.0.1') + runner = make_runner() + await runner.setup() + tcp = web.SockSite(runner, _sock) + await tcp.start() + path = str(shorttmpdir / 'tmp.sock') + unix = web.UnixSite(runner, path) + await unix.start() + actual_addrs = runner.addresses + expected_host, expected_post = _sock.getsockname()[:2] + assert actual_addrs == [(expected_host, expected_post), path] diff -Nru python-aiohttp-3.1.3/tests/test_web_sendfile_functional.py python-aiohttp-3.5.1/tests/test_web_sendfile_functional.py --- python-aiohttp-3.1.3/tests/test_web_sendfile_functional.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_web_sendfile_functional.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,6 +1,8 @@ import asyncio import os import pathlib +import socket +import zlib import pytest @@ -11,7 +13,7 @@ try: import ssl except ImportError: - ssl = False + ssl = None # type: ignore @pytest.fixture(params=['sendfile', 'fallback'], ids=['sendfile', 'fallback']) @@ -24,7 +26,7 @@ return maker -async def test_static_file_ok(aiohttp_client, sender): +async def test_static_file_ok(aiohttp_client, sender) -> None: filepath = pathlib.Path(__file__).parent / 'data.unknown_mime_type' async def handler(request): @@ -43,7 +45,7 @@ await resp.release() -async def test_static_file_ok_string_path(aiohttp_client, sender): +async def test_static_file_ok_string_path(aiohttp_client, sender) -> None: filepath = pathlib.Path(__file__).parent / 'data.unknown_mime_type' async def handler(request): @@ -62,7 +64,7 @@ await resp.release() -async def test_static_file_not_exists(aiohttp_client): +async def test_static_file_not_exists(aiohttp_client) -> None: app = web.Application() client = await aiohttp_client(app) @@ -72,7 +74,7 @@ await resp.release() -async def test_static_file_name_too_long(aiohttp_client): +async def test_static_file_name_too_long(aiohttp_client) -> None: app = web.Application() client = await aiohttp_client(app) @@ -82,7 +84,7 @@ await resp.release() -async def test_static_file_upper_directory(aiohttp_client): +async def test_static_file_upper_directory(aiohttp_client) -> None: app = web.Application() client = await aiohttp_client(app) @@ -92,7 +94,7 @@ await resp.release() -async def test_static_file_with_content_type(aiohttp_client, sender): +async def test_static_file_with_content_type(aiohttp_client, sender) -> None: filepath = (pathlib.Path(__file__).parent / 'aiohttp.jpg') async def handler(request): @@ -113,7 +115,7 @@ resp.close() -async def test_static_file_custom_content_type(aiohttp_client, sender): +async def test_static_file_custom_content_type(aiohttp_client, sender) -> None: filepath = (pathlib.Path(__file__).parent / 'hello.txt.gz') async def handler(request): @@ -158,7 +160,8 @@ resp.close() -async def test_static_file_with_content_encoding(aiohttp_client, sender): +async def test_static_file_with_content_encoding(aiohttp_client, + sender) -> None: filepath = pathlib.Path(__file__).parent / 'hello.txt.gz' async def handler(request): @@ -179,7 +182,7 @@ resp.close() -async def test_static_file_if_modified_since(aiohttp_client, sender): +async def test_static_file_if_modified_since(aiohttp_client, sender) -> None: filename = 'data.unknown_mime_type' filepath = pathlib.Path(__file__).parent / filename @@ -204,7 +207,8 @@ resp.close() -async def test_static_file_if_modified_since_past_date(aiohttp_client, sender): +async def test_static_file_if_modified_since_past_date(aiohttp_client, + sender) -> None: filename = 'data.unknown_mime_type' filepath = pathlib.Path(__file__).parent / filename @@ -264,7 +268,7 @@ @pytest.mark.skipif(not ssl, reason="ssl not supported") -async def test_static_file_ssl(aiohttp_server, aiohttp_client): +async def test_static_file_ssl(aiohttp_server, aiohttp_client) -> None: dirname = os.path.dirname(__file__) filename = 'data.unknown_mime_type' ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) @@ -287,7 +291,7 @@ assert resp.headers.get('CONTENT-ENCODING') is None -async def test_static_file_directory_traversal_attack(loop, aiohttp_client): +async def test_static_file_directory_traversal_attack(aiohttp_client) -> None: dirname = os.path.dirname(__file__) relpath = '../README.rst' assert os.path.isfile(os.path.join(dirname, relpath)) @@ -309,7 +313,7 @@ assert 403 == resp.status -def test_static_route_path_existence_check(): +def test_static_route_path_existence_check() -> None: directory = os.path.dirname(__file__) web.StaticResource("/", directory) @@ -318,10 +322,10 @@ web.StaticResource("/", nodirectory) -async def test_static_file_huge(loop, aiohttp_client, tmpdir): +async def test_static_file_huge(aiohttp_client, tmpdir) -> None: filename = 'huge_data.unknown_mime_type' - # fill 100MB file + # fill 20MB file with tmpdir.join(filename).open('w') as f: for i in range(1024*20): f.write(chr(i % 64 + 0x20) * 1024) @@ -351,7 +355,7 @@ f.close() -async def test_static_file_range(loop, aiohttp_client, sender): +async def test_static_file_range(aiohttp_client, sender) -> None: filepath = (pathlib.Path(__file__).parent.parent / 'LICENSE.txt') filesize = filepath.stat().st_size @@ -361,7 +365,7 @@ app = web.Application() app.router.add_get('/', handler) - client = await aiohttp_client(lambda loop: app) + client = await aiohttp_client(app) with filepath.open('rb') as f: content = f.read() @@ -371,7 +375,6 @@ client.get('/', headers={'Range': 'bytes=0-999'}), client.get('/', headers={'Range': 'bytes=1000-1999'}), client.get('/', headers={'Range': 'bytes=2000-'}), - loop=loop ) assert len(responses) == 3 assert responses[0].status == 206, \ @@ -390,7 +393,6 @@ body = await asyncio.gather( *(resp.read() for resp in responses), - loop=loop ) assert len(body[0]) == 1000, \ @@ -405,7 +407,6 @@ async def test_static_file_range_end_bigger_than_size( - loop, aiohttp_client, sender ): @@ -416,28 +417,28 @@ app = web.Application() app.router.add_get('/', handler) - client = await aiohttp_client(lambda loop: app) + client = await aiohttp_client(app) with filepath.open('rb') as f: content = f.read() # Ensure the whole file requested in parts is correct response = await client.get( - '/', headers={'Range': 'bytes=61000-62000'}) + '/', headers={'Range': 'bytes=54000-55000'}) assert response.status == 206, \ - "failed 'bytes=61000-62000': %s" % response.reason + "failed 'bytes=54000-55000': %s" % response.reason assert response.headers['Content-Range'] == \ - 'bytes 61000-61107/61108', 'failed: Content-Range Error' + 'bytes 54000-54996/54997', 'failed: Content-Range Error' body = await response.read() - assert len(body) == 108, \ - "failed 'bytes=61000-62000', received %d bytes" % len(body) + assert len(body) == 997, \ + "failed 'bytes=54000-55000', received %d bytes" % len(body) - assert content[61000:] == body + assert content[54000:] == body -async def test_static_file_range_beyond_eof(loop, aiohttp_client, sender): +async def test_static_file_range_beyond_eof(aiohttp_client, sender) -> None: filepath = (pathlib.Path(__file__).parent / 'aiohttp.png') async def handler(request): @@ -445,7 +446,7 @@ app = web.Application() app.router.add_get('/', handler) - client = await aiohttp_client(lambda loop: app) + client = await aiohttp_client(app) # Ensure the whole file requested in parts is correct response = await client.get( @@ -455,7 +456,7 @@ "failed 'bytes=1000000-1200000': %s" % response.reason -async def test_static_file_range_tail(loop, aiohttp_client, sender): +async def test_static_file_range_tail(aiohttp_client, sender) -> None: filepath = (pathlib.Path(__file__).parent / 'aiohttp.png') async def handler(request): @@ -463,7 +464,7 @@ app = web.Application() app.router.add_get('/', handler) - client = await aiohttp_client(lambda loop: app) + client = await aiohttp_client(app) with filepath.open('rb') as f: content = f.read() @@ -471,7 +472,7 @@ # Ensure the tail of the file is correct resp = await client.get('/', headers={'Range': 'bytes=-500'}) assert resp.status == 206, resp.reason - assert resp.headers['Content-Range'] == 'bytes 60608-61107/61108', \ + assert resp.headers['Content-Range'] == 'bytes 54497-54996/54997', \ 'failed: Content-Range Error' body4 = await resp.read() resp.close() @@ -480,11 +481,11 @@ # Ensure out-of-range tails could be handled resp2 = await client.get('/', headers={'Range': 'bytes=-99999999999999'}) assert resp2.status == 206, resp.reason - assert resp2.headers['Content-Range'] == 'bytes 0-61107/61108', \ + assert resp2.headers['Content-Range'] == 'bytes 0-54996/54997', \ 'failed: Content-Range Error' -async def test_static_file_invalid_range(loop, aiohttp_client, sender): +async def test_static_file_invalid_range(aiohttp_client, sender) -> None: filepath = (pathlib.Path(__file__).parent / 'aiohttp.png') async def handler(request): @@ -492,7 +493,7 @@ app = web.Application() app.router.add_get('/', handler) - client = await aiohttp_client(lambda loop: app) + client = await aiohttp_client(app) # range must be in bytes resp = await client.get('/', headers={'Range': 'blocks=0-10'}) @@ -729,3 +730,90 @@ resp = await client.get('/', headers={'If-Range': lastmod}) assert 200 == resp.status resp.close() + + +async def test_static_file_compression(aiohttp_client, sender) -> None: + filepath = pathlib.Path(__file__).parent / 'data.unknown_mime_type' + + async def handler(request): + ret = sender(filepath) + ret.enable_compression() + return ret + + app = web.Application() + app.router.add_get('/', handler) + client = await aiohttp_client(app, auto_decompress=False) + + resp = await client.get('/') + assert resp.status == 200 + zcomp = zlib.compressobj(wbits=-zlib.MAX_WBITS) + expected_body = zcomp.compress(b'file content\n') + zcomp.flush() + assert expected_body == await resp.read() + assert 'application/octet-stream' == resp.headers['Content-Type'] + assert resp.headers.get('Content-Encoding') == 'deflate' + await resp.release() + + +async def test_static_file_huge_cancel(aiohttp_client, tmpdir) -> None: + filename = 'huge_data.unknown_mime_type' + + # fill 100MB file + with tmpdir.join(filename).open('w') as f: + for i in range(1024*20): + f.write(chr(i % 64 + 0x20) * 1024) + + task = None + + async def handler(request): + nonlocal task + task = request.task + # reduce send buffer size + tr = request.transport + sock = tr.get_extra_info('socket') + sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1024) + ret = web.FileResponse(pathlib.Path(str(tmpdir.join(filename)))) + return ret + + app = web.Application() + + app.router.add_get('/', handler) + client = await aiohttp_client(app) + + resp = await client.get('/') + assert resp.status == 200 + task.cancel() + await asyncio.sleep(0) + data = b'' + while True: + try: + data += await resp.content.read(1024) + except aiohttp.ClientPayloadError: + break + assert len(data) < 1024 * 1024 * 20 + + +async def test_static_file_huge_error(aiohttp_client, tmpdir) -> None: + filename = 'huge_data.unknown_mime_type' + + # fill 20MB file + with tmpdir.join(filename).open('wb') as f: + f.seek(20*1024*1024) + f.write(b'1') + + async def handler(request): + # reduce send buffer size + tr = request.transport + sock = tr.get_extra_info('socket') + sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 1024) + ret = web.FileResponse(pathlib.Path(str(tmpdir.join(filename)))) + return ret + + app = web.Application() + + app.router.add_get('/', handler) + client = await aiohttp_client(app) + + resp = await client.get('/') + assert resp.status == 200 + # raise an exception on server side + resp.close() diff -Nru python-aiohttp-3.1.3/tests/test_web_sendfile.py python-aiohttp-3.5.1/tests/test_web_sendfile.py --- python-aiohttp-3.1.3/tests/test_web_sendfile.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_web_sendfile.py 2018-12-24 20:58:54.000000000 +0000 @@ -2,76 +2,10 @@ from aiohttp import hdrs from aiohttp.test_utils import make_mocked_coro, make_mocked_request -from aiohttp.web_fileresponse import FileResponse, SendfileStreamWriter +from aiohttp.web_fileresponse import FileResponse -def test_static_handle_eof(loop): - fake_loop = mock.Mock() - with mock.patch('aiohttp.web_fileresponse.os') as m_os: - out_fd = 30 - in_fd = 31 - fut = loop.create_future() - m_os.sendfile.return_value = 0 - writer = SendfileStreamWriter(mock.Mock(), mock.Mock(), fake_loop) - writer._sendfile_cb(fut, out_fd, in_fd, 0, 100, fake_loop, False) - m_os.sendfile.assert_called_with(out_fd, in_fd, 0, 100) - assert fut.done() - assert fut.result() is None - assert not fake_loop.add_writer.called - assert not fake_loop.remove_writer.called - - -def test_static_handle_again(loop): - fake_loop = mock.Mock() - with mock.patch('aiohttp.web_fileresponse.os') as m_os: - out_fd = 30 - in_fd = 31 - fut = loop.create_future() - m_os.sendfile.side_effect = BlockingIOError() - writer = SendfileStreamWriter(mock.Mock(), mock.Mock(), fake_loop) - writer._sendfile_cb(fut, out_fd, in_fd, 0, 100, fake_loop, False) - m_os.sendfile.assert_called_with(out_fd, in_fd, 0, 100) - assert not fut.done() - fake_loop.add_writer.assert_called_with(out_fd, - writer._sendfile_cb, - fut, out_fd, in_fd, 0, 100, - fake_loop, True) - assert not fake_loop.remove_writer.called - - -def test_static_handle_exception(loop): - fake_loop = mock.Mock() - with mock.patch('aiohttp.web_fileresponse.os') as m_os: - out_fd = 30 - in_fd = 31 - fut = loop.create_future() - exc = OSError() - m_os.sendfile.side_effect = exc - writer = SendfileStreamWriter(mock.Mock(), mock.Mock(), fake_loop) - writer._sendfile_cb(fut, out_fd, in_fd, 0, 100, fake_loop, False) - m_os.sendfile.assert_called_with(out_fd, in_fd, 0, 100) - assert fut.done() - assert exc is fut.exception() - assert not fake_loop.add_writer.called - assert not fake_loop.remove_writer.called - - -def test__sendfile_cb_return_on_cancelling(loop): - fake_loop = mock.Mock() - with mock.patch('aiohttp.web_fileresponse.os') as m_os: - out_fd = 30 - in_fd = 31 - fut = loop.create_future() - fut.cancel() - writer = SendfileStreamWriter(mock.Mock(), mock.Mock(), fake_loop) - writer._sendfile_cb(fut, out_fd, in_fd, 0, 100, fake_loop, False) - assert fut.done() - assert not fake_loop.add_writer.called - assert not fake_loop.remove_writer.called - assert not m_os.sendfile.called - - -def test_using_gzip_if_header_present_and_file_available(loop): +def test_using_gzip_if_header_present_and_file_available(loop) -> None: request = make_mocked_request( 'GET', 'http://python.org/logo.png', headers={ hdrs.ACCEPT_ENCODING: 'gzip' @@ -98,7 +32,7 @@ assert gz_filepath.open.called -def test_gzip_if_header_not_present_and_file_available(loop): +def test_gzip_if_header_not_present_and_file_available(loop) -> None: request = make_mocked_request( 'GET', 'http://python.org/logo.png', headers={ } @@ -124,7 +58,7 @@ assert not gz_filepath.open.called -def test_gzip_if_header_not_present_and_file_not_available(loop): +def test_gzip_if_header_not_present_and_file_not_available(loop) -> None: request = make_mocked_request( 'GET', 'http://python.org/logo.png', headers={ } @@ -150,7 +84,7 @@ assert not gz_filepath.open.called -def test_gzip_if_header_present_and_file_not_available(loop): +def test_gzip_if_header_present_and_file_not_available(loop) -> None: request = make_mocked_request( 'GET', 'http://python.org/logo.png', headers={ hdrs.ACCEPT_ENCODING: 'gzip' diff -Nru python-aiohttp-3.1.3/tests/test_web_server.py python-aiohttp-3.5.1/tests/test_web_server.py --- python-aiohttp-3.1.3/tests/test_web_server.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_web_server.py 2018-12-24 20:58:54.000000000 +0000 @@ -6,7 +6,7 @@ from aiohttp import client, web -async def test_simple_server(aiohttp_raw_server, aiohttp_client): +async def test_simple_server(aiohttp_raw_server, aiohttp_client) -> None: async def handler(request): return web.Response(text=str(request.rel_url)) @@ -39,7 +39,8 @@ exc_info=exc) -async def test_raw_server_handler_timeout(aiohttp_raw_server, aiohttp_client): +async def test_raw_server_handler_timeout(aiohttp_raw_server, + aiohttp_client) -> None: exc = asyncio.TimeoutError("error") async def handler(request): @@ -52,7 +53,7 @@ assert resp.status == 504 await resp.text() - logger.debug.assert_called_with("Request handler timed out.") + logger.debug.assert_called_with("Request handler timed out.", exc_info=exc) async def test_raw_server_do_not_swallow_exceptions(aiohttp_raw_server, @@ -108,13 +109,3 @@ logger.exception.assert_called_with( "Error handling request", exc_info=exc) - - -def test_create_web_server_with_implicit_loop(loop): - asyncio.set_event_loop(loop) - - async def handler(request): - return web.Response() # pragma: no cover - - srv = web.Server(handler) - assert srv._loop is loop diff -Nru python-aiohttp-3.1.3/tests/test_websocket_handshake.py python-aiohttp-3.5.1/tests/test_websocket_handshake.py --- python-aiohttp-3.1.3/tests/test_websocket_handshake.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_websocket_handshake.py 2018-12-24 20:58:54.000000000 +0000 @@ -32,21 +32,21 @@ return hdrs, key -async def test_not_get(): +async def test_not_get() -> None: ws = web.WebSocketResponse() req = make_mocked_request('POST', '/') with pytest.raises(web.HTTPMethodNotAllowed): await ws.prepare(req) -async def test_no_upgrade(): +async def test_no_upgrade() -> None: ws = web.WebSocketResponse() req = make_mocked_request('GET', '/') with pytest.raises(web.HTTPBadRequest): await ws.prepare(req) -async def test_no_connection(): +async def test_no_connection() -> None: ws = web.WebSocketResponse() req = make_mocked_request('GET', '/', headers={'Upgrade': 'websocket', 'Connection': 'keep-alive'}) @@ -54,7 +54,7 @@ await ws.prepare(req) -async def test_protocol_version_unset(): +async def test_protocol_version_unset() -> None: ws = web.WebSocketResponse() req = make_mocked_request('GET', '/', headers={'Upgrade': 'websocket', 'Connection': 'upgrade'}) @@ -62,7 +62,7 @@ await ws.prepare(req) -async def test_protocol_version_not_supported(): +async def test_protocol_version_not_supported() -> None: ws = web.WebSocketResponse() req = make_mocked_request('GET', '/', headers={'Upgrade': 'websocket', @@ -72,7 +72,7 @@ await ws.prepare(req) -async def test_protocol_key_not_present(): +async def test_protocol_key_not_present() -> None: ws = web.WebSocketResponse() req = make_mocked_request('GET', '/', headers={'Upgrade': 'websocket', @@ -82,7 +82,7 @@ await ws.prepare(req) -async def test_protocol_key_invalid(): +async def test_protocol_key_invalid() -> None: ws = web.WebSocketResponse() req = make_mocked_request('GET', '/', headers={'Upgrade': 'websocket', @@ -93,7 +93,7 @@ await ws.prepare(req) -async def test_protocol_key_bad_size(): +async def test_protocol_key_bad_size() -> None: ws = web.WebSocketResponse() sec_key = base64.b64encode(os.urandom(2)) val = sec_key.decode() @@ -106,7 +106,7 @@ await ws.prepare(req) -async def test_handshake_ok(): +async def test_handshake_ok() -> None: hdrs, sec_key = gen_ws_headers() ws = web.WebSocketResponse() req = make_mocked_request('GET', '/', headers=hdrs) @@ -116,7 +116,7 @@ assert ws.ws_protocol is None -async def test_handshake_protocol(): +async def test_handshake_protocol() -> None: # Tests if one protocol is returned by handshake proto = 'chat' @@ -128,7 +128,7 @@ assert ws.ws_protocol == proto -async def test_handshake_protocol_agreement(): +async def test_handshake_protocol_agreement() -> None: # Tests if the right protocol is selected given multiple best_proto = 'worse_proto' wanted_protos = ['best', 'chat', 'worse_proto'] @@ -143,7 +143,7 @@ assert ws.ws_protocol == best_proto -async def test_handshake_protocol_unsupported(caplog): +async def test_handshake_protocol_unsupported(caplog) -> None: # Tests if a protocol mismatch handshake warns and returns None proto = 'chat' req = make_mocked_request('GET', '/', @@ -157,7 +157,7 @@ assert ws.ws_protocol is None -async def test_handshake_compress(): +async def test_handshake_compress() -> None: hdrs, sec_key = gen_ws_headers(compress=15) req = make_mocked_request('GET', '/', headers=hdrs) @@ -168,7 +168,7 @@ assert ws.compress == 15 -def test_handshake_compress_server_notakeover(): +def test_handshake_compress_server_notakeover() -> None: hdrs, sec_key = gen_ws_headers(compress=15, server_notakeover=True) req = make_mocked_request('GET', '/', headers=hdrs) @@ -183,7 +183,7 @@ 'permessage-deflate; server_no_context_takeover') -def test_handshake_compress_client_notakeover(): +def test_handshake_compress_client_notakeover() -> None: hdrs, sec_key = gen_ws_headers(compress=15, client_notakeover=True) req = make_mocked_request('GET', '/', headers=hdrs) @@ -198,7 +198,7 @@ assert compress == 15 -def test_handshake_compress_wbits(): +def test_handshake_compress_wbits() -> None: hdrs, sec_key = gen_ws_headers(compress=9) req = make_mocked_request('GET', '/', headers=hdrs) @@ -212,7 +212,7 @@ assert compress == 9 -def test_handshake_compress_wbits_error(): +def test_handshake_compress_wbits_error() -> None: hdrs, sec_key = gen_ws_headers(compress=6) req = make_mocked_request('GET', '/', headers=hdrs) @@ -224,7 +224,7 @@ assert compress == 0 -def test_handshake_compress_bad_ext(): +def test_handshake_compress_bad_ext() -> None: hdrs, sec_key = gen_ws_headers(compress=15, extension_text='bad') req = make_mocked_request('GET', '/', headers=hdrs) @@ -236,7 +236,7 @@ assert compress == 0 -def test_handshake_compress_multi_ext_bad(): +def test_handshake_compress_multi_ext_bad() -> None: hdrs, sec_key = gen_ws_headers(compress=15, extension_text='bad, permessage-deflate') @@ -249,7 +249,7 @@ assert headers['Sec-Websocket-Extensions'] == 'permessage-deflate' -def test_handshake_compress_multi_ext_wbits(): +def test_handshake_compress_multi_ext_wbits() -> None: hdrs, sec_key = gen_ws_headers(compress=6, extension_text=', permessage-deflate') diff -Nru python-aiohttp-3.1.3/tests/test_websocket_parser.py python-aiohttp-3.5.1/tests/test_websocket_parser.py --- python-aiohttp-3.1.3/tests/test_websocket_parser.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_websocket_parser.py 2018-12-24 20:58:54.000000000 +0000 @@ -1,5 +1,6 @@ import random import struct +import zlib from unittest import mock import pytest @@ -7,13 +8,20 @@ import aiohttp from aiohttp import http_websocket from aiohttp.http import WebSocketError, WSCloseCode, WSMessage, WSMsgType -from aiohttp.http_websocket import (PACK_CLOSE_CODE, PACK_LEN1, PACK_LEN2, - PACK_LEN3, WebSocketReader, - _websocket_mask) +from aiohttp.http_websocket import (_WS_DEFLATE_TRAILING, PACK_CLOSE_CODE, + PACK_LEN1, PACK_LEN2, PACK_LEN3, + WebSocketReader, _websocket_mask) -def build_frame(message, opcode, use_mask=False, noheader=False, is_fin=True): +def build_frame(message, opcode, use_mask=False, noheader=False, is_fin=True, + compress=False): """Send a frame over the websocket with message as its payload.""" + if compress: + compressobj = zlib.compressobj(wbits=-9) + message = compressobj.compress(message) + message = message + compressobj.flush(zlib.Z_SYNC_FLUSH) + if message.endswith(_WS_DEFLATE_TRAILING): + message = message[:-4] msg_length = len(message) if use_mask: # pragma: no cover mask_bit = 0x80 @@ -25,6 +33,9 @@ else: header_first_byte = opcode + if compress: + header_first_byte |= 0x40 + if msg_length < 126: header = PACK_LEN1( header_first_byte, msg_length | mask_bit) @@ -62,15 +73,15 @@ @pytest.fixture() def out(loop): - return aiohttp.DataQueue(loop=loop) + return aiohttp.DataQueue(loop) @pytest.fixture() def parser(out): - return WebSocketReader(out) + return WebSocketReader(out, 4*1024*1024) -def test_parse_frame(parser): +def test_parse_frame(parser) -> None: parser.parse_frame(struct.pack('!BB', 0b00000001, 0b00000001)) res = parser.parse_frame(b'1') fin, opcode, payload, compress = res[0] @@ -78,14 +89,14 @@ assert (0, 1, b'1', False) == (fin, opcode, payload, not not compress) -def test_parse_frame_length0(parser): +def test_parse_frame_length0(parser) -> None: fin, opcode, payload, compress = parser.parse_frame( struct.pack('!BB', 0b00000001, 0b00000000))[0] assert (0, 1, b'', False) == (fin, opcode, payload, not not compress) -def test_parse_frame_length2(parser): +def test_parse_frame_length2(parser) -> None: parser.parse_frame(struct.pack('!BB', 0b00000001, 126)) parser.parse_frame(struct.pack('!H', 4)) res = parser.parse_frame(b'1234') @@ -94,7 +105,7 @@ assert (0, 1, b'1234', False) == (fin, opcode, payload, not not compress) -def test_parse_frame_length4(parser): +def test_parse_frame_length4(parser) -> None: parser.parse_frame(struct.pack('!BB', 0b00000001, 127)) parser.parse_frame(struct.pack('!Q', 4)) fin, opcode, payload, compress = parser.parse_frame(b'1234')[0] @@ -102,7 +113,7 @@ assert (0, 1, b'1234', False) == (fin, opcode, payload, not not compress) -def test_parse_frame_mask(parser): +def test_parse_frame_mask(parser) -> None: parser.parse_frame(struct.pack('!BB', 0b00000001, 0b10000001)) parser.parse_frame(b'0001') fin, opcode, payload, compress = parser.parse_frame(b'1')[0] @@ -110,13 +121,13 @@ assert (0, 1, b'\x01', False) == (fin, opcode, payload, not not compress) -def test_parse_frame_header_reversed_bits(out, parser): +def test_parse_frame_header_reversed_bits(out, parser) -> None: with pytest.raises(WebSocketError): parser.parse_frame(struct.pack('!BB', 0b01100000, 0b00000000)) raise out.exception() -def test_parse_frame_header_control_frame(out, parser): +def test_parse_frame_header_control_frame(out, parser) -> None: with pytest.raises(WebSocketError): parser.parse_frame(struct.pack('!BB', 0b00001000, 0b00000000)) raise out.exception() @@ -128,13 +139,13 @@ raise out.exception() -def test_parse_frame_header_payload_size(out, parser): +def test_parse_frame_header_payload_size(out, parser) -> None: with pytest.raises(WebSocketError): parser.parse_frame(struct.pack('!BB', 0b10001000, 0b01111110)) raise out.exception() -def test_ping_frame(out, parser): +def test_ping_frame(out, parser) -> None: parser.parse_frame = mock.Mock() parser.parse_frame.return_value = [(1, WSMsgType.PING, b'data', False)] @@ -143,7 +154,7 @@ assert res == ((WSMsgType.PING, b'data', ''), 4) -def test_pong_frame(out, parser): +def test_pong_frame(out, parser) -> None: parser.parse_frame = mock.Mock() parser.parse_frame.return_value = [(1, WSMsgType.PONG, b'data', False)] @@ -152,7 +163,7 @@ assert res == ((WSMsgType.PONG, b'data', ''), 4) -def test_close_frame(out, parser): +def test_close_frame(out, parser) -> None: parser.parse_frame = mock.Mock() parser.parse_frame.return_value = [(1, WSMsgType.CLOSE, b'', False)] @@ -161,7 +172,7 @@ assert res == ((WSMsgType.CLOSE, 0, ''), 0) -def test_close_frame_info(out, parser): +def test_close_frame_info(out, parser) -> None: parser.parse_frame = mock.Mock() parser.parse_frame.return_value = [(1, WSMsgType.CLOSE, b'0112345', False)] @@ -170,7 +181,7 @@ assert res == (WSMessage(WSMsgType.CLOSE, 12337, '12345'), 0) -def test_close_frame_invalid(out, parser): +def test_close_frame_invalid(out, parser) -> None: parser.parse_frame = mock.Mock() parser.parse_frame.return_value = [(1, WSMsgType.CLOSE, b'1', False)] parser.feed_data(b'') @@ -179,7 +190,7 @@ assert out.exception().code == WSCloseCode.PROTOCOL_ERROR -def test_close_frame_invalid_2(out, parser): +def test_close_frame_invalid_2(out, parser) -> None: data = build_close_frame(code=1) with pytest.raises(WebSocketError) as ctx: @@ -188,7 +199,7 @@ assert ctx.value.code == WSCloseCode.PROTOCOL_ERROR -def test_close_frame_unicode_err(parser): +def test_close_frame_unicode_err(parser) -> None: data = build_close_frame( code=1000, message=b'\xf4\x90\x80\x80') @@ -198,7 +209,7 @@ assert ctx.value.code == WSCloseCode.INVALID_TEXT -def test_unknown_frame(out, parser): +def test_unknown_frame(out, parser) -> None: parser.parse_frame = mock.Mock() parser.parse_frame.return_value = [(1, WSMsgType.CONTINUATION, b'', False)] @@ -207,14 +218,14 @@ raise out.exception() -def test_simple_text(out, parser): +def test_simple_text(out, parser) -> None: data = build_frame(b'text', WSMsgType.TEXT) parser._feed_data(data) res = out._buffer[0] assert res == ((WSMsgType.TEXT, 'text', ''), 4) -def test_simple_text_unicode_err(parser): +def test_simple_text_unicode_err(parser) -> None: data = build_frame(b'\xf4\x90\x80\x80', WSMsgType.TEXT) with pytest.raises(WebSocketError) as ctx: @@ -223,7 +234,7 @@ assert ctx.value.code == WSCloseCode.INVALID_TEXT -def test_simple_binary(out, parser): +def test_simple_binary(out, parser) -> None: parser.parse_frame = mock.Mock() parser.parse_frame.return_value = [(1, WSMsgType.BINARY, b'binary', False)] @@ -232,7 +243,7 @@ assert res == ((WSMsgType.BINARY, b'binary', ''), 6) -def test_fragmentation_header(out, parser): +def test_fragmentation_header(out, parser) -> None: data = build_frame(b'a', WSMsgType.TEXT) parser._feed_data(data[:1]) parser._feed_data(data[1:]) @@ -241,7 +252,7 @@ assert res == (WSMessage(WSMsgType.TEXT, 'a', ''), 1) -def test_continuation(out, parser): +def test_continuation(out, parser) -> None: data1 = build_frame(b'line1', WSMsgType.TEXT, is_fin=False) parser._feed_data(data1) @@ -252,7 +263,7 @@ assert res == (WSMessage(WSMsgType.TEXT, 'line1line2', ''), 10) -def test_continuation_with_ping(out, parser): +def test_continuation_with_ping(out, parser) -> None: parser.parse_frame = mock.Mock() parser.parse_frame.return_value = [ (0, WSMsgType.TEXT, b'line1', False), @@ -275,7 +286,7 @@ assert res == (WSMessage(WSMsgType.TEXT, 'line1line2', ''), 10) -def test_continuation_err(out, parser): +def test_continuation_err(out, parser) -> None: parser.parse_frame = mock.Mock() parser.parse_frame.return_value = [ (0, WSMsgType.TEXT, b'line1', False), @@ -285,7 +296,7 @@ parser._feed_data(b'') -def test_continuation_with_close(out, parser): +def test_continuation_with_close(out, parser) -> None: parser.parse_frame = mock.Mock() parser.parse_frame.return_value = [ (0, WSMsgType.TEXT, b'line1', False), @@ -301,7 +312,7 @@ assert res == (WSMessage(WSMsgType.TEXT, 'line1line2', ''), 10) -def test_continuation_with_close_unicode_err(out, parser): +def test_continuation_with_close_unicode_err(out, parser) -> None: parser.parse_frame = mock.Mock() parser.parse_frame.return_value = [ (0, WSMsgType.TEXT, b'line1', False), @@ -315,7 +326,7 @@ assert ctx.value.code == WSCloseCode.INVALID_TEXT -def test_continuation_with_close_bad_code(out, parser): +def test_continuation_with_close_bad_code(out, parser) -> None: parser.parse_frame = mock.Mock() parser.parse_frame.return_value = [ (0, WSMsgType.TEXT, b'line1', False), @@ -329,7 +340,7 @@ assert ctx.value.code == WSCloseCode.PROTOCOL_ERROR -def test_continuation_with_close_bad_payload(out, parser): +def test_continuation_with_close_bad_payload(out, parser) -> None: parser.parse_frame = mock.Mock() parser.parse_frame.return_value = [ (0, WSMsgType.TEXT, b'line1', False), @@ -342,7 +353,7 @@ assert ctx.value.code, WSCloseCode.PROTOCOL_ERROR -def test_continuation_with_close_empty(out, parser): +def test_continuation_with_close_empty(out, parser) -> None: parser.parse_frame = mock.Mock() parser.parse_frame.return_value = [ (0, WSMsgType.TEXT, b'line1', False), @@ -363,7 +374,7 @@ b'\\T\x14SK\x13CTP@[RYV@') -def test_websocket_mask_python(): +def test_websocket_mask_python() -> None: message = bytearray(websocket_mask_data) http_websocket._websocket_mask_python( websocket_mask_mask, message) @@ -372,14 +383,14 @@ @pytest.mark.skipif(not hasattr(http_websocket, '_websocket_mask_cython'), reason='Requires Cython') -def test_websocket_mask_cython(): +def test_websocket_mask_cython() -> None: message = bytearray(websocket_mask_data) http_websocket._websocket_mask_cython( websocket_mask_mask, message) assert message == websocket_mask_masked -def test_websocket_mask_python_empty(): +def test_websocket_mask_python_empty() -> None: message = bytearray() http_websocket._websocket_mask_python( websocket_mask_mask, message) @@ -388,14 +399,14 @@ @pytest.mark.skipif(not hasattr(http_websocket, '_websocket_mask_cython'), reason='Requires Cython') -def test_websocket_mask_cython_empty(): +def test_websocket_mask_cython_empty() -> None: message = bytearray() http_websocket._websocket_mask_cython( websocket_mask_mask, message) assert message == bytearray() -def test_msgtype_aliases(): +def test_msgtype_aliases() -> None: assert aiohttp.WSMsgType.TEXT == aiohttp.WSMsgType.text assert aiohttp.WSMsgType.BINARY == aiohttp.WSMsgType.binary assert aiohttp.WSMsgType.PING == aiohttp.WSMsgType.ping @@ -405,7 +416,7 @@ assert aiohttp.WSMsgType.ERROR == aiohttp.WSMsgType.error -def test_parse_compress_frame_single(parser): +def test_parse_compress_frame_single(parser) -> None: parser.parse_frame(struct.pack('!BB', 0b11000001, 0b00000001)) res = parser.parse_frame(b'1') fin, opcode, payload, compress = res[0] @@ -413,7 +424,7 @@ assert (1, 1, b'1', True) == (fin, opcode, payload, not not compress) -def test_parse_compress_frame_multi(parser): +def test_parse_compress_frame_multi(parser) -> None: parser.parse_frame(struct.pack('!BB', 0b01000001, 126)) parser.parse_frame(struct.pack('!H', 4)) res = parser.parse_frame(b'1234') @@ -433,7 +444,7 @@ assert (1, 1, b'1234', False) == (fin, opcode, payload, not not compress) -def test_parse_compress_error_frame(parser): +def test_parse_compress_error_frame(parser) -> None: parser.parse_frame(struct.pack('!BB', 0b01000001, 0b00000001)) parser.parse_frame(b'1') @@ -444,16 +455,35 @@ assert ctx.value.code == WSCloseCode.PROTOCOL_ERROR -@pytest.fixture() -def parser_no_compress(out): - return WebSocketReader(out, compress=False) - - -def test_parse_no_compress_frame_single(parser_no_compress): - +def test_parse_no_compress_frame_single() -> None: + parser_no_compress = WebSocketReader(out, 0, compress=False) with pytest.raises(WebSocketError) as ctx: parser_no_compress.parse_frame(struct.pack( '!BB', 0b11000001, 0b00000001)) parser_no_compress.parse_frame(b'1') assert ctx.value.code == WSCloseCode.PROTOCOL_ERROR + + +def test_msg_too_large(out) -> None: + parser = WebSocketReader(out, 256, compress=False) + data = build_frame(b'text'*256, WSMsgType.TEXT) + with pytest.raises(WebSocketError) as ctx: + parser._feed_data(data) + assert ctx.value.code == WSCloseCode.MESSAGE_TOO_BIG + + +def test_msg_too_large_not_fin(out) -> None: + parser = WebSocketReader(out, 256, compress=False) + data = build_frame(b'text'*256, WSMsgType.TEXT, is_fin=False) + with pytest.raises(WebSocketError) as ctx: + parser._feed_data(data) + assert ctx.value.code == WSCloseCode.MESSAGE_TOO_BIG + + +def test_compressed_msg_too_large(out) -> None: + parser = WebSocketReader(out, 256, compress=True) + data = build_frame(b'aaa'*256, WSMsgType.TEXT, compress=True) + with pytest.raises(WebSocketError) as ctx: + parser._feed_data(data) + assert ctx.value.code == WSCloseCode.MESSAGE_TOO_BIG diff -Nru python-aiohttp-3.1.3/tests/test_websocket_writer.py python-aiohttp-3.5.1/tests/test_websocket_writer.py --- python-aiohttp-3.1.3/tests/test_websocket_writer.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_websocket_writer.py 2018-12-24 20:58:54.000000000 +0000 @@ -24,39 +24,39 @@ return WebSocketWriter(protocol, transport, use_mask=False) -async def test_pong(writer): +async def test_pong(writer) -> None: await writer.pong() writer.transport.write.assert_called_with(b'\x8a\x00') -async def test_ping(writer): +async def test_ping(writer) -> None: await writer.ping() writer.transport.write.assert_called_with(b'\x89\x00') -async def test_send_text(writer): +async def test_send_text(writer) -> None: await writer.send(b'text') writer.transport.write.assert_called_with(b'\x81\x04text') -async def test_send_binary(writer): +async def test_send_binary(writer) -> None: await writer.send('binary', True) writer.transport.write.assert_called_with(b'\x82\x06binary') -async def test_send_binary_long(writer): +async def test_send_binary_long(writer) -> None: await writer.send(b'b' * 127, True) assert writer.transport.write.call_args[0][0].startswith(b'\x82~\x00\x7fb') -async def test_send_binary_very_long(writer): +async def test_send_binary_very_long(writer) -> None: await writer.send(b'b' * 65537, True) assert (writer.transport.write.call_args_list[0][0][0] == b'\x82\x7f\x00\x00\x00\x00\x00\x01\x00\x01') assert writer.transport.write.call_args_list[1][0][0] == b'b' * 65537 -async def test_close(writer): +async def test_close(writer) -> None: await writer.close(1001, 'msg') writer.transport.write.assert_called_with(b'\x88\x05\x03\xe9msg') @@ -68,7 +68,7 @@ writer.transport.write.assert_called_with(b'\x88\x05\x03\xf4msg') -async def test_send_text_masked(protocol, transport): +async def test_send_text_masked(protocol, transport) -> None: writer = WebSocketWriter(protocol, transport, use_mask=True, @@ -77,7 +77,7 @@ writer.transport.write.assert_called_with(b'\x81\x84\rg\xb3fy\x02\xcb\x12') -async def test_send_compress_text(protocol, transport): +async def test_send_compress_text(protocol, transport) -> None: writer = WebSocketWriter(protocol, transport, compress=15) await writer.send(b'text') writer.transport.write.assert_called_with(b'\xc1\x06*I\xad(\x01\x00') @@ -85,7 +85,7 @@ writer.transport.write.assert_called_with(b'\xc1\x05*\x01b\x00\x00') -async def test_send_compress_text_notakeover(protocol, transport): +async def test_send_compress_text_notakeover(protocol, transport) -> None: writer = WebSocketWriter(protocol, transport, compress=15, @@ -96,7 +96,7 @@ writer.transport.write.assert_called_with(b'\xc1\x06*I\xad(\x01\x00') -async def test_send_compress_text_per_message(protocol, transport): +async def test_send_compress_text_per_message(protocol, transport) -> None: writer = WebSocketWriter(protocol, transport) await writer.send(b'text', compress=15) writer.transport.write.assert_called_with(b'\xc1\x06*I\xad(\x01\x00') diff -Nru python-aiohttp-3.1.3/tests/test_web_urldispatcher.py python-aiohttp-3.5.1/tests/test_web_urldispatcher.py --- python-aiohttp-3.1.3/tests/test_web_urldispatcher.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_web_urldispatcher.py 2018-12-24 20:58:54.000000000 +0000 @@ -46,8 +46,12 @@ b'
  • my_file
  • \n' b'\n\n', id="index_static")]) -async def test_access_root_of_static_handler(tmp_dir_path, aiohttp_client, - show_index, status, prefix, data): +async def test_access_root_of_static_handler(tmp_dir_path, + aiohttp_client, + show_index, + status, + prefix, + data) -> None: """ Tests the operation of static file server. Try to access the root of static file server, and make @@ -82,7 +86,7 @@ assert read_ == data -async def test_follow_symlink(tmp_dir_path, aiohttp_client): +async def test_follow_symlink(tmp_dir_path, aiohttp_client) -> None: """ Tests the access to a symlink, in static folder """ @@ -142,7 +146,8 @@ assert (await r.text()) == data -async def test_access_non_existing_resource(tmp_dir_path, aiohttp_client): +async def test_access_non_existing_resource(tmp_dir_path, + aiohttp_client) -> None: """ Tests accessing non-existing resource Try to access a non-exiting resource and make sure that 404 HTTP status @@ -164,7 +169,9 @@ ('/a@b', '/a@b'), ('/a:b', '/a%3Ab'), ]) -async def test_url_escaping(aiohttp_client, registered_path, request_url): +async def test_url_escaping(aiohttp_client, + registered_path, + request_url) -> None: """ Tests accessing a resource with """ @@ -179,7 +186,7 @@ assert r.status == 200 -async def test_handler_metadata_persistence(): +async def test_handler_metadata_persistence() -> None: """ Tests accessing metadata of a handler after registering it on the app router. @@ -203,7 +210,8 @@ assert route.handler.__doc__ == 'Doc' -async def test_unauthorized_folder_access(tmp_dir_path, aiohttp_client): +async def test_unauthorized_folder_access(tmp_dir_path, + aiohttp_client) -> None: """ Tests the unauthorized access to a folder of static file server. Try to list a folder content of static file server when server does not @@ -230,7 +238,7 @@ assert r.status == 403 -async def test_access_symlink_loop(tmp_dir_path, aiohttp_client): +async def test_access_symlink_loop(tmp_dir_path, aiohttp_client) -> None: """ Tests the access to a looped symlink, which could not be resolved. """ @@ -248,7 +256,7 @@ assert r.status == 404 -async def test_access_special_resource(tmp_dir_path, aiohttp_client): +async def test_access_special_resource(tmp_dir_path, aiohttp_client) -> None: """ Tests the access to a resource that is neither a file nor a directory. Checks that if a special resource is accessed (f.e. named pipe or UNIX @@ -278,7 +286,7 @@ assert r.status == 403 -async def test_partially_applied_handler(aiohttp_client): +async def test_partially_applied_handler(aiohttp_client) -> None: app = web.Application() async def handler(data, request): @@ -293,7 +301,7 @@ assert data == b'hello' -def test_system_route(): +def test_system_route() -> None: route = SystemRoute(web.HTTPCreated(reason='test')) with pytest.raises(RuntimeError): route.url_for() @@ -304,14 +312,15 @@ assert 'test' == route.reason -async def test_412_is_returned(aiohttp_client): +async def test_412_is_returned(aiohttp_client) -> None: class MyRouter(abc.AbstractRouter): async def resolve(self, request): raise web.HTTPPreconditionFailed() - app = web.Application(router=MyRouter()) + with pytest.warns(DeprecationWarning): + app = web.Application(router=MyRouter()) client = await aiohttp_client(app) @@ -320,7 +329,7 @@ assert resp.status == 412 -async def test_allow_head(aiohttp_client): +async def test_allow_head(aiohttp_client) -> None: """ Test allow_head on routes. """ @@ -353,7 +362,7 @@ '/a', '/{a}', ]) -def test_reuse_last_added_resource(path): +def test_reuse_last_added_resource(path) -> None: """ Test that adding a route with the same name and path of the last added resource doesn't create a new resource. @@ -369,7 +378,7 @@ assert len(app.router.resources()) == 1 -def test_resource_raw_match(): +def test_resource_raw_match() -> None: app = web.Application() async def handler(request): @@ -385,7 +394,7 @@ assert not resource.raw_match("/static") -async def test_add_view(aiohttp_client): +async def test_add_view(aiohttp_client) -> None: app = web.Application() class MyView(web.View): @@ -412,7 +421,7 @@ await r.release() -async def test_decorate_view(aiohttp_client): +async def test_decorate_view(aiohttp_client) -> None: routes = web.RouteTableDef() @routes.view("/a") @@ -441,7 +450,7 @@ await r.release() -async def test_web_view(aiohttp_client): +async def test_web_view(aiohttp_client) -> None: app = web.Application() class MyView(web.View): @@ -470,7 +479,7 @@ await r.release() -async def test_static_absolute_url(aiohttp_client, tmpdir): +async def test_static_absolute_url(aiohttp_client, tmpdir) -> None: # requested url is an absolute name like # /static/\\machine_name\c$ or /static/D:\path # where the static dir is totally different diff -Nru python-aiohttp-3.1.3/tests/test_web_websocket_functional.py python-aiohttp-3.5.1/tests/test_web_websocket_functional.py --- python-aiohttp-3.1.3/tests/test_web_websocket_functional.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_web_websocket_functional.py 2018-12-24 20:58:54.000000000 +0000 @@ -17,7 +17,7 @@ mocker.patch('aiohttp.helpers.ceil').side_effect = ceil -async def test_websocket_can_prepare(loop, aiohttp_client): +async def test_websocket_can_prepare(loop, aiohttp_client) -> None: async def handler(request): ws = web.WebSocketResponse() @@ -34,7 +34,7 @@ assert resp.status == 426 -async def test_websocket_json(loop, aiohttp_client): +async def test_websocket_json(loop, aiohttp_client) -> None: async def handler(request): ws = web.WebSocketResponse() @@ -64,7 +64,7 @@ assert resp.data == expected_value -async def test_websocket_json_invalid_message(loop, aiohttp_client): +async def test_websocket_json_invalid_message(loop, aiohttp_client) -> None: async def handler(request): ws = web.WebSocketResponse() @@ -91,7 +91,7 @@ assert 'ValueError was raised' in data -async def test_websocket_send_json(loop, aiohttp_client): +async def test_websocket_send_json(loop, aiohttp_client) -> None: async def handler(request): ws = web.WebSocketResponse() @@ -115,7 +115,7 @@ assert data['test'] == expected_value -async def test_websocket_receive_json(loop, aiohttp_client): +async def test_websocket_receive_json(loop, aiohttp_client) -> None: async def handler(request): ws = web.WebSocketResponse() @@ -141,7 +141,7 @@ assert resp.data == expected_value -async def test_send_recv_text(loop, aiohttp_client): +async def test_send_recv_text(loop, aiohttp_client) -> None: closed = loop.create_future() @@ -175,7 +175,7 @@ await closed -async def test_send_recv_bytes(loop, aiohttp_client): +async def test_send_recv_bytes(loop, aiohttp_client) -> None: closed = loop.create_future() @@ -210,7 +210,7 @@ await closed -async def test_send_recv_json(loop, aiohttp_client): +async def test_send_recv_json(loop, aiohttp_client) -> None: closed = loop.create_future() async def handler(request): @@ -244,7 +244,7 @@ await closed -async def test_close_timeout(loop, aiohttp_client): +async def test_close_timeout(loop, aiohttp_client) -> None: aborted = loop.create_future() async def handler(request): @@ -297,7 +297,7 @@ await ws.close() -async def test_concurrent_close(loop, aiohttp_client): +async def test_concurrent_close(loop, aiohttp_client) -> None: srv_ws = None @@ -337,7 +337,7 @@ assert msg.type == WSMsgType.CLOSED -async def test_auto_pong_with_closing_by_peer(loop, aiohttp_client): +async def test_auto_pong_with_closing_by_peer(loop, aiohttp_client) -> None: closed = loop.create_future() @@ -367,7 +367,7 @@ await closed -async def test_ping(loop, aiohttp_client): +async def test_ping(loop, aiohttp_client) -> None: closed = loop.create_future() @@ -420,7 +420,7 @@ await ws.close() -async def test_pong(loop, aiohttp_client): +async def test_pong(loop, aiohttp_client) -> None: closed = loop.create_future() @@ -455,7 +455,7 @@ await closed -async def test_change_status(loop, aiohttp_client): +async def test_change_status(loop, aiohttp_client) -> None: closed = loop.create_future() @@ -480,7 +480,7 @@ await ws.close() -async def test_handle_protocol(loop, aiohttp_client): +async def test_handle_protocol(loop, aiohttp_client) -> None: closed = loop.create_future() @@ -502,7 +502,7 @@ await closed -async def test_server_close_handshake(loop, aiohttp_client): +async def test_server_close_handshake(loop, aiohttp_client) -> None: closed = loop.create_future() @@ -591,7 +591,7 @@ await closed -async def test_receive_timeout(loop, aiohttp_client): +async def test_receive_timeout(loop, aiohttp_client) -> None: raised = False async def handler(request): @@ -617,7 +617,7 @@ assert raised -async def test_custom_receive_timeout(loop, aiohttp_client): +async def test_custom_receive_timeout(loop, aiohttp_client) -> None: raised = False async def handler(request): @@ -643,7 +643,7 @@ assert raised -async def test_heartbeat(loop, aiohttp_client, ceil): +async def test_heartbeat(loop, aiohttp_client, ceil) -> None: async def handler(request): ws = web.WebSocketResponse(heartbeat=0.05) @@ -664,7 +664,7 @@ await ws.close() -async def test_heartbeat_no_pong(loop, aiohttp_client, ceil): +async def test_heartbeat_no_pong(loop, aiohttp_client, ceil) -> None: cancelled = False async def handler(request): @@ -692,7 +692,7 @@ assert cancelled -async def test_server_ws_async_for(loop, aiohttp_server): +async def test_server_ws_async_for(loop, aiohttp_server) -> None: closed = loop.create_future() async def handler(request): @@ -724,7 +724,7 @@ await closed -async def test_closed_async_for(loop, aiohttp_client): +async def test_closed_async_for(loop, aiohttp_client) -> None: closed = loop.create_future() @@ -760,7 +760,7 @@ await closed -async def test_websocket_disable_keepalive(loop, aiohttp_client): +async def test_websocket_disable_keepalive(loop, aiohttp_client) -> None: async def handler(request): ws = web.WebSocketResponse() if not ws.can_prepare(request): diff -Nru python-aiohttp-3.1.3/tests/test_web_websocket.py python-aiohttp-3.5.1/tests/test_web_websocket.py --- python-aiohttp-3.1.3/tests/test_web_websocket.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_web_websocket.py 2018-12-24 20:58:54.000000000 +0000 @@ -51,61 +51,61 @@ return maker -async def test_nonstarted_ping(): +async def test_nonstarted_ping() -> None: ws = WebSocketResponse() with pytest.raises(RuntimeError): await ws.ping() -async def test_nonstarted_pong(): +async def test_nonstarted_pong() -> None: ws = WebSocketResponse() with pytest.raises(RuntimeError): await ws.pong() -async def test_nonstarted_send_str(): +async def test_nonstarted_send_str() -> None: ws = WebSocketResponse() with pytest.raises(RuntimeError): await ws.send_str('string') -async def test_nonstarted_send_bytes(): +async def test_nonstarted_send_bytes() -> None: ws = WebSocketResponse() with pytest.raises(RuntimeError): await ws.send_bytes(b'bytes') -async def test_nonstarted_send_json(): +async def test_nonstarted_send_json() -> None: ws = WebSocketResponse() with pytest.raises(RuntimeError): await ws.send_json({'type': 'json'}) -async def test_nonstarted_close(): +async def test_nonstarted_close() -> None: ws = WebSocketResponse() with pytest.raises(RuntimeError): await ws.close() -async def test_nonstarted_receive_str(): +async def test_nonstarted_receive_str() -> None: ws = WebSocketResponse() with pytest.raises(RuntimeError): await ws.receive_str() -async def test_nonstarted_receive_bytes(): +async def test_nonstarted_receive_bytes() -> None: ws = WebSocketResponse() with pytest.raises(RuntimeError): await ws.receive_bytes() -async def test_nonstarted_receive_json(): +async def test_nonstarted_receive_json() -> None: ws = WebSocketResponse() with pytest.raises(RuntimeError): await ws.receive_json() -async def test_receive_str_nonstring(make_request): +async def test_receive_str_nonstring(make_request) -> None: req = make_request('GET', '/') ws = WebSocketResponse() await ws.prepare(req) @@ -119,7 +119,7 @@ await ws.receive_str() -async def test_receive_bytes_nonsbytes(make_request): +async def test_receive_bytes_nonsbytes(make_request) -> None: req = make_request('GET', '/') ws = WebSocketResponse() await ws.prepare(req) @@ -133,7 +133,7 @@ await ws.receive_bytes() -async def test_send_str_nonstring(make_request): +async def test_send_str_nonstring(make_request) -> None: req = make_request('GET', '/') ws = WebSocketResponse() await ws.prepare(req) @@ -141,7 +141,7 @@ await ws.send_str(b'bytes') -async def test_send_bytes_nonbytes(make_request): +async def test_send_bytes_nonbytes(make_request) -> None: req = make_request('GET', '/') ws = WebSocketResponse() await ws.prepare(req) @@ -149,7 +149,7 @@ await ws.send_bytes('string') -async def test_send_json_nonjson(make_request): +async def test_send_json_nonjson(make_request) -> None: req = make_request('GET', '/') ws = WebSocketResponse() await ws.prepare(req) @@ -157,66 +157,66 @@ await ws.send_json(set()) -async def test_write_non_prepared(): +async def test_write_non_prepared() -> None: ws = WebSocketResponse() with pytest.raises(RuntimeError): await ws.write(b'data') -def test_websocket_ready(): +def test_websocket_ready() -> None: websocket_ready = WebSocketReady(True, 'chat') assert websocket_ready.ok is True assert websocket_ready.protocol == 'chat' -def test_websocket_not_ready(): +def test_websocket_not_ready() -> None: websocket_ready = WebSocketReady(False, None) assert websocket_ready.ok is False assert websocket_ready.protocol is None -def test_websocket_ready_unknown_protocol(): +def test_websocket_ready_unknown_protocol() -> None: websocket_ready = WebSocketReady(True, None) assert websocket_ready.ok is True assert websocket_ready.protocol is None -def test_bool_websocket_ready(): +def test_bool_websocket_ready() -> None: websocket_ready = WebSocketReady(True, None) assert bool(websocket_ready) is True -def test_bool_websocket_not_ready(): +def test_bool_websocket_not_ready() -> None: websocket_ready = WebSocketReady(False, None) assert bool(websocket_ready) is False -def test_can_prepare_ok(make_request): +def test_can_prepare_ok(make_request) -> None: req = make_request('GET', '/', protocols=True) ws = WebSocketResponse(protocols=('chat',)) assert WebSocketReady(True, 'chat') == ws.can_prepare(req) -def test_can_prepare_unknown_protocol(make_request): +def test_can_prepare_unknown_protocol(make_request) -> None: req = make_request('GET', '/') ws = WebSocketResponse() assert WebSocketReady(True, None) == ws.can_prepare(req) -def test_can_prepare_invalid_method(make_request): +def test_can_prepare_invalid_method(make_request) -> None: req = make_request('POST', '/') ws = WebSocketResponse() assert WebSocketReady(False, None) == ws.can_prepare(req) -def test_can_prepare_without_upgrade(make_request): +def test_can_prepare_without_upgrade(make_request) -> None: req = make_request('GET', '/', headers=CIMultiDict({})) ws = WebSocketResponse() assert WebSocketReady(False, None) == ws.can_prepare(req) -async def test_can_prepare_started(make_request): +async def test_can_prepare_started(make_request) -> None: req = make_request('GET', '/') ws = WebSocketResponse() await ws.prepare(req) @@ -226,13 +226,13 @@ assert 'Already started' in str(ctx.value) -def test_closed_after_ctor(): +def test_closed_after_ctor() -> None: ws = WebSocketResponse() assert not ws.closed assert ws.close_code is None -async def test_send_str_closed(make_request, mocker): +async def test_send_str_closed(make_request, mocker) -> None: req = make_request('GET', '/') ws = WebSocketResponse() await ws.prepare(req) @@ -244,7 +244,7 @@ assert ws_logger.warning.called -async def test_send_bytes_closed(make_request, mocker): +async def test_send_bytes_closed(make_request, mocker) -> None: req = make_request('GET', '/') ws = WebSocketResponse() await ws.prepare(req) @@ -256,7 +256,7 @@ assert ws_logger.warning.called -async def test_send_json_closed(make_request, mocker): +async def test_send_json_closed(make_request, mocker) -> None: req = make_request('GET', '/') ws = WebSocketResponse() await ws.prepare(req) @@ -268,7 +268,7 @@ assert ws_logger.warning.called -async def test_ping_closed(make_request, mocker): +async def test_ping_closed(make_request, mocker) -> None: req = make_request('GET', '/') ws = WebSocketResponse() await ws.prepare(req) @@ -280,7 +280,7 @@ assert ws_logger.warning.called -async def test_pong_closed(make_request, mocker): +async def test_pong_closed(make_request, mocker) -> None: req = make_request('GET', '/') ws = WebSocketResponse() await ws.prepare(req) @@ -292,7 +292,7 @@ assert ws_logger.warning.called -async def test_close_idempotent(make_request): +async def test_close_idempotent(make_request) -> None: req = make_request('GET', '/') ws = WebSocketResponse() await ws.prepare(req) @@ -302,14 +302,14 @@ assert not (await ws.close(code=2, message='message2')) -async def test_prepare_invalid_method(make_request): +async def test_prepare_invalid_method(make_request) -> None: req = make_request('POST', '/') ws = WebSocketResponse() with pytest.raises(HTTPMethodNotAllowed): await ws.prepare(req) -async def test_prepare_without_upgrade(make_request): +async def test_prepare_without_upgrade(make_request) -> None: req = make_request('GET', '/', headers=CIMultiDict({})) ws = WebSocketResponse() @@ -317,19 +317,19 @@ await ws.prepare(req) -async def test_wait_closed_before_start(): +async def test_wait_closed_before_start() -> None: ws = WebSocketResponse() with pytest.raises(RuntimeError): await ws.close() -async def test_write_eof_not_started(): +async def test_write_eof_not_started() -> None: ws = WebSocketResponse() with pytest.raises(RuntimeError): await ws.write_eof() -async def test_write_eof_idempotent(make_request): +async def test_write_eof_idempotent(make_request) -> None: req = make_request('GET', '/') ws = WebSocketResponse() await ws.prepare(req) @@ -341,7 +341,7 @@ await ws.write_eof() -async def test_receive_eofstream_in_reader(make_request, loop): +async def test_receive_eofstream_in_reader(make_request, loop) -> None: req = make_request('GET', '/') ws = WebSocketResponse() await ws.prepare(req) @@ -360,7 +360,7 @@ assert ws.closed -async def test_receive_exc_in_reader(make_request, loop): +async def test_receive_exc_in_reader(make_request, loop) -> None: req = make_request('GET', '/') ws = WebSocketResponse() await ws.prepare(req) @@ -380,7 +380,7 @@ assert ws.exception() is exc -async def test_receive_cancelled(make_request, loop): +async def test_receive_cancelled(make_request, loop) -> None: req = make_request('GET', '/') ws = WebSocketResponse() await ws.prepare(req) @@ -394,7 +394,7 @@ await ws.receive() -async def test_receive_timeouterror(make_request, loop): +async def test_receive_timeouterror(make_request, loop) -> None: req = make_request('GET', '/') ws = WebSocketResponse() await ws.prepare(req) @@ -408,7 +408,7 @@ await ws.receive() -async def test_multiple_receive_on_close_connection(make_request): +async def test_multiple_receive_on_close_connection(make_request) -> None: req = make_request('GET', '/') ws = WebSocketResponse() await ws.prepare(req) @@ -424,7 +424,7 @@ await ws.receive() -async def test_concurrent_receive(make_request): +async def test_concurrent_receive(make_request) -> None: req = make_request('GET', '/') ws = WebSocketResponse() await ws.prepare(req) @@ -434,7 +434,7 @@ await ws.receive() -async def test_close_exc(make_request, loop, mocker): +async def test_close_exc(make_request, loop, mocker) -> None: req = make_request('GET', '/') ws = WebSocketResponse() @@ -460,7 +460,7 @@ assert ws.close_code == 1006 -async def test_close_exc2(make_request): +async def test_close_exc2(make_request) -> None: req = make_request('GET', '/') ws = WebSocketResponse() @@ -479,7 +479,7 @@ await ws.close() -async def test_prepare_twice_idempotent(make_request): +async def test_prepare_twice_idempotent(make_request) -> None: req = make_request('GET', '/') ws = WebSocketResponse() @@ -488,7 +488,7 @@ assert impl1 is impl2 -async def test_send_with_per_message_deflate(make_request, mocker): +async def test_send_with_per_message_deflate(make_request, mocker) -> None: req = make_request('GET', '/') ws = WebSocketResponse() await ws.prepare(req) diff -Nru python-aiohttp-3.1.3/tests/test_worker.py python-aiohttp-3.5.1/tests/test_worker.py --- python-aiohttp-3.1.3/tests/test_worker.py 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tests/test_worker.py 2018-12-24 20:58:54.000000000 +0000 @@ -43,13 +43,13 @@ self.wsgi = web.Application() -class AsyncioWorker(BaseTestWorker, base_worker.GunicornWebWorker): +class AsyncioWorker(BaseTestWorker, base_worker.GunicornWebWorker): # type: ignore # noqa pass PARAMS = [AsyncioWorker] if uvloop is not None: - class UvloopWorker(BaseTestWorker, base_worker.GunicornUVLoopWebWorker): + class UvloopWorker(BaseTestWorker, base_worker.GunicornUVLoopWebWorker): # type: ignore # noqa pass PARAMS.append(UvloopWorker) @@ -63,7 +63,7 @@ return ret -def test_init_process(worker): +def test_init_process(worker) -> None: with mock.patch('aiohttp.worker.asyncio') as m_asyncio: try: worker.init_process() @@ -75,7 +75,7 @@ assert m_asyncio.set_event_loop.called -def test_run(worker, loop): +def test_run(worker, loop) -> None: worker.log = mock.Mock() worker.cfg = mock.Mock() worker.cfg.access_log_format = ACCEPTABLE_LOG_FORMAT @@ -88,7 +88,7 @@ assert loop.is_closed() -def test_run_async_factory(worker, loop): +def test_run_async_factory(worker, loop) -> None: worker.log = mock.Mock() worker.cfg = mock.Mock() worker.cfg.access_log_format = ACCEPTABLE_LOG_FORMAT @@ -106,7 +106,7 @@ assert loop.is_closed() -def test_handle_quit(worker, loop): +def test_handle_quit(worker, loop) -> None: worker.loop = mock.Mock() worker.handle_quit(object(), object()) assert not worker.alive @@ -115,7 +115,7 @@ 0.1, worker._notify_waiter_done) -def test_handle_abort(worker): +def test_handle_abort(worker) -> None: with mock.patch('aiohttp.worker.sys') as m_sys: worker.handle_abort(object(), object()) assert not worker.alive @@ -123,7 +123,7 @@ m_sys.exit.assert_called_with(1) -def test__wait_next_notify(worker): +def test__wait_next_notify(worker) -> None: worker.loop = mock.Mock() worker._notify_waiter_done = mock.Mock() fut = worker._wait_next_notify() @@ -134,7 +134,7 @@ fut) -def test__notify_waiter_done(worker): +def test__notify_waiter_done(worker) -> None: worker._notify_waiter = None worker._notify_waiter_done() assert worker._notify_waiter is None @@ -147,7 +147,7 @@ waiter.set_result.assert_called_with(True) -def test__notify_waiter_done_explicit_waiter(worker): +def test__notify_waiter_done_explicit_waiter(worker) -> None: worker._notify_waiter = None assert worker._notify_waiter is None @@ -161,7 +161,7 @@ assert not waiter2.set_result.called -def test_init_signals(worker): +def test_init_signals(worker) -> None: worker.loop = mock.Mock() worker.init_signals() assert worker.loop.add_signal_handler.called @@ -172,17 +172,18 @@ (AsyncioWorker.DEFAULT_GUNICORN_LOG_FORMAT, AsyncioWorker.DEFAULT_AIOHTTP_LOG_FORMAT), ]) -def test__get_valid_log_format_ok(worker, source, result): +def test__get_valid_log_format_ok(worker, source, result) -> None: assert result == worker._get_valid_log_format(source) -def test__get_valid_log_format_exc(worker): +def test__get_valid_log_format_exc(worker) -> None: with pytest.raises(ValueError) as exc: worker._get_valid_log_format(WRONG_LOG_FORMAT) assert '%(name)s' in str(exc) -async def test__run_ok_parent_changed(worker, loop, aiohttp_unused_port): +async def test__run_ok_parent_changed(worker, loop, + aiohttp_unused_port) -> None: skip_if_no_dict(loop) worker.ppid = 0 @@ -208,7 +209,7 @@ assert worker._runner.server is None -async def test__run_exc(worker, loop, aiohttp_unused_port): +async def test__run_exc(worker, loop, aiohttp_unused_port) -> None: skip_if_no_dict(loop) worker.ppid = os.getppid() @@ -268,7 +269,7 @@ assert worker._runner.server is None -def test__create_ssl_context_without_certs_and_ciphers(worker): +def test__create_ssl_context_without_certs_and_ciphers(worker) -> None: here = pathlib.Path(__file__).parent worker.cfg.ssl_version = ssl.PROTOCOL_SSLv23 worker.cfg.cert_reqs = ssl.CERT_OPTIONAL @@ -280,7 +281,7 @@ assert isinstance(crt, ssl.SSLContext) -def test__create_ssl_context_with_ciphers(worker): +def test__create_ssl_context_with_ciphers(worker) -> None: here = pathlib.Path(__file__).parent worker.cfg.ssl_version = ssl.PROTOCOL_SSLv23 worker.cfg.cert_reqs = ssl.CERT_OPTIONAL @@ -292,7 +293,7 @@ assert isinstance(ctx, ssl.SSLContext) -def test__create_ssl_context_with_ca_certs(worker): +def test__create_ssl_context_with_ca_certs(worker) -> None: here = pathlib.Path(__file__).parent worker.cfg.ssl_version = ssl.PROTOCOL_SSLv23 worker.cfg.cert_reqs = ssl.CERT_OPTIONAL diff -Nru python-aiohttp-3.1.3/tools/build-wheels.sh python-aiohttp-3.5.1/tools/build-wheels.sh --- python-aiohttp-3.1.3/tools/build-wheels.sh 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tools/build-wheels.sh 2018-12-24 20:58:54.000000000 +0000 @@ -6,7 +6,7 @@ set -euo pipefail # ref: https://coderwall.com/p/fkfaqq/safer-bash-scripts-with-set-euxo-pipefail -PYTHON_VERSIONS="cp35-cp35m cp36-cp36m" +PYTHON_VERSIONS="cp35-cp35m cp36-cp36m cp37-cp37m" # Avoid creation of __pycache__/*.py[c|o] export PYTHONDONTWRITEBYTECODE=1 @@ -24,6 +24,7 @@ echo echo "Compile wheels" for PYTHON in ${PYTHON_VERSIONS}; do + /opt/python/${PYTHON}/bin/pip install -r /io/requirements/cython.txt /opt/python/${PYTHON}/bin/pip install -r /io/requirements/wheel.txt /opt/python/${PYTHON}/bin/pip wheel /io/ -w /io/dist/ done @@ -59,6 +60,7 @@ echo echo -n "Test $PYTHON: " /opt/python/${PYTHON}/bin/python -c "import platform; print('Building wheel for {platform} platform.'.format(platform=platform.platform()))" + /opt/python/${PYTHON}/bin/pip install -r /io/requirements/cython.txt /opt/python/${PYTHON}/bin/pip install -r /io/requirements/ci-wheel.txt /opt/python/${PYTHON}/bin/pip install "$package_name" --no-index -f file:///io/dist /opt/python/${PYTHON}/bin/py.test /io/tests diff -Nru python-aiohttp-3.1.3/tools/gen.py python-aiohttp-3.5.1/tools/gen.py --- python-aiohttp-3.1.3/tools/gen.py 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/tools/gen.py 2018-12-24 20:58:54.000000000 +0000 @@ -0,0 +1,157 @@ +#!/usr/bin/env python3 + +import aiohttp +import pathlib +from aiohttp import hdrs +from collections import defaultdict +import io + +headers = [getattr(hdrs, name) + for name in dir(hdrs) + if isinstance(getattr(hdrs, name), hdrs.istr)] + +def factory(): + return defaultdict(factory) + + +TERMINAL = object() + + +def build(headers): + dct = defaultdict(factory) + for hdr in headers: + d = dct + for ch in hdr: + d = d[ch] + d[TERMINAL] = hdr + return dct + +dct = build(headers) + + +HEADER = """\ +/* 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--; +""" + +BLOCK = """ +{label}: + NEXT_CHAR(); + switch (ch) {{ +{cases} + default: + return -1; + }} +""" + +CASE = """\ + case '{char}': + if (last) {{ + return {index}; + }} + goto {next};""" + +FOOTER = """ +{missing} +missing: + /* nothing found */ + return -1; +}} +""" + +def gen_prefix(prefix, k): + if k == '-': + return prefix + '_' + else: + return prefix + k.upper() + + +def gen_block(dct, prefix, used_blocks, missing, out): + cases = [] + for k, v in dct.items(): + if k is TERMINAL: + continue + next_prefix = gen_prefix(prefix, k) + term = v.get(TERMINAL) + if term is not None: + index = headers.index(term) + else: + index = -1 + hi = k.upper() + lo = k.lower() + case = CASE.format(char=hi, index=index, next=next_prefix) + cases.append(case) + if lo != hi: + case = CASE.format(char=lo, index=index, next=next_prefix) + cases.append(case) + label = prefix if prefix else 'INITIAL' + if cases: + block = BLOCK.format(label=label, cases='\n'.join(cases)) + out.write(block) + else: + missing.add(label) + for k, v in dct.items(): + if not isinstance(v, defaultdict): + continue + block_name = gen_prefix(prefix, k) + if block_name in used_blocks: + continue + used_blocks.add(block_name) + gen_block(v, block_name, used_blocks, missing, out) + + +def gen(dct): + out = io.StringIO() + out.write(HEADER) + missing = set() + gen_block(dct, '', set(), missing, out) + missing_labels = '\n'.join(m + ':' for m in sorted(missing)) + out.write(FOOTER.format(missing=missing_labels)) + return out + + +def gen_headers(headers): + out = io.StringIO() + out.write("# The file is autogenerated from aiohttp/hdrs.py\n") + out.write("# Run ./tools/gen.py to update it after the origin changing.") + out.write("\n\n") + out.write("from . import hdrs\n") + out.write("cdef tuple headers = (\n") + for hdr in headers: + out.write(" hdrs.{},\n".format(hdr.upper().replace('-', '_'))) + out.write(")\n") + return out + +# print(gen(dct).getvalue()) +# print(gen_headers(headers).getvalue()) + +folder = pathlib.Path(aiohttp.__file__).parent + +with (folder / '_find_header.c').open('w') as f: + f.write(gen(dct).getvalue()) + +with (folder / '_headers.pxi').open('w') as f: + f.write(gen_headers(headers).getvalue()) diff -Nru python-aiohttp-3.1.3/tools/run_docker.sh python-aiohttp-3.5.1/tools/run_docker.sh --- python-aiohttp-3.1.3/tools/run_docker.sh 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tools/run_docker.sh 2018-12-24 20:58:54.000000000 +0000 @@ -1,5 +1,6 @@ #!/bin/bash -set -e + +set -euo pipefail package_name="$1" if [ -z "$package_name" ] @@ -35,3 +36,5 @@ dock_ext_args="" # Reset docker args, just in case done + +set +u diff -Nru python-aiohttp-3.1.3/tox.ini python-aiohttp-3.5.1/tox.ini --- python-aiohttp-3.1.3/tox.ini 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/tox.ini 2018-12-24 20:58:54.000000000 +0000 @@ -1,18 +1,20 @@ [tox] -envlist = check, {py35,py36}-{debug,release}-{cchardet,cython,pure}, report +envlist = check, {py35,py36}-{debug,release}-{cython,pure}, report [testenv] deps = pytest pytest-mock + pytest-xdist # pytest-cov coverage gunicorn - cchardet: cython - cchardet: cchardet + async-generator + brotlipy cython: cython + -e . commands = # --cov={envsitepackagesdir}/tests @@ -40,10 +42,14 @@ flake8 pyflakes>=1.0.0 coverage + docutils + pygments + isort commands = flake8 aiohttp examples tests - python setup.py check -rm + python setup.py check -rms + # isort --check -rc aiohttp tests examples coverage erase basepython: diff -Nru python-aiohttp-3.1.3/.travis.yml python-aiohttp-3.5.1/.travis.yml --- python-aiohttp-3.1.3/.travis.yml 2018-04-13 10:00:38.000000000 +0000 +++ python-aiohttp-3.5.1/.travis.yml 2018-12-24 20:58:53.000000000 +0000 @@ -1,25 +1,30 @@ -sudo: false +conditions: v1 +version: "= 0" +if: > # Forbid running non-PR pushes from pyup bot + not (type != pull_request AND branch =~ ^pyup\-scheduled\-update\-) + +dist: xenial +sudo: required language: python python: - 3.5 -- &mainstream_python 3.6 -- 3.6-dev +- 3.6 +- &mainstream_python 3.7 - nightly - &pypy3 pypy3.5 install: - &upgrade_python_toolset pip install --upgrade pip wheel setuptools +- pip install -r requirements/cython.txt - pip install -r requirements/ci.txt script: -- make cov-ci-no-ext -- make cov-ci-aio-debug - make cov-ci-run after_success: -- codecov + - codecov _helpers: - &_mainstream_python_base @@ -41,7 +46,7 @@ <<: *_lint_base install: - *upgrade_python_toolset - - pip install -U -r requirements/ci.txt -r requirements/doc.txt -r requirements/doc-spelling.txt + - pip install -U -r requirements/doc.txt -r requirements/doc-spelling.txt after_failure: cat docs/_build/spelling/output.txt addons: apt: @@ -53,19 +58,13 @@ language: generic python: *pypy3 env: - - &env_pypy3 PYTHON_VERSION=pypy3.5-5.8.0 + - &env_pypy3 PYTHON_VERSION=pypy3.5-5.10.0 - &env_pyenv PYENV_ROOT="$HOME/.pyenv" - &env_path PATH="$PYENV_ROOT/bin:$PATH" before_install: - brew update - - brew install readline xz - - &ensure_pyenv_installed | - if [ ! -f "$PYENV_ROOT/bin/pyenv" ] - then - rm -rf "$PYENV_ROOT" - curl -L https://raw.githubusercontent.com/pyenv/pyenv-installer/master/bin/pyenv-installer | bash - fi - pyenv update + - brew install pyenv || brew upgrade pyenv + - &ensure_pyenv_preloaded | eval "$(pyenv init -)" eval "$(pyenv virtualenv-init -)" - &install_python pyenv install --skip-existing --keep --verbose "$PYTHON_VERSION" @@ -81,9 +80,15 @@ # `skip_cleanup: true` is required to preserve binary wheels, built # inside of manylinux1 docker container during `script` step above. skip_cleanup: true - user: andrew.svetlov + # `skip-existing: true` is required to skip uploading dists, already + # present in PYPI instead of failing the whole process. + # This happens when other CI (AppVeyor etc.) has already uploaded + # the very same dist (usually sdist). + skip-existing: true + user: aio-libs-bot password: - secure: ZQKbdPT9BlNqP5CTbWRQyeyig7Bpf7wsnYVQIQPOZc9Ec74A+dsbagstR1sPkAO+d+5PN0pZMovvmU7OQhSVPAnJ74nsN90/fL4ux3kqYecMbevv0rJg20hMXSSkwMEIpjUsMdMjJvZAcaKytGWmKL0qAlOJHhixd1pBbWyuIUE= + # Encrypted with `travis encrypt -r aio-libs/aiohttp --api-endpoint 'https://api.travis-ci.com/'`: + secure: bWF8GkGmjxfisMx+LqOmZgf9EXPT4yBMhiIbN+rU5gs53PJJyn1r287c5zEijnIHlpQaJVwWJ9ZFl1n34y37P1yvhlz0M6esr5K10B9fJ6nkUoAivtOWARcHLQ3bC+WGC/V9S0v0pZ11qFuSNzJzFZqfRabRw0H8muVWGhuBuYp97EdJWCdSNpXqsj2Ts8ytPMYv+5m3iPgXq833svFbWRjZ+HgX8HwvF2lo+ej+tsFJNACbQmj+eQDGlWQZzP2s4/3grHivd2retpqfW1cYgZaZX68/UB2ghsCtkxhcNpGaM8I/n3udAHkPSqz3MC2FJL0RdkyvQ8UZkcmcisQxz0voQM25995BHGWktwpDh7BxFtGJishXV7hiFz9zVOZLM9u5AzIO4hoN770SsZDewWdhzowXPYT8DXiHVg+roEkszg8FeBmisx1cw34CK9H0iLUSQ9EF2vuz8T4bqEpbT6Fyta90wZTvJ7GpJ4yXJXR6VAvLgiX4zXeFdx/4aViz3UzkDJ06qieRuZJWfQ9u2lDxJfqHEVy5IxM5iACagP1XayJiVIN0uFRxNElxTlCMope6ICCOu9fhcGnF15XNw5YpFPYYvph3JU1vC8cYw7ypg8LQGryp1fNM9SXWaGTiV+J/yvsynFiXX6QiyGOwSBIJ9XjZEfRd8i9HaGHw2cw= # Although Travis CI instructs `setup.py` to build source distribution, # which is default value for distribution option (`distribution: sdist`), # it will also upload all wheels we've previously built in manylinux1 @@ -103,7 +108,7 @@ script: skip after_success: [] env: - - &env_os1011_msg Build and deploy to PYPI of OS X 10.11 binary wheel + - &env_os1011_msg Build and deploy to PYPI of OS X 10.11 binary wheel= - &env_py36 PYTHON_VERSION=3.6.3 - *env_pyenv - *env_path @@ -115,7 +120,7 @@ <<: *osx_pypi_deploy_base_1011 osx_image: xcode8.1 env: - - &env_os1012_msg Build and deploy to PYPI of OS X 10.12 binary wheel + - &env_os1012_msg Build and deploy to PYPI of OS X 10.12 binary wheel= - *env_py36 - *env_pyenv - *env_path @@ -123,43 +128,73 @@ <<: *osx_pypi_deploy_base_1011 osx_image: xcode6.4 env: - - &env_os1010_msg Build and deploy to PYPI of OS X 10.10 binary wheel + - &env_os1010_msg Build and deploy to PYPI of OS X 10.10 binary wheel= - *env_py36 - *env_pyenv - *env_path -# doesn't work on MacOSX out of the box -- the system has no Python installed -# there's a workaround to use `language: generic` and install it, but it's slow os: linux jobs: fast_finish: true allow_failures: - python: nightly - - python: *pypy3 include: - - <<: *_doc_base + - name: 3.7 without extensions + python: 3.7 env: - - docs + AIOHTTP_NO_EXTENSIONS: 1 + + - <<: *_doc_base + name: Checking docs spelling script: - - towncrier --yes - make doc-spelling + - <<: *_doc_base + name: Checking Towncrier fragments + install: + - *upgrade_python_toolset + - pip install -r requirements/cython.txt + - pip install -r requirements/ci.txt + - pip install -r requirements/towncrier.txt + script: + - towncrier --yes + - <<: *_lint_base - env: - - flake8 + name: Linting source code with flake8 + install: + - *upgrade_python_toolset + - pip install -r requirements/flake.txt script: - - flake8 aiohttp examples tests demos + - flake8 aiohttp examples tests - <<: *_lint_base - env: - - dist setup check + name: Linting source code with mypy + install: + - *upgrade_python_toolset + - pip install -r requirements/cython.txt + - pip install -r requirements/ci.txt + script: + - mypy aiohttp + + - <<: *_lint_base + name: Verifying distribution package metadata install: - *upgrade_python_toolset - - pip install -r requirements/doc.txt + - pip install -r requirements/cython.txt + - pip install -r requirements/ci.txt -r requirements/doc.txt script: - - python setup.py check --metadata --restructuredtext --strict --verbose + - python setup.py check --metadata --restructuredtext --strict --verbose sdist bdist_wheel + - twine check dist/* + + - <<: *_lint_base + name: Making sure that CONTRIBUTORS.txt remains sorted + language: minimal + install: + - skip + script: + - LC_ALL=C sort -c CONTRIBUTORS.txt - <<: *osx_python_base python: 3.5.3 @@ -180,44 +215,25 @@ - *env_pyenv - *env_path - <<: *osx_python_base - python: nightly + python: 3.7 env: - - PYTHON_VERSION=3.7-dev + - &env_py37 PYTHON_VERSION=3.7.0 - *env_pyenv - *env_path - # pypy3.5-5.8.0 fails under OS X because it's unsupported + # pypy3.5-5.10.0 fails under OS X because it's unsupported # Build and deploy manylinux1 binary wheels and source distribution - <<: *generic_deploy_base <<: *_reset_steps - env: Build and deploy to PYPI of manylinux1 binary wheels for all supported Pythons and source distribution - dist: trusty - group: edge + env: Build and deploy to PYPI of manylinux1 binary wheels for all supported Pythons and source distribution= services: - docker script: - ./tools/run_docker.sh "aiohttp" + - pip install -r requirements/cython.txt - pip install -r requirements/ci.txt # to compile *.c files by Cython deploy: - provider: pypi - # `skip_cleanup: true` is required to preserve binary wheels, built - # inside of manylinux1 docker container during `script` step above. - skip_cleanup: true - user: andrew.svetlov - password: - secure: ZQKbdPT9BlNqP5CTbWRQyeyig7Bpf7wsnYVQIQPOZc9Ec74A+dsbagstR1sPkAO+d+5PN0pZMovvmU7OQhSVPAnJ74nsN90/fL4ux3kqYecMbevv0rJg20hMXSSkwMEIpjUsMdMjJvZAcaKytGWmKL0qAlOJHhixd1pBbWyuIUE= - # Although Travis CI instructs `setup.py` to build source distribution, - # which is default value for distribution option (`distribution: sdist`), - # it will also upload all wheels we've previously built in manylinux1 - # docker container using `twine upload -r pypi dist/*` command. - # Also since commit https://github.com/travis-ci/dpl/commit/90b5e39 - # it is default that Travis PYPI provider has `skip_upload_docs: true` - # set by default. - # Besides above, we don't do cleanup of `dist/*`, because it's being done - # by Travis CI PYPI deployment provider after upload, unconditionally. - on: - tags: true - all_branches: true + <<: *deploy_step # Build and deploy MacOS binary wheels for each OSX+Python combo possible # OS X 10.10, Python 3.5 @@ -235,6 +251,13 @@ - *env_py36 - *env_pyenv - *env_path + # OS X 10.10, Python 3.7 + - <<: *osx_pypi_deploy_base_1010 + env: + - *env_os1010_msg + - *env_py37 + - *env_pyenv + - *env_path # OS X 10.11, Python 3.5 - <<: *osx_pypi_deploy_base_1011 python: 3.5 @@ -250,6 +273,13 @@ - *env_py36 - *env_pyenv - *env_path + # OS X 10.11, Python 3.7 + - <<: *osx_pypi_deploy_base_1011 + env: + - *env_os1011_msg + - *env_py37 + - *env_pyenv + - *env_path # OS X 10.12, Python 3.5 - <<: *osx_pypi_deploy_base_1012 python: 3.5 @@ -265,6 +295,13 @@ - *env_py36 - *env_pyenv - *env_path + # OS X 10.12, Python 3.7 + - <<: *osx_pypi_deploy_base_1012 + env: + - *env_os1012_msg + - *env_py37 + - *env_pyenv + - *env_path stages: - *doc_stage_name diff -Nru python-aiohttp-3.1.3/vendor/http-parser/bench.c python-aiohttp-3.5.1/vendor/http-parser/bench.c --- python-aiohttp-3.1.3/vendor/http-parser/bench.c 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/vendor/http-parser/bench.c 2018-12-24 20:58:55.000000000 +0000 @@ -20,10 +20,14 @@ */ #include "http_parser.h" #include +#include #include #include #include +/* 8 gb */ +static const int64_t kBytes = 8LL << 30; + static const char data[] = "POST /joyent/http-parser HTTP/1.1\r\n" "Host: github.com\r\n" @@ -38,7 +42,7 @@ "Referer: https://github.com/joyent/http-parser\r\n" "Connection: keep-alive\r\n" "Transfer-Encoding: chunked\r\n" - "Cache-Control: max-age=0\r\n\r\nb\r\nhello world\r\n0\r\n\r\n"; + "Cache-Control: max-age=0\r\n\r\nb\r\nhello world\r\n0\r\n"; static const size_t data_len = sizeof(data) - 1; static int on_info(http_parser* p) { @@ -67,13 +71,13 @@ int err; struct timeval start; struct timeval end; - float rps; if (!silent) { err = gettimeofday(&start, NULL); assert(err == 0); } + fprintf(stderr, "req_len=%d\n", (int) data_len); for (i = 0; i < iter_count; i++) { size_t parsed; http_parser_init(&parser, HTTP_REQUEST); @@ -83,17 +87,27 @@ } if (!silent) { + double elapsed; + double bw; + double total; + err = gettimeofday(&end, NULL); assert(err == 0); fprintf(stdout, "Benchmark result:\n"); - rps = (float) (end.tv_sec - start.tv_sec) + - (end.tv_usec - start.tv_usec) * 1e-6f; - fprintf(stdout, "Took %f seconds to run\n", rps); + elapsed = (double) (end.tv_sec - start.tv_sec) + + (end.tv_usec - start.tv_usec) * 1e-6f; + + total = (double) iter_count * data_len; + bw = (double) total / elapsed; + + fprintf(stdout, "%.2f mb | %.2f mb/s | %.2f req/sec | %.2f s\n", + (double) total / (1024 * 1024), + bw / (1024 * 1024), + (double) iter_count / elapsed, + elapsed); - rps = (float) iter_count / rps; - fprintf(stdout, "%f req/sec\n", rps); fflush(stdout); } @@ -101,11 +115,14 @@ } int main(int argc, char** argv) { + int64_t iterations; + + iterations = kBytes / (int64_t) data_len; if (argc == 2 && strcmp(argv[1], "infinite") == 0) { for (;;) - bench(5000000, 1); + bench(iterations, 1); return 0; } else { - return bench(5000000, 0); + return bench(iterations, 0); } } diff -Nru python-aiohttp-3.1.3/vendor/http-parser/.git python-aiohttp-3.5.1/vendor/http-parser/.git --- python-aiohttp-3.1.3/vendor/http-parser/.git 1970-01-01 00:00:00.000000000 +0000 +++ python-aiohttp-3.5.1/vendor/http-parser/.git 2018-12-24 20:58:55.000000000 +0000 @@ -0,0 +1 @@ +gitdir: ../../.git/modules/vendor/http-parser diff -Nru python-aiohttp-3.1.3/vendor/http-parser/http_parser.c python-aiohttp-3.5.1/vendor/http-parser/http_parser.c --- python-aiohttp-3.1.3/vendor/http-parser/http_parser.c 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/vendor/http-parser/http_parser.c 2018-12-24 20:58:55.000000000 +0000 @@ -49,6 +49,7 @@ #define SET_ERRNO(e) \ do { \ + parser->nread = nread; \ parser->http_errno = (e); \ } while(0) @@ -56,6 +57,7 @@ #define UPDATE_STATE(V) p_state = (enum state) (V); #define RETURN(V) \ do { \ + parser->nread = nread; \ parser->state = CURRENT_STATE(); \ return (V); \ } while (0); @@ -149,8 +151,8 @@ */ #define COUNT_HEADER_SIZE(V) \ do { \ - parser->nread += (V); \ - if (UNLIKELY(parser->nread > (HTTP_MAX_HEADER_SIZE))) { \ + nread += (V); \ + if (UNLIKELY(nread > (HTTP_MAX_HEADER_SIZE))) { \ SET_ERRNO(HPE_HEADER_OVERFLOW); \ goto error; \ } \ @@ -192,7 +194,7 @@ /* 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us */ 0, 0, 0, 0, 0, 0, 0, 0, /* 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' */ - 0, '!', 0, '#', '$', '%', '&', '\'', + ' ', '!', 0, '#', '$', '%', '&', '\'', /* 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / */ 0, 0, '*', '+', 0, '-', '.', 0, /* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */ @@ -370,6 +372,8 @@ , h_connection , h_content_length + , h_content_length_num + , h_content_length_ws , h_transfer_encoding , h_upgrade @@ -417,14 +421,14 @@ (c) == ';' || (c) == ':' || (c) == '&' || (c) == '=' || (c) == '+' || \ (c) == '$' || (c) == ',') -#define STRICT_TOKEN(c) (tokens[(unsigned char)c]) +#define STRICT_TOKEN(c) ((c == ' ') ? 0 : tokens[(unsigned char)c]) #if HTTP_PARSER_STRICT -#define TOKEN(c) (tokens[(unsigned char)c]) +#define TOKEN(c) STRICT_TOKEN(c) #define IS_URL_CHAR(c) (BIT_AT(normal_url_char, (unsigned char)c)) #define IS_HOST_CHAR(c) (IS_ALPHANUM(c) || (c) == '.' || (c) == '-') #else -#define TOKEN(c) ((c == ' ') ? ' ' : tokens[(unsigned char)c]) +#define TOKEN(c) tokens[(unsigned char)c] #define IS_URL_CHAR(c) \ (BIT_AT(normal_url_char, (unsigned char)c) || ((c) & 0x80)) #define IS_HOST_CHAR(c) \ @@ -538,7 +542,7 @@ return s_dead; } - /* FALLTHROUGH */ + /* fall through */ case s_req_server_start: case s_req_server: if (ch == '/') { @@ -642,6 +646,7 @@ const char *status_mark = 0; enum state p_state = (enum state) parser->state; const unsigned int lenient = parser->lenient_http_headers; + uint32_t nread = parser->nread; /* We're in an error state. Don't bother doing anything. */ if (HTTP_PARSER_ERRNO(parser) != HPE_OK) { @@ -753,21 +758,16 @@ case s_start_res: { + if (ch == CR || ch == LF) + break; parser->flags = 0; parser->content_length = ULLONG_MAX; - switch (ch) { - case 'H': - UPDATE_STATE(s_res_H); - break; - - case CR: - case LF: - break; - - default: - SET_ERRNO(HPE_INVALID_CONSTANT); - goto error; + if (ch == 'H') { + UPDATE_STATE(s_res_H); + } else { + SET_ERRNO(HPE_INVALID_CONSTANT); + goto error; } CALLBACK_NOTIFY(message_begin); @@ -1236,8 +1236,14 @@ break; switch (parser->header_state) { - case h_general: + case h_general: { + size_t limit = data + len - p; + limit = MIN(limit, HTTP_MAX_HEADER_SIZE); + while (p+1 < data + limit && TOKEN(p[1])) { + p++; + } break; + } case h_C: parser->index++; @@ -1337,13 +1343,14 @@ } } - COUNT_HEADER_SIZE(p - start); - if (p == data + len) { --p; + COUNT_HEADER_SIZE(p - start); break; } + COUNT_HEADER_SIZE(p - start); + if (ch == ':') { UPDATE_STATE(s_header_value_discard_ws); CALLBACK_DATA(header_field); @@ -1367,7 +1374,7 @@ break; } - /* FALLTHROUGH */ + /* fall through */ case s_header_value_start: { @@ -1406,6 +1413,7 @@ parser->flags |= F_CONTENTLENGTH; parser->content_length = ch - '0'; + parser->header_state = h_content_length_num; break; case h_connection: @@ -1483,7 +1491,6 @@ p = data + len; } --p; - break; } @@ -1493,10 +1500,18 @@ break; case h_content_length: + if (ch == ' ') break; + h_state = h_content_length_num; + /* fall through */ + + case h_content_length_num: { uint64_t t; - if (ch == ' ') break; + if (ch == ' ') { + h_state = h_content_length_ws; + break; + } if (UNLIKELY(!IS_NUM(ch))) { SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); @@ -1519,6 +1534,12 @@ break; } + case h_content_length_ws: + if (ch == ' ') break; + SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); + parser->header_state = h_state; + goto error; + /* Transfer-Encoding: chunked */ case h_matching_transfer_encoding_chunked: parser->index++; @@ -1617,10 +1638,10 @@ } parser->header_state = h_state; - COUNT_HEADER_SIZE(p - start); - if (p == data + len) --p; + + COUNT_HEADER_SIZE(p - start); break; } @@ -1753,7 +1774,7 @@ case 2: parser->upgrade = 1; - /* FALLTHROUGH */ + /* fall through */ case 1: parser->flags |= F_SKIPBODY; break; @@ -1777,6 +1798,7 @@ STRICT_CHECK(ch != LF); parser->nread = 0; + nread = 0; hasBody = parser->flags & F_CHUNKED || (parser->content_length > 0 && parser->content_length != ULLONG_MAX); @@ -1871,7 +1893,7 @@ case s_chunk_size_start: { - assert(parser->nread == 1); + assert(nread == 1); assert(parser->flags & F_CHUNKED); unhex_val = unhex[(unsigned char)ch]; @@ -1939,6 +1961,7 @@ STRICT_CHECK(ch != LF); parser->nread = 0; + nread = 0; if (parser->content_length == 0) { parser->flags |= F_TRAILING; @@ -1985,6 +2008,7 @@ assert(parser->flags & F_CHUNKED); STRICT_CHECK(ch != LF); parser->nread = 0; + nread = 0; UPDATE_STATE(s_chunk_size_start); CALLBACK_NOTIFY(chunk_complete); break; @@ -1996,7 +2020,7 @@ } } - /* Run callbacks for any marks that we have leftover after we ran our of + /* Run callbacks for any marks that we have leftover after we ran out of * bytes. There should be at most one of these set, so it's OK to invoke * them in series (unset marks will not result in callbacks). * @@ -2078,6 +2102,16 @@ return ELEM_AT(method_strings, m, ""); } +const char * +http_status_str (enum http_status s) +{ + switch (s) { +#define XX(num, name, string) case HTTP_STATUS_##name: return #string; + HTTP_STATUS_MAP(XX) +#undef XX + default: return ""; + } +} void http_parser_init (http_parser *parser, enum http_parser_type t) @@ -2138,7 +2172,7 @@ return s_http_host; } - /* FALLTHROUGH */ + /* fall through */ case s_http_host_v6_end: if (ch == ':') { return s_http_host_port_start; @@ -2151,7 +2185,7 @@ return s_http_host_v6_end; } - /* FALLTHROUGH */ + /* fall through */ case s_http_host_v6_start: if (IS_HEX(ch) || ch == ':' || ch == '.') { return s_http_host_v6; @@ -2167,7 +2201,7 @@ return s_http_host_v6_end; } - /* FALLTHROUGH */ + /* fall through */ case s_http_host_v6_zone_start: /* RFC 6874 Zone ID consists of 1*( unreserved / pct-encoded) */ if (IS_ALPHANUM(ch) || ch == '%' || ch == '.' || ch == '-' || ch == '_' || @@ -2286,6 +2320,10 @@ enum http_parser_url_fields uf, old_uf; int found_at = 0; + if (buflen == 0) { + return 1; + } + u->port = u->field_set = 0; s = is_connect ? s_req_server_start : s_req_spaces_before_url; old_uf = UF_MAX; @@ -2313,7 +2351,7 @@ case s_req_server_with_at: found_at = 1; - /* FALLTHROUGH */ + /* fall through */ case s_req_server: uf = UF_HOST; break; @@ -2404,6 +2442,7 @@ */ if (HTTP_PARSER_ERRNO(parser) == HPE_OK || HTTP_PARSER_ERRNO(parser) == HPE_PAUSED) { + uint32_t nread = parser->nread; /* used by the SET_ERRNO macro */ SET_ERRNO((paused) ? HPE_PAUSED : HPE_OK); } else { assert(0 && "Attempting to pause parser in error state"); diff -Nru python-aiohttp-3.1.3/vendor/http-parser/http_parser.h python-aiohttp-3.5.1/vendor/http-parser/http_parser.h --- python-aiohttp-3.1.3/vendor/http-parser/http_parser.h 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/vendor/http-parser/http_parser.h 2018-12-24 20:58:55.000000000 +0000 @@ -27,7 +27,7 @@ /* Also update SONAME in the Makefile whenever you change these. */ #define HTTP_PARSER_VERSION_MAJOR 2 #define HTTP_PARSER_VERSION_MINOR 8 -#define HTTP_PARSER_VERSION_PATCH 0 +#define HTTP_PARSER_VERSION_PATCH 1 #include #if defined(_WIN32) && !defined(__MINGW32__) && \ @@ -407,6 +407,9 @@ /* Returns a string version of the HTTP method. */ const char *http_method_str(enum http_method m); +/* Returns a string version of the HTTP status code. */ +const char *http_status_str(enum http_status s); + /* Return a string name of the given error */ const char *http_errno_name(enum http_errno err); diff -Nru python-aiohttp-3.1.3/vendor/http-parser/Makefile python-aiohttp-3.5.1/vendor/http-parser/Makefile --- python-aiohttp-3.1.3/vendor/http-parser/Makefile 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/vendor/http-parser/Makefile 2018-12-24 20:58:55.000000000 +0000 @@ -24,7 +24,7 @@ SOLIBNAME = libhttp_parser SOMAJOR = 2 SOMINOR = 8 -SOREV = 0 +SOREV = 1 ifeq (darwin,$(PLATFORM)) SOEXT ?= dylib SONAME ?= $(SOLIBNAME).$(SOMAJOR).$(SOMINOR).$(SOEXT) diff -Nru python-aiohttp-3.1.3/vendor/http-parser/test.c python-aiohttp-3.5.1/vendor/http-parser/test.c --- python-aiohttp-3.1.3/vendor/http-parser/test.c 2018-04-13 10:00:39.000000000 +0000 +++ python-aiohttp-3.5.1/vendor/http-parser/test.c 2018-12-24 20:58:55.000000000 +0000 @@ -27,9 +27,7 @@ #include #if defined(__APPLE__) -# undef strlcat # undef strlncpy -# undef strlcpy #endif /* defined(__APPLE__) */ #undef TRUE @@ -43,7 +41,9 @@ #define MIN(a,b) ((a) < (b) ? (a) : (b)) -static http_parser *parser; +#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*x)) + +static http_parser parser; struct message { const char *name; // for debugging purposes @@ -153,10 +153,10 @@ ,.body= "" } -#define DUMBFUCK 2 -, {.name= "dumbfuck" +#define DUMBLUCK 2 +, {.name= "dumbluck" ,.type= HTTP_REQUEST - ,.raw= "GET /dumbfuck HTTP/1.1\r\n" + ,.raw= "GET /dumbluck HTTP/1.1\r\n" "aaaaaaaaaaaaa:++++++++++\r\n" "\r\n" ,.should_keep_alive= TRUE @@ -166,8 +166,8 @@ ,.method= HTTP_GET ,.query_string= "" ,.fragment= "" - ,.request_path= "/dumbfuck" - ,.request_url= "/dumbfuck" + ,.request_path= "/dumbluck" + ,.request_url= "/dumbluck" ,.num_headers= 1 ,.headers= { { "aaaaaaaaaaaaa", "++++++++++" } @@ -371,13 +371,13 @@ ,.chunk_lengths= { 5, 6 } } -#define CHUNKED_W_BULLSHIT_AFTER_LENGTH 11 -, {.name= "with bullshit after the length" +#define CHUNKED_W_NONSENSE_AFTER_LENGTH 11 +, {.name= "with nonsense after the length" ,.type= HTTP_REQUEST - ,.raw= "POST /chunked_w_bullshit_after_length HTTP/1.1\r\n" + ,.raw= "POST /chunked_w_nonsense_after_length HTTP/1.1\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" - "5; ihatew3;whatthefuck=aretheseparametersfor\r\nhello\r\n" + "5; ilovew3;whattheluck=aretheseparametersfor\r\nhello\r\n" "6; blahblah; blah\r\n world\r\n" "0\r\n" "\r\n" @@ -388,8 +388,8 @@ ,.method= HTTP_POST ,.query_string= "" ,.fragment= "" - ,.request_path= "/chunked_w_bullshit_after_length" - ,.request_url= "/chunked_w_bullshit_after_length" + ,.request_path= "/chunked_w_nonsense_after_length" + ,.request_url= "/chunked_w_nonsense_after_length" ,.num_headers= 1 ,.headers= { { "Transfer-Encoding", "chunked" } @@ -1173,8 +1173,6 @@ ,.headers= { { "Host", "example.com" } } ,.body= "" } - -, {.name= NULL } /* sentinel */ }; /* * R E S P O N S E S * */ @@ -1952,8 +1950,6 @@ ,.num_chunks_complete= 3 ,.chunk_lengths= { 2, 2 } } - -, {.name= NULL } /* sentinel */ }; /* strnlen() is a POSIX.2008 addition. Can't rely on it being available so @@ -1994,12 +1990,6 @@ } size_t -strlcat(char *dst, const char *src, size_t len) -{ - return strlncat(dst, len, src, (size_t) -1); -} - -size_t strlncpy(char *dst, size_t len, const char *src, size_t n) { size_t slen; @@ -2017,16 +2007,10 @@ return slen; } -size_t -strlcpy(char *dst, const char *src, size_t len) -{ - return strlncpy(dst, len, src, (size_t) -1); -} - int request_url_cb (http_parser *p, const char *buf, size_t len) { - assert(p == parser); + assert(p == &parser); strlncat(messages[num_messages].request_url, sizeof(messages[num_messages].request_url), buf, @@ -2037,7 +2021,7 @@ int header_field_cb (http_parser *p, const char *buf, size_t len) { - assert(p == parser); + assert(p == &parser); struct message *m = &messages[num_messages]; if (m->last_header_element != FIELD) @@ -2056,7 +2040,7 @@ int header_value_cb (http_parser *p, const char *buf, size_t len) { - assert(p == parser); + assert(p == &parser); struct message *m = &messages[num_messages]; strlncat(m->headers[m->num_headers-1][1], @@ -2085,7 +2069,7 @@ int body_cb (http_parser *p, const char *buf, size_t len) { - assert(p == parser); + assert(p == &parser); strlncat(messages[num_messages].body, sizeof(messages[num_messages].body), buf, @@ -2099,7 +2083,7 @@ int count_body_cb (http_parser *p, const char *buf, size_t len) { - assert(p == parser); + assert(p == &parser); assert(buf); messages[num_messages].body_size += len; check_body_is_final(p); @@ -2109,7 +2093,8 @@ int message_begin_cb (http_parser *p) { - assert(p == parser); + assert(p == &parser); + assert(!messages[num_messages].message_begin_cb_called); messages[num_messages].message_begin_cb_called = TRUE; return 0; } @@ -2117,21 +2102,22 @@ int headers_complete_cb (http_parser *p) { - assert(p == parser); - messages[num_messages].method = parser->method; - messages[num_messages].status_code = parser->status_code; - messages[num_messages].http_major = parser->http_major; - messages[num_messages].http_minor = parser->http_minor; + assert(p == &parser); + messages[num_messages].method = parser.method; + messages[num_messages].status_code = parser.status_code; + messages[num_messages].http_major = parser.http_major; + messages[num_messages].http_minor = parser.http_minor; messages[num_messages].headers_complete_cb_called = TRUE; - messages[num_messages].should_keep_alive = http_should_keep_alive(parser); + messages[num_messages].should_keep_alive = http_should_keep_alive(&parser); return 0; } int message_complete_cb (http_parser *p) { - assert(p == parser); - if (messages[num_messages].should_keep_alive != http_should_keep_alive(parser)) + assert(p == &parser); + if (messages[num_messages].should_keep_alive != + http_should_keep_alive(&parser)) { fprintf(stderr, "\n\n *** Error http_should_keep_alive() should have same " "value in both on_message_complete and on_headers_complete " @@ -2162,7 +2148,7 @@ int response_status_cb (http_parser *p, const char *buf, size_t len) { - assert(p == parser); + assert(p == &parser); messages[num_messages].status_cb_called = TRUE; @@ -2176,7 +2162,7 @@ int chunk_header_cb (http_parser *p) { - assert(p == parser); + assert(p == &parser); int chunk_idx = messages[num_messages].num_chunks; messages[num_messages].num_chunks++; if (chunk_idx < MAX_CHUNKS) { @@ -2189,7 +2175,7 @@ int chunk_complete_cb (http_parser *p) { - assert(p == parser); + assert(p == &parser); /* Here we want to verify that each chunk_header_cb is matched by a * chunk_complete_cb, so not only should the total number of calls to @@ -2394,7 +2380,7 @@ int connect_message_complete_cb (http_parser *p) { - messages[num_messages].should_keep_alive = http_should_keep_alive(parser); + messages[num_messages].should_keep_alive = http_should_keep_alive(&parser); return message_complete_cb(p); } @@ -2467,30 +2453,15 @@ parser_init (enum http_parser_type type) { num_messages = 0; - - assert(parser == NULL); - - parser = malloc(sizeof(http_parser)); - - http_parser_init(parser, type); - + http_parser_init(&parser, type); memset(&messages, 0, sizeof messages); - -} - -void -parser_free () -{ - assert(parser); - free(parser); - parser = NULL; } size_t parse (const char *buf, size_t len) { size_t nparsed; currently_parsing_eof = (len == 0); - nparsed = http_parser_execute(parser, &settings, buf, len); + nparsed = http_parser_execute(&parser, &settings, buf, len); return nparsed; } @@ -2498,7 +2469,7 @@ { size_t nparsed; currently_parsing_eof = (len == 0); - nparsed = http_parser_execute(parser, &settings_count_body, buf, len); + nparsed = http_parser_execute(&parser, &settings_count_body, buf, len); return nparsed; } @@ -2509,7 +2480,7 @@ currently_parsing_eof = (len == 0); current_pause_parser = &s; - nparsed = http_parser_execute(parser, current_pause_parser, buf, len); + nparsed = http_parser_execute(&parser, current_pause_parser, buf, len); return nparsed; } @@ -2517,7 +2488,7 @@ { size_t nparsed; currently_parsing_eof = (len == 0); - nparsed = http_parser_execute(parser, &settings_connect, buf, len); + nparsed = http_parser_execute(&parser, &settings_connect, buf, len); return nparsed; } @@ -2737,7 +2708,7 @@ print_error (const char *raw, size_t error_location) { fprintf(stderr, "\n*** %s ***\n\n", - http_errno_description(HTTP_PARSER_ERRNO(parser))); + http_errno_description(HTTP_PARSER_ERRNO(&parser))); int this_line = 0, char_len = 0; size_t i, j, len = strlen(raw), error_location_line = 0; @@ -3280,6 +3251,24 @@ ,.rv=1 /* s_dead */ } +, {.name="empty url" + ,.url="" + ,.is_connect=0 + ,.rv=1 + } + +, {.name="NULL url" + ,.url=NULL + ,.is_connect=0 + ,.rv=1 + } + +, {.name="full of spaces url" + ,.url=" " + ,.is_connect=0 + ,.rv=1 + } + #if HTTP_PARSER_STRICT , {.name="tab in URL" @@ -3364,7 +3353,7 @@ memset(&u, 0, sizeof(u)); rv = http_parser_parse_url(test->url, - strlen(test->url), + test->url ? strlen(test->url) : 0, test->is_connect, &u); @@ -3405,6 +3394,14 @@ } void +test_status_str (void) +{ + assert(0 == strcmp("OK", http_status_str(HTTP_STATUS_OK))); + assert(0 == strcmp("Not Found", http_status_str(HTTP_STATUS_NOT_FOUND))); + assert(0 == strcmp("", http_status_str(1337))); +} + +void test_message (const struct message *message) { size_t raw_len = strlen(message->raw); @@ -3418,9 +3415,18 @@ size_t msg2len = raw_len - msg1len; if (msg1len) { + assert(num_messages == 0); + messages[0].headers_complete_cb_called = FALSE; + read = parse(msg1, msg1len); - if (message->upgrade && parser->upgrade && num_messages > 0) { + if (!messages[0].headers_complete_cb_called && parser.nread != read) { + assert(parser.nread == read); + print_error(msg1, read); + abort(); + } + + if (message->upgrade && parser.upgrade && num_messages > 0) { messages[num_messages - 1].upgrade = msg1 + read; goto test; } @@ -3434,7 +3440,7 @@ read = parse(msg2, msg2len); - if (message->upgrade && parser->upgrade) { + if (message->upgrade && parser.upgrade) { messages[num_messages - 1].upgrade = msg2 + read; goto test; } @@ -3459,8 +3465,6 @@ } if(!message_eq(0, 0, message)) abort(); - - parser_free(); } } @@ -3496,8 +3500,6 @@ } if(!message_eq(0, 0, message)) abort(); - - parser_free(); } void @@ -3510,11 +3512,9 @@ enum http_errno err; parse(buf, strlen(buf)); - err = HTTP_PARSER_ERRNO(parser); + err = HTTP_PARSER_ERRNO(&parser); parse(NULL, 0); - parser_free(); - /* In strict mode, allow us to pass with an unexpected HPE_STRICT as * long as the caller isn't expecting success. */ @@ -3854,7 +3854,7 @@ read = parse(total, strlen(total)); - if (parser->upgrade) { + if (parser.upgrade) { upgrade_message_fix(total, read, 3, r1, r2, r3); goto test; } @@ -3881,8 +3881,6 @@ if (!message_eq(0, 0, r1)) abort(); if (message_count > 1 && !message_eq(1, 0, r2)) abort(); if (message_count > 2 && !message_eq(2, 0, r3)) abort(); - - parser_free(); } /* SCAN through every possible breaking to make sure the @@ -3936,9 +3934,17 @@ strlncpy(buf3, sizeof(buf1), total+j, buf3_len); buf3[buf3_len] = 0; + assert(num_messages == 0); + messages[0].headers_complete_cb_called = FALSE; + read = parse(buf1, buf1_len); - if (parser->upgrade) goto test; + if (!messages[0].headers_complete_cb_called && parser.nread != read) { + print_error(buf1, read); + goto error; + } + + if (parser.upgrade) goto test; if (read != buf1_len) { print_error(buf1, read); @@ -3947,7 +3953,7 @@ read += parse(buf2, buf2_len); - if (parser->upgrade) goto test; + if (parser.upgrade) goto test; if (read != buf1_len + buf2_len) { print_error(buf2, read); @@ -3956,7 +3962,7 @@ read += parse(buf3, buf3_len); - if (parser->upgrade) goto test; + if (parser.upgrade) goto test; if (read != buf1_len + buf2_len + buf3_len) { print_error(buf3, read); @@ -3966,7 +3972,7 @@ parse(NULL, 0); test: - if (parser->upgrade) { + if (parser.upgrade) { upgrade_message_fix(total, read, 3, r1, r2, r3); } @@ -3990,8 +3996,6 @@ fprintf(stderr, "\n\nError matching messages[2] in test_scan.\n"); goto error; } - - parser_free(); } } } @@ -4055,7 +4059,7 @@ // completion callback. if (messages[0].message_complete_cb_called && msg->upgrade && - parser->upgrade) { + parser.upgrade) { messages[0].upgrade = buf + nread; goto test; } @@ -4063,17 +4067,16 @@ if (nread < buflen) { // Not much do to if we failed a strict-mode check - if (HTTP_PARSER_ERRNO(parser) == HPE_STRICT) { - parser_free(); + if (HTTP_PARSER_ERRNO(&parser) == HPE_STRICT) { return; } - assert (HTTP_PARSER_ERRNO(parser) == HPE_PAUSED); + assert (HTTP_PARSER_ERRNO(&parser) == HPE_PAUSED); } buf += nread; buflen -= nread; - http_parser_pause(parser, 0); + http_parser_pause(&parser, 0); } while (buflen > 0); nread = parse_pause(NULL, 0); @@ -4086,8 +4089,6 @@ } if(!message_eq(0, 0, msg)) abort(); - - parser_free(); } /* Verify that body and next message won't be parsed in responses to CONNECT */ @@ -4107,17 +4108,12 @@ } if(!message_eq(0, 1, msg)) abort(); - - parser_free(); } int main (void) { - parser = NULL; - int i, j, k; - int request_count; - int response_count; + unsigned i, j, k; unsigned long version; unsigned major; unsigned minor; @@ -4131,13 +4127,11 @@ printf("sizeof(http_parser) = %u\n", (unsigned int)sizeof(http_parser)); - for (request_count = 0; requests[request_count].name; request_count++); - for (response_count = 0; responses[response_count].name; response_count++); - //// API test_preserve_data(); test_parse_url(); test_method_str(); + test_status_str(); //// NREAD test_header_nread_value(); @@ -4168,6 +4162,27 @@ test_invalid_header_field_token_error(HTTP_RESPONSE); test_invalid_header_field_content_error(HTTP_RESPONSE); + test_simple_type( + "POST / HTTP/1.1\r\n" + "Content-Length: 42 \r\n" // Note the surrounding whitespace. + "\r\n", + HPE_OK, + HTTP_REQUEST); + + test_simple_type( + "POST / HTTP/1.1\r\n" + "Content-Length: 4 2\r\n" + "\r\n", + HPE_INVALID_CONTENT_LENGTH, + HTTP_REQUEST); + + test_simple_type( + "POST / HTTP/1.1\r\n" + "Content-Length: 13 37\r\n" + "\r\n", + HPE_INVALID_CONTENT_LENGTH, + HTTP_REQUEST); + //// RESPONSES test_simple_type("HTP/1.1 200 OK\r\n\r\n", HPE_INVALID_VERSION, HTTP_RESPONSE); @@ -4175,24 +4190,25 @@ test_simple_type("HTTP/11.1 200 OK\r\n\r\n", HPE_INVALID_VERSION, HTTP_RESPONSE); test_simple_type("HTTP/1.01 200 OK\r\n\r\n", HPE_INVALID_VERSION, HTTP_RESPONSE); test_simple_type("HTTP/1.1\t200 OK\r\n\r\n", HPE_INVALID_VERSION, HTTP_RESPONSE); + test_simple_type("\rHTTP/1.1\t200 OK\r\n\r\n", HPE_INVALID_VERSION, HTTP_RESPONSE); - for (i = 0; i < response_count; i++) { + for (i = 0; i < ARRAY_SIZE(responses); i++) { test_message(&responses[i]); } - for (i = 0; i < response_count; i++) { + for (i = 0; i < ARRAY_SIZE(responses); i++) { test_message_pause(&responses[i]); } - for (i = 0; i < response_count; i++) { + for (i = 0; i < ARRAY_SIZE(responses); i++) { test_message_connect(&responses[i]); } - for (i = 0; i < response_count; i++) { + for (i = 0; i < ARRAY_SIZE(responses); i++) { if (!responses[i].should_keep_alive) continue; - for (j = 0; j < response_count; j++) { + for (j = 0; j < ARRAY_SIZE(responses); j++) { if (!responses[j].should_keep_alive) continue; - for (k = 0; k < response_count; k++) { + for (k = 0; k < ARRAY_SIZE(responses); k++) { test_multiple3(&responses[i], &responses[j], &responses[k]); } } @@ -4339,9 +4355,9 @@ "\r\n", HPE_INVALID_HEADER_TOKEN); - const char *dumbfuck2 = + const char *dumbluck2 = "GET / HTTP/1.1\r\n" - "X-SSL-Bullshit: -----BEGIN CERTIFICATE-----\r\n" + "X-SSL-Nonsense: -----BEGIN CERTIFICATE-----\r\n" "\tMIIFbTCCBFWgAwIBAgICH4cwDQYJKoZIhvcNAQEFBQAwcDELMAkGA1UEBhMCVUsx\r\n" "\tETAPBgNVBAoTCGVTY2llbmNlMRIwEAYDVQQLEwlBdXRob3JpdHkxCzAJBgNVBAMT\r\n" "\tAkNBMS0wKwYJKoZIhvcNAQkBFh5jYS1vcGVyYXRvckBncmlkLXN1cHBvcnQuYWMu\r\n" @@ -4374,7 +4390,7 @@ "\tRA==\r\n" "\t-----END CERTIFICATE-----\r\n" "\r\n"; - test_simple(dumbfuck2, HPE_OK); + test_simple(dumbluck2, HPE_OK); const char *corrupted_connection = "GET / HTTP/1.1\r\n" @@ -4408,19 +4424,19 @@ /* check to make sure our predefined requests are okay */ - for (i = 0; requests[i].name; i++) { + for (i = 0; i < ARRAY_SIZE(requests); i++) { test_message(&requests[i]); } - for (i = 0; i < request_count; i++) { + for (i = 0; i < ARRAY_SIZE(requests); i++) { test_message_pause(&requests[i]); } - for (i = 0; i < request_count; i++) { + for (i = 0; i < ARRAY_SIZE(requests); i++) { if (!requests[i].should_keep_alive) continue; - for (j = 0; j < request_count; j++) { + for (j = 0; j < ARRAY_SIZE(requests); j++) { if (!requests[j].should_keep_alive) continue; - for (k = 0; k < request_count; k++) { + for (k = 0; k < ARRAY_SIZE(requests); k++) { test_multiple3(&requests[i], &requests[j], &requests[k]); } } @@ -4441,7 +4457,7 @@ printf("request scan 3/4 "); test_scan( &requests[TWO_CHUNKS_MULT_ZERO_END] , &requests[CHUNKED_W_TRAILING_HEADERS] - , &requests[CHUNKED_W_BULLSHIT_AFTER_LENGTH] + , &requests[CHUNKED_W_NONSENSE_AFTER_LENGTH] ); printf("request scan 4/4 ");