|
1 | 1 | import base64
|
2 | 2 | import binascii
|
3 |
| -from io import BufferedWriter |
| 3 | +from typing import TYPE_CHECKING |
4 | 4 |
|
5 | 5 | from .exceptions import DecodeError
|
6 | 6 |
|
| 7 | +if TYPE_CHECKING: # pragma: no cover |
| 8 | + from typing import Protocol, TypeVar |
| 9 | + |
| 10 | + _T_contra = TypeVar("_T_contra", contravariant=True) |
| 11 | + |
| 12 | + class SupportsWrite(Protocol[_T_contra]): |
| 13 | + def write(self, __b: _T_contra) -> object: ... |
| 14 | + |
| 15 | + # No way to specify optional methods. See |
| 16 | + # https://github.com/python/typing/issues/601 |
| 17 | + # close() [Optional] |
| 18 | + # finalize() [Optional] |
| 19 | + |
7 | 20 |
|
8 | 21 | class Base64Decoder:
|
9 | 22 | """This object provides an interface to decode a stream of Base64 data. It
|
@@ -34,7 +47,7 @@ class Base64Decoder:
|
34 | 47 | :param underlying: the underlying object to pass writes to
|
35 | 48 | """
|
36 | 49 |
|
37 |
| - def __init__(self, underlying: BufferedWriter): |
| 50 | + def __init__(self, underlying: "SupportsWrite[bytes]") -> None: |
38 | 51 | self.cache = bytearray()
|
39 | 52 | self.underlying = underlying
|
40 | 53 |
|
@@ -67,9 +80,9 @@ def write(self, data: bytes) -> int:
|
67 | 80 | # Get the remaining bytes and save in our cache.
|
68 | 81 | remaining_len = len(data) % 4
|
69 | 82 | if remaining_len > 0:
|
70 |
| - self.cache = data[-remaining_len:] |
| 83 | + self.cache[:] = data[-remaining_len:] |
71 | 84 | else:
|
72 |
| - self.cache = b"" |
| 85 | + self.cache[:] = b"" |
73 | 86 |
|
74 | 87 | # Return the length of the data to indicate no error.
|
75 | 88 | return len(data)
|
@@ -112,7 +125,7 @@ class QuotedPrintableDecoder:
|
112 | 125 | :param underlying: the underlying object to pass writes to
|
113 | 126 | """
|
114 | 127 |
|
115 |
| - def __init__(self, underlying: BufferedWriter) -> None: |
| 128 | + def __init__(self, underlying: "SupportsWrite[bytes]") -> None: |
116 | 129 | self.cache = b""
|
117 | 130 | self.underlying = underlying
|
118 | 131 |
|
|
0 commit comments