struct.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. """
  2. Contains structures for representing header fields with associated metadata.
  3. """
  4. from __future__ import annotations
  5. from typing import TYPE_CHECKING, Any
  6. if TYPE_CHECKING:
  7. from typing_extensions import Self, TypeAlias # pragma: no cover
  8. class HeaderTuple(tuple[bytes, bytes]):
  9. """
  10. A data structure that stores a single header field.
  11. HTTP headers can be thought of as tuples of ``(field name, field value)``.
  12. A single header block is a sequence of such tuples.
  13. In HTTP/2, however, certain bits of additional information are required for
  14. compressing these headers: in particular, whether the header field can be
  15. safely added to the HPACK compression context.
  16. This class stores a header that can be added to the compression context. In
  17. all other ways it behaves exactly like a tuple.
  18. """
  19. __slots__ = ()
  20. indexable = True
  21. def __new__(cls, *args: Any) -> Self:
  22. return tuple.__new__(cls, args)
  23. class NeverIndexedHeaderTuple(HeaderTuple):
  24. """
  25. A data structure that stores a single header field that cannot be added to
  26. a HTTP/2 header compression context.
  27. """
  28. __slots__ = ()
  29. indexable = False
  30. def __new__(cls, *args: Any) -> Self:
  31. return tuple.__new__(cls, args)
  32. Header: TypeAlias = "HeaderTuple | NeverIndexedHeaderTuple | tuple[bytes, bytes]"
  33. HeaderWeaklyTyped: TypeAlias = "HeaderTuple | NeverIndexedHeaderTuple | tuple[bytes | str, bytes | str]"