Read 'size' bytes from remote.
(self, size)
| 334 | |
| 335 | |
| 336 | def read(self, size): |
| 337 | """Read 'size' bytes from remote.""" |
| 338 | # We need buffered read() to continue working after socket timeouts, |
| 339 | # since we use them during IDLE. Unfortunately, the standard library's |
| 340 | # SocketIO implementation makes this impossible, by setting a permanent |
| 341 | # error condition instead of letting the caller decide how to handle a |
| 342 | # timeout. We therefore implement our own buffered read(). |
| 343 | # https://github.com/python/cpython/issues/51571 |
| 344 | # |
| 345 | # Reading in chunks instead of delegating to a single |
| 346 | # BufferedReader.read() call also means we avoid its preallocation |
| 347 | # of an unreasonably large memory block if a malicious server claims |
| 348 | # it will send a huge literal without actually sending one. |
| 349 | # https://github.com/python/cpython/issues/119511 |
| 350 | |
| 351 | parts = [] |
| 352 | |
| 353 | while size > 0: |
| 354 | |
| 355 | if len(parts) < len(self._readbuf): |
| 356 | buf = self._readbuf[len(parts)] |
| 357 | else: |
| 358 | try: |
| 359 | buf = self.sock.recv(DEFAULT_BUFFER_SIZE) |
| 360 | except ConnectionError: |
| 361 | break |
| 362 | if not buf: |
| 363 | break |
| 364 | self._readbuf.append(buf) |
| 365 | |
| 366 | if len(buf) >= size: |
| 367 | parts.append(buf[:size]) |
| 368 | self._readbuf = [buf[size:]] + self._readbuf[len(parts):] |
| 369 | break |
| 370 | parts.append(buf) |
| 371 | size -= len(buf) |
| 372 | |
| 373 | return b''.join(parts) |
| 374 | |
| 375 | |
| 376 | def readline(self): |
no test coverage detected