-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Move the now-unused InventoryFileReader
- Loading branch information
Showing
2 changed files
with
84 additions
and
55 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
from __future__ import annotations | ||
|
||
import zlib | ||
from typing import TYPE_CHECKING | ||
|
||
from sphinx.util import logging | ||
|
||
BUFSIZE = 16 * 1024 | ||
logger = logging.getLogger(__name__) | ||
|
||
if TYPE_CHECKING: | ||
from collections.abc import Iterator | ||
from typing import Protocol | ||
|
||
# Readable file stream for inventory loading | ||
class _SupportsRead(Protocol): | ||
def read(self, size: int = ...) -> bytes: ... | ||
|
||
|
||
__all__ = ('InventoryFileReader',) | ||
|
||
|
||
class InventoryFileReader: | ||
"""A file reader for an inventory file. | ||
This reader supports mixture of texts and compressed texts. | ||
""" | ||
|
||
def __init__(self, stream: _SupportsRead) -> None: | ||
self.stream = stream | ||
self.buffer = b'' | ||
self.eof = False | ||
|
||
def read_buffer(self) -> None: | ||
chunk = self.stream.read(BUFSIZE) | ||
if chunk == b'': | ||
self.eof = True | ||
self.buffer += chunk | ||
|
||
def readline(self) -> str: | ||
pos = self.buffer.find(b'\n') | ||
if pos != -1: | ||
line = self.buffer[:pos].decode() | ||
self.buffer = self.buffer[pos + 1 :] | ||
elif self.eof: | ||
line = self.buffer.decode() | ||
self.buffer = b'' | ||
else: | ||
self.read_buffer() | ||
line = self.readline() | ||
|
||
return line | ||
|
||
def readlines(self) -> Iterator[str]: | ||
while not self.eof: | ||
line = self.readline() | ||
if line: | ||
yield line | ||
|
||
def read_compressed_chunks(self) -> Iterator[bytes]: | ||
decompressor = zlib.decompressobj() | ||
while not self.eof: | ||
self.read_buffer() | ||
yield decompressor.decompress(self.buffer) | ||
self.buffer = b'' | ||
yield decompressor.flush() | ||
|
||
def read_compressed_lines(self) -> Iterator[str]: | ||
buf = b'' | ||
for chunk in self.read_compressed_chunks(): | ||
buf += chunk | ||
pos = buf.find(b'\n') | ||
while pos != -1: | ||
yield buf[:pos].decode() | ||
buf = buf[pos + 1 :] | ||
pos = buf.find(b'\n') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters