Debian Codegraph @

src/anyio/streams/buffered.py

raw
1 from __future__ import annotations
2
3 __all__ = (
4 "BufferedByteReceiveStream",
5 "BufferedByteStream",
6 "BufferedConnectable",
7 )
8
9 import sys
10 from collections.abc import Callable, Iterable, Mapping
11 from dataclasses import dataclass, field
12 from typing import Any, SupportsIndex
13
14 from .. import ClosedResourceError, DelimiterNotFound, EndOfStream, IncompleteRead
15 from ..abc import (
16 AnyByteReceiveStream,
17 AnyByteStream,
18 AnyByteStreamConnectable,
19 ByteReceiveStream,
20 ByteStream,
21 ByteStreamConnectable,
22 )
23
24 if sys.version_info >= (3, 12):
25 from typing import override
26 else:
27 from typing_extensions import override
28
29
30 @dataclass(eq=False)
31 class BufferedByteReceiveStream(ByteReceiveStream):
32 """
33 Wraps any bytes-based receive stream and uses a buffer to provide sophisticated
34 receiving capabilities in the form of a byte stream.
35 """
36
37 receive_stream: AnyByteReceiveStream
38 _buffer: bytearray = field(init=False, default_factory=bytearray)
39 _closed: bool = field(init=False, default=False)
40
41 async def aclose(self) -> None:
42 await self.receive_stream.aclose()
43 self._closed = True
44
45 @property
46 def buffer(self) -> bytes:
47 """The bytes currently in the buffer."""
48 return bytes(self._buffer)
49
50 @property
51 def extra_attributes(self) -> Mapping[Any, Callable[[], Any]]:
52 return self.receive_stream.extra_attributes
53
54 def feed_data(self, data: Iterable[SupportsIndex], /) -> None:
55 """
56 Append data directly into the buffer.
57
58 Any data in the buffer will be consumed by receive operations before receiving
59 anything from the wrapped stream.
60
61 :param data: the data to append to the buffer (can be bytes or anything else
62 that supports ``__index__()``)
63
64 """
65 self._buffer.extend(data)
66
67 async def receive(self, max_bytes: int = 65536) -> bytes:
68 if self._closed:
69 raise ClosedResourceError
70
71 if self._buffer:
72 chunk = bytes(self._buffer[:max_bytes])
73 del self._buffer[:max_bytes]
74 return chunk
75 elif isinstance(self.receive_stream, ByteReceiveStream):
76 return await self.receive_stream.receive(max_bytes)
77 else:
78 # With a bytes-oriented object stream, we need to handle any surplus bytes
79 # we get from the receive() call
80 chunk = await self.receive_stream.receive()
81 if len(chunk) > max_bytes:
82 # Save the surplus bytes in the buffer
83 self._buffer.extend(chunk[max_bytes:])
84 return chunk[:max_bytes]
85 else:
86 return chunk
87
88 async def receive_exactly(self, nbytes: int) -> bytes:
89 """
90 Read exactly the given amount of bytes from the stream.
91
92 :param nbytes: the number of bytes to read
93 :return: the bytes read
94 :raises ~anyio.IncompleteRead: if the stream was closed before the requested
95 amount of bytes could be read from the stream
96
97 """
98 while True:
99 remaining = nbytes - len(self._buffer)
100 if remaining <= 0:
101 retval = self._buffer[:nbytes]
102 del self._buffer[:nbytes]
103 return bytes(retval)
104
105 try:
106 if isinstance(self.receive_stream, ByteReceiveStream):
107 chunk = await self.receive_stream.receive(remaining)
108 else:
109 chunk = await self.receive_stream.receive()
110 except EndOfStream as exc:
111 raise IncompleteRead from exc
112
113 self._buffer.extend(chunk)
114
115 async def receive_until(self, delimiter: bytes, max_bytes: int) -> bytes:
116 """
117 Read from the stream until the delimiter is found or max_bytes have been read.
118
119 :param delimiter: the marker to look for in the stream
120 :param max_bytes: maximum number of bytes that will be read before raising
121 :exc:`~anyio.DelimiterNotFound`
122 :return: the bytes read (not including the delimiter)
123 :raises ~anyio.IncompleteRead: if the stream was closed before the delimiter
124 was found
125 :raises ~anyio.DelimiterNotFound: if the delimiter is not found within the
126 bytes read up to the maximum allowed
127
128 """
129 delimiter_size = len(delimiter)
130 offset = 0
131 while True:
132 # Check if the delimiter can be found in the current buffer
133 index = self._buffer.find(delimiter, offset)
134 if index >= 0:
135 found = self._buffer[:index]
136 del self._buffer[: index + len(delimiter) :]
137 return bytes(found)
138
139 # Check if the buffer is already at or over the limit
140 if len(self._buffer) >= max_bytes:
141 raise DelimiterNotFound(max_bytes)
142
143 # Read more data into the buffer from the socket
144 try:
145 data = await self.receive_stream.receive()
146 except EndOfStream as exc:
147 raise IncompleteRead from exc
148
149 # Move the offset forward and add the new data to the buffer
150 offset = max(len(self._buffer) - delimiter_size + 1, 0)
151 self._buffer.extend(data)
152
153
154 class BufferedByteStream(BufferedByteReceiveStream, ByteStream):
155 """
156 A full-duplex variant of :class:`BufferedByteReceiveStream`. All writes are passed
157 through to the wrapped stream as-is.
158 """
159
160 def __init__(self, stream: AnyByteStream):
161 """
162 :param stream: the stream to be wrapped
163
164 """
165 super().__init__(stream)
166 self._stream = stream
167
168 @override
169 async def send_eof(self) -> None:
170 await self._stream.send_eof()
171
172 @override
173 async def send(self, item: bytes) -> None:
174 await self._stream.send(item)
175
176
177 class BufferedConnectable(ByteStreamConnectable):
178 def __init__(self, connectable: AnyByteStreamConnectable):
179 """
180 :param connectable: the connectable to wrap
181
182 """
183 self.connectable = connectable
184
185 @override
186 async def connect(self) -> BufferedByteStream:
187 stream = await self.connectable.connect()
188 return BufferedByteStream(stream)