Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/hip/parsers/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
from .base import BytesParser, ParseError
from .http import HTTPParser, ProtocolError
from .sansio import HTTPClient, HTTPServer

__all__ = [
"BytesParser",
"HTTPClient",
"HTTPParser",
"HTTPServer",
"ParseError",
"ProtocolError",
]
89 changes: 89 additions & 0 deletions src/hip/parsers/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
__all__ = ["BytesParser", "ParseError"]


class ParseError(Exception):
pass


class BytesParser:
"""
A parser following the Sans-IO design pattern.

Provides parsing operations for "read some data" and
"read some data up until a fixed delimiter".

Used by the HTTP parsing to handle parsing the different
sections of the request and response.
"""

def __init__(self):
self._buffer = bytearray()
self._closed = False
self._cursor = 0

def read_some(self, max_size: int) -> bytes | None:
"""
Read and return some data from the buffer, up to `max_size` bytes.
The `max_size` limit must be greater than 0.

Returns b'' to indicate the end of the stream.

Returns `None` to indicate feed required.
"""
if max_size <= 0:
raise ValueError("max_size must be > 0")

if not self._buffer:
if self._closed:
return b""
return None

read, unread = self._buffer[:max_size], self._buffer[max_size:]
self._buffer = bytearray(unread)
return bytes(read)

def read_until(self, marker: bytes, max_size: int) -> bytes | None:
"""
Returns data up to and excluding the designated `marker`.
Returns at most `max_size` bytes.
Removes both the returned data and the marker from the buffer.

Returns `None` to indicate feed required.

Raises a `ParseError` if the marker cannot be found.
"""
if self._cursor >= len(self._buffer):
if self._closed:
raise ParseError()
return None

start_point = self._cursor
end_point = max_size + len(marker)
idx = self._buffer.find(marker, start_point, end_point)
if idx < 0:
self._cursor = max(0, len(self._buffer) - len(marker))
return None

read, unread = self._buffer[:idx], self._buffer[idx + len(marker) :]
self._buffer = bytearray(unread)
self._cursor = 0
return bytes(read)

def maybe_read_eof(self) -> bool | None:
if not self._buffer:
if self._closed:
return True # buffer is empty and closed
return None # buffer is empty and not closed
return False # buffer is not empty

def feed(self, data: bytes) -> None:
"""
Feed `data` bytes to the parser.
Feed b'' to indicate the end of the stream.
"""
if data:
if self._closed:
raise ValueError("Attempted to feed data to a closed parser.")
self._buffer.extend(data)
else:
self._closed = True
Loading
Loading