Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pypdf/_utils.py: 48%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

311 statements  

1# Copyright (c) 2006, Mathieu Fenniak 

2# All rights reserved. 

3# 

4# Redistribution and use in source and binary forms, with or without 

5# modification, are permitted provided that the following conditions are 

6# met: 

7# 

8# * Redistributions of source code must retain the above copyright notice, 

9# this list of conditions and the following disclaimer. 

10# * Redistributions in binary form must reproduce the above copyright notice, 

11# this list of conditions and the following disclaimer in the documentation 

12# and/or other materials provided with the distribution. 

13# * The name of the author may not be used to endorse or promote products 

14# derived from this software without specific prior written permission. 

15# 

16# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 

17# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 

18# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 

19# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 

20# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 

21# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 

22# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 

23# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 

24# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 

25# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 

26# POSSIBILITY OF SUCH DAMAGE. 

27 

28"""Utility functions for PDF library.""" 

29__author__ = "Mathieu Fenniak" 

30__author_email__ = "biziqe@mathieu.fenniak.net" 

31 

32import functools 

33import logging 

34import os 

35import re 

36import sys 

37import warnings 

38from dataclasses import dataclass 

39from datetime import datetime, timezone 

40from io import DEFAULT_BUFFER_SIZE 

41from os import SEEK_CUR 

42from re import Pattern 

43from typing import ( 

44 IO, 

45 Any, 

46 NoReturn, 

47 TypeAlias, 

48 Union, 

49 cast, 

50) 

51 

52if sys.version_info >= (3, 11): 

53 from typing import Self 

54else: 

55 from typing_extensions import Self 

56 

57from .errors import ( 

58 STREAM_TRUNCATED_PREMATURELY, 

59 DeprecationError, 

60 LimitReachedError, 

61 PdfStreamError, 

62) 

63 

64TransformationMatrixType: TypeAlias = tuple[ 

65 tuple[float, float, float], tuple[float, float, float], tuple[float, float, float] 

66] 

67CompressedTransformationMatrix: TypeAlias = tuple[ 

68 float, float, float, float, float, float 

69] 

70 

71StreamType = IO[Any] 

72BinaryStreamType = IO[bytes] 

73StrByteType = Union[str, StreamType] 

74 

75 

76def parse_iso8824_date(text: str | None) -> datetime | None: 

77 orgtext = text 

78 if not text: 

79 return None 

80 if text[0].isdigit(): 

81 text = "D:" + text 

82 if text.endswith(("Z", "z")): 

83 text += "0000" 

84 text = text.replace("z", "+").replace("Z", "+").replace("'", "") 

85 i = max(text.find("+"), text.find("-")) 

86 if i > 0 and i != len(text) - 5: 

87 text += "00" 

88 for f in ( 

89 "D:%Y", 

90 "D:%Y%m", 

91 "D:%Y%m%d", 

92 "D:%Y%m%d%H", 

93 "D:%Y%m%d%H%M", 

94 "D:%Y%m%d%H%M%S", 

95 "D:%Y%m%d%H%M%S%z", 

96 ): 

97 try: 

98 d = datetime.strptime(text, f) # noqa: DTZ007 

99 except ValueError: 

100 continue 

101 else: 

102 if text.endswith("+0000"): 

103 d = d.replace(tzinfo=timezone.utc) 

104 return d 

105 raise ValueError(f"Can not convert date: {orgtext}") 

106 

107 

108def format_iso8824_date(dt: datetime) -> str: 

109 """ 

110 Convert a datetime object to PDF date string format. 

111 

112 Converts datetime to the PDF date format D:YYYYMMDDHHmmSSOHH'mm 

113 as specified in the PDF Reference. 

114 

115 Args: 

116 dt: A datetime object to convert. 

117 

118 Returns: 

119 A date string in PDF format. 

120 """ 

121 date_str = dt.strftime("D:%Y%m%d%H%M%S") 

122 if dt.tzinfo is not None: 

123 offset = dt.utcoffset() 

124 assert offset is not None 

125 total_seconds = int(offset.total_seconds()) 

126 hours, remainder = divmod(abs(total_seconds), 3600) 

127 minutes = remainder // 60 

128 sign = "+" if total_seconds >= 0 else "-" 

129 date_str += f"{sign}{hours:02d}'{minutes:02d}'" 

130 return date_str 

131 

132 

133def _get_max_pdf_version_header(header1: str, header2: str) -> str: 

134 versions = ( 

135 "%PDF-1.3", 

136 "%PDF-1.4", 

137 "%PDF-1.5", 

138 "%PDF-1.6", 

139 "%PDF-1.7", 

140 "%PDF-2.0", 

141 ) 

142 pdf_header_indices = [] 

143 if header1 in versions: 

144 pdf_header_indices.append(versions.index(header1)) 

145 if header2 in versions: 

146 pdf_header_indices.append(versions.index(header2)) 

147 if len(pdf_header_indices) == 0: 

148 raise ValueError(f"Neither {header1!r} nor {header2!r} are proper headers") 

149 return versions[max(pdf_header_indices)] 

150 

151 

152WHITESPACES = (b"\x00", b"\t", b"\n", b"\f", b"\r", b" ") 

153WHITESPACES_AS_BYTES = b"".join(WHITESPACES) 

154WHITESPACES_AS_REGEXP = b"[" + WHITESPACES_AS_BYTES + b"]" 

155 

156 

157def read_until_whitespace(stream: StreamType, max_bytes: int | None = None, strict: bool = False) -> bytes: 

158 """ 

159 Read non-whitespace characters and return them. 

160 

161 Stops upon encountering whitespace or when max_bytes is reached. 

162 

163 Args: 

164 stream: The data stream from which was read. 

165 max_bytes: The maximum number of bytes which are considered valid. One more byte 

166 will always be read from the stream. 

167 strict: Whether to raise an exception if the token exceeds max_bytes. 

168 If False, a warning is logged and only the first max_bytes are returned. 

169 

170 Returns: 

171 The data which was read. 

172 

173 """ 

174 txt = bytearray() 

175 while True: 

176 tok = stream.read(1) 

177 if tok.isspace() or tok in WHITESPACES or not tok: 

178 break 

179 if max_bytes is not None and len(txt) >= max_bytes: 

180 if strict: 

181 raise LimitReachedError(f"Token exceeds maximum length of {max_bytes} bytes.") 

182 logger_warning( 

183 "Token exceeds maximum length of %(max_bytes)d bytes.", source=__name__, max_bytes=max_bytes 

184 ) 

185 break 

186 txt += tok 

187 return bytes(txt) 

188 

189 

190def read_non_whitespace(stream: BinaryStreamType) -> bytes: 

191 """ 

192 Find and read the next non-whitespace character (ignores whitespace). 

193 

194 Args: 

195 stream: The data stream from which was read. 

196 

197 Returns: 

198 The data which was read. 

199 

200 """ 

201 tok = stream.read(1) 

202 while tok in WHITESPACES: 

203 tok = stream.read(1) 

204 return tok 

205 

206 

207def skip_over_whitespace(stream: StreamType) -> bool: 

208 """ 

209 Similar to read_non_whitespace, but return a boolean if at least one 

210 whitespace character was read. 

211 

212 Args: 

213 stream: The data stream from which was read. 

214 

215 Returns: 

216 True if one or more whitespace was skipped, otherwise return False. 

217 

218 """ 

219 tok = stream.read(1) 

220 cnt = 0 

221 while tok in WHITESPACES: 

222 cnt += 1 

223 tok = stream.read(1) 

224 return cnt > 0 

225 

226 

227def check_if_whitespace_only(value: bytes) -> bool: 

228 """ 

229 Check if the given value consists of whitespace characters only. 

230 

231 Args: 

232 value: The bytes to check. 

233 

234 Returns: 

235 True if the value only has whitespace characters, otherwise return False. 

236 

237 """ 

238 return all(b in WHITESPACES_AS_BYTES for b in value) 

239 

240 

241NEUTRAL_CHARACTER_RANGES = ( 

242 ("\x00", "\x2F"), # ASCII control codes, space, and early punctuation (!"#$%) 

243 ("\x3A", "\x40"), # ASCII operators and punctuation between digits & A (:;<=>?@) 

244 ("\u0660", "\u066D"), # Arabic-Indic digits and Arabic numeric separators 

245 ("\u06F0", "\u06F9"), # Extended Arabic-Indic (Persian) digits 

246 ("\u2000", "\u206F"), # General punctuation 

247 ("\u20A0", "\u21FF"), # Currency symbols, diacritical marks, letter-like symbols, number forms, arrows 

248) 

249 

250 

251def is_char_neutral(char: str, custom_special_characters: str = "") -> bool: 

252 """Check if a character is part of neutral character ranges""" 

253 if any(start <= char <= end for start, end in NEUTRAL_CHARACTER_RANGES): 

254 return True 

255 

256 return bool(custom_special_characters and char in custom_special_characters) 

257 

258 

259RTL_CHARACTER_RANGES = ( 

260 ("\u0590", "\u08FF"), # Hebrew, Arabic, Syriac, Thaana, N'Ko, etc. 

261 ("\uFB1D", "\uFDFF"), # Hebrew & Arabic Presentation Forms-A 

262 ("\uFE70", "\uFEFF"), # Arabic Presentation Forms-B 

263) 

264 

265 

266def is_char_rtl(char: str, custom_rtl_min: str = "", custom_rtl_max: str = "") -> bool: 

267 """Check if a character is part of RTL character ranges""" 

268 if any(start <= char <= end for start, end in RTL_CHARACTER_RANGES): 

269 return True 

270 

271 return bool(custom_rtl_min and custom_rtl_max and (custom_rtl_min <= char <= custom_rtl_max)) 

272 

273 

274def skip_over_comment(stream: StreamType) -> None: 

275 tok = stream.read(1) 

276 stream.seek(-1, 1) 

277 if tok == b"%": 

278 while tok not in (b"\n", b"\r"): 

279 tok = stream.read(1) 

280 if tok == b"": 

281 raise PdfStreamError("File ended unexpectedly.") 

282 

283 

284def skip_over_comments(stream: StreamType, *, limit: int | None = None) -> None: 

285 """ 

286 Skip consecutive leading comments and the whitespace following each one. 

287 

288 The stream must be positioned at the first comment, if any. If the next 

289 character is not ``%``, the stream position is unchanged. If only whitespace 

290 follows the last comment before EOF, leave the stream at the last whitespace 

291 byte, preserving the existing read_object behaviour for a missing object. 

292 

293 Args: 

294 stream: The stream to read from. 

295 limit: The maximum number of comments to skip, or ``None`` for no limit. 

296 

297 Raises: 

298 LimitReachedError: If another comment follows after ``limit`` comments; 

299 the stream remains at its ``%`` without reading its body. 

300 PdfStreamError: If a comment ends before a line ending. 

301 

302 """ 

303 tok = stream.read(1) 

304 stream.seek(-len(tok), 1) 

305 comment_count = 0 

306 while tok == b"%": 

307 if limit is not None and comment_count >= limit: 

308 raise LimitReachedError(f"Maximum number of leading comments reached: {limit}.") 

309 skip_over_comment(stream) 

310 tok = read_non_whitespace(stream) 

311 stream.seek(-1, 1) 

312 comment_count += 1 

313 

314 

315def read_until_regex(*, stream: StreamType, regex: Pattern[bytes], length: int = sys.maxsize) -> bytes: 

316 """ 

317 Read until the regular expression pattern matched (ignore the match). 

318 Treats EOF on the underlying stream as the end of the token to be matched. 

319 

320 Args: 

321 stream: The stream to read from. 

322 regex: The pattern to search for. 

323 length: The (approximated) maximum number of bytes to read before raising an exception. 

324 

325 Returns: 

326 The read bytes. 

327 

328 """ 

329 parts: list[bytes] = [] 

330 total_length = 0 

331 tail = b"" 

332 chunk_size = 16 

333 while True: 

334 token = stream.read(chunk_size) 

335 if not token: 

336 return b"".join(parts) 

337 token_length = len(token) 

338 if (current_length := total_length + token_length) >= length: 

339 raise LimitReachedError( 

340 f"Read stream length of {current_length} exceeds maximum allowed length of {length}." 

341 ) 

342 

343 # Search overlap of previous tail + new chunk to catch 

344 # multi-byte regex matches spanning chunk boundaries. 

345 current_buffer = tail + token 

346 search_match = regex.search(current_buffer) 

347 parts.append(token) 

348 if search_match is not None: 

349 overlap = len(tail) 

350 actual_start = total_length - overlap + search_match.start() 

351 stream.seek(actual_start - total_length - token_length, 1) 

352 return b"".join(parts)[:actual_start] 

353 total_length += token_length 

354 

355 # Fixed overlap: 16 bytes is sufficient for the short 

356 # delimiter patterns used in PDF parsing. 

357 tail = token[-16:] 

358 if chunk_size < 8192: 

359 chunk_size <<= 1 

360 

361 

362def read_block_backwards(stream: BinaryStreamType, to_read: int) -> bytes: 

363 """ 

364 Given a stream at position X, read a block of size to_read ending at position X. 

365 

366 This changes the stream's position to the beginning of where the block was 

367 read. 

368 

369 Args: 

370 stream: 

371 to_read: 

372 

373 Returns: 

374 The data which was read. 

375 

376 """ 

377 if stream.tell() < to_read: 

378 raise PdfStreamError("Could not read malformed PDF file") 

379 # Seek to the start of the block we want to read. 

380 stream.seek(-to_read, SEEK_CUR) 

381 read = stream.read(to_read) 

382 # Seek to the start of the block we read after reading it. 

383 stream.seek(-to_read, SEEK_CUR) 

384 return read 

385 

386 

387def read_previous_line(stream: StreamType) -> bytes: 

388 """ 

389 Given a byte stream with current position X, return the previous line. 

390 

391 All characters between the first CR/LF byte found before X 

392 (or, the start of the file, if no such byte is found) and position X 

393 After this call, the stream will be positioned one byte after the 

394 first non-CRLF character found beyond the first CR/LF byte before X, 

395 or, if no such byte is found, at the beginning of the stream. 

396 

397 Args: 

398 stream: StreamType: 

399 

400 Returns: 

401 The data which was read. 

402 

403 """ 

404 line_content = [] 

405 found_crlf = False 

406 if stream.tell() == 0: 

407 raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY) 

408 while True: 

409 to_read = min(DEFAULT_BUFFER_SIZE, stream.tell()) 

410 if to_read == 0: 

411 break 

412 # Read the block. After this, our stream will be one 

413 # beyond the initial position. 

414 block = read_block_backwards(stream, to_read) 

415 idx = len(block) - 1 

416 if not found_crlf: 

417 # We haven't found our first CR/LF yet. 

418 # Read off characters until we hit one. 

419 while idx >= 0 and block[idx] not in b"\r\n": 

420 idx -= 1 

421 if idx >= 0: 

422 found_crlf = True 

423 if found_crlf: 

424 # We found our first CR/LF already (on this block or 

425 # a previous one). 

426 # Our combined line is the remainder of the block 

427 # plus any previously read blocks. 

428 line_content.append(block[idx + 1 :]) 

429 # Continue to read off any more CRLF characters. 

430 while idx >= 0 and block[idx] in b"\r\n": 

431 idx -= 1 

432 else: 

433 # Didn't find CR/LF yet - add this block to our 

434 # previously read blocks and continue. 

435 line_content.append(block) 

436 if idx >= 0: 

437 # We found the next non-CRLF character. 

438 # Set the stream position correctly, then break 

439 stream.seek(idx + 1, SEEK_CUR) 

440 break 

441 # Join all the blocks in the line (which are in reverse order) 

442 return b"".join(line_content[::-1]) 

443 

444 

445def matrix_multiply( 

446 a: TransformationMatrixType, b: TransformationMatrixType 

447) -> TransformationMatrixType: 

448 return tuple( # type: ignore[return-value] 

449 tuple(sum(float(i) * float(j) for i, j in zip(row, col)) for col in zip(*b)) 

450 for row in a 

451 ) 

452 

453 

454def mark_location(stream: StreamType) -> None: 

455 """Create text file showing current location in context.""" 

456 # Mainly for debugging 

457 radius = 5000 

458 stream.seek(-radius, 1) 

459 with open("pypdf_pdfLocation.txt", "wb") as output_fh: 

460 output_fh.write(stream.read(radius)) 

461 output_fh.write(b"HERE") 

462 output_fh.write(stream.read(radius)) 

463 stream.seek(-radius, 1) 

464 

465 

466def deprecate(msg: str, stacklevel: int = 3) -> None: 

467 warnings.warn(msg, DeprecationWarning, stacklevel=stacklevel) 

468 

469 

470def deprecation(msg: str) -> NoReturn: 

471 raise DeprecationError(msg) 

472 

473 

474def deprecate_with_replacement(old_name: str, new_name: str, removed_in: str) -> None: 

475 """Issue a warning that a feature will be removed, but has a replacement.""" 

476 deprecate( 

477 f"{old_name} is deprecated and will be removed in pypdf {removed_in}. Use {new_name} instead.", 

478 4, 

479 ) 

480 

481 

482def deprecation_with_replacement(old_name: str, new_name: str, removed_in: str) -> NoReturn: 

483 """Raise an exception that a feature was already removed, but has a replacement.""" 

484 deprecation( 

485 f"{old_name} is deprecated and was removed in pypdf {removed_in}. Use {new_name} instead." 

486 ) 

487 

488 

489def deprecate_no_replacement(name: str, removed_in: str) -> None: 

490 """Issue a warning that a feature will be removed without replacement.""" 

491 deprecate(f"{name} is deprecated and will be removed in pypdf {removed_in}.", 4) 

492 

493 

494def deprecation_no_replacement(name: str, removed_in: str) -> NoReturn: 

495 """Raise an exception that a feature was already removed without replacement.""" 

496 deprecation(f"{name} is deprecated and was removed in pypdf {removed_in}.") 

497 

498 

499def logger_error(message: str, *, source: str, **values: Any) -> None: 

500 """ 

501 Use this instead of logger.error directly. 

502 

503 That allows people to overwrite it more easily. 

504 

505 See the docs on when to use which: 

506 https://pypdf.readthedocs.io/en/latest/user/suppress-warnings.html 

507 """ 

508 if values: 

509 logging.getLogger(source).error(message, values) 

510 else: 

511 logging.getLogger(source).error(message) 

512 

513 

514def logger_warning(message: str, *, source: str, **values: Any) -> None: 

515 """ 

516 Use this instead of logger.warning directly. 

517 

518 That allows people to overwrite it more easily. 

519 

520 ## Exception, warnings.warn, logger_warning 

521 - Exceptions should be used if the user should write code that deals with 

522 an error case, e.g. the PDF being completely broken. 

523 - warnings.warn should be used if the user needs to fix their code, e.g. 

524 DeprecationWarnings 

525 - logger_warning should be used if the user needs to know that an issue was 

526 handled by pypdf, e.g. a non-compliant PDF being read in a way that 

527 pypdf could apply a robustness fix to still read it. This applies mainly 

528 to strict=False mode. 

529 """ 

530 if values: 

531 logging.getLogger(source).warning(message, values) 

532 else: 

533 # Keep parity with logger_error and support plain warning messages. 

534 # Passing an empty dict to logging is not equivalent to passing no args: 

535 # plain messages would fail while being formatted. 

536 logging.getLogger(source).warning(message) 

537 

538 

539def rename_kwargs( 

540 func_name: str, kwargs: dict[str, Any], aliases: dict[str, str], fail: bool = False 

541) -> None: 

542 """ 

543 Helper function to deprecate arguments. 

544 

545 Args: 

546 func_name: Name of the function to be deprecated 

547 kwargs: 

548 aliases: 

549 fail: 

550 

551 """ 

552 for old_term, new_term in aliases.items(): 

553 if old_term in kwargs: 

554 if fail: 

555 raise DeprecationError( 

556 f"{old_term} is deprecated as an argument. Use {new_term} instead" 

557 ) 

558 if new_term in kwargs: 

559 raise TypeError( 

560 f"{func_name} received both {old_term} and {new_term} as " 

561 f"an argument. {old_term} is deprecated. " 

562 f"Use {new_term} instead." 

563 ) 

564 kwargs[new_term] = kwargs.pop(old_term) 

565 warnings.warn( 

566 message=( 

567 f"{old_term} is deprecated as an argument. Use {new_term} instead" 

568 ), 

569 category=DeprecationWarning, 

570 stacklevel=3, 

571 ) 

572 

573 

574def _human_readable_bytes(bytes: int) -> str: 

575 if bytes < 10**3: 

576 return f"{bytes} Byte" 

577 if bytes < 10**6: 

578 return f"{bytes / 10**3:.1f} kB" 

579 if bytes < 10**9: 

580 return f"{bytes / 10**6:.1f} MB" 

581 return f"{bytes / 10**9:.1f} GB" 

582 

583 

584def get_stream_size(stream: StreamType) -> int: 

585 if hasattr(stream, "getbuffer"): 

586 with stream.getbuffer() as view: 

587 return cast(int, view.nbytes) 

588 

589 position = stream.tell() 

590 stream.seek(0, os.SEEK_END) 

591 size = stream.tell() 

592 stream.seek(position) 

593 return size 

594 

595 

596def get_stream_data(stream: StreamType) -> bytes: 

597 if hasattr(stream, "getbuffer"): 

598 with stream.getbuffer() as view: 

599 return bytes(view) 

600 

601 position = stream.tell() 

602 stream.seek(0, os.SEEK_SET) 

603 data = stream.read(-1) 

604 stream.seek(position) 

605 return cast(bytes, data) 

606 

607 

608# The following class has been copied from Django: 

609# https://github.com/django/django/blob/adae619426b6f50046b3daaa744db52989c9d6db/django/utils/functional.py#L51-L65 

610# It received some modifications to comply with our own coding standards. 

611# 

612# Original license: 

613# 

614# --------------------------------------------------------------------------------- 

615# Copyright (c) Django Software Foundation and individual contributors. 

616# All rights reserved. 

617# 

618# Redistribution and use in source and binary forms, with or without modification, 

619# are permitted provided that the following conditions are met: 

620# 

621# 1. Redistributions of source code must retain the above copyright notice, 

622# this list of conditions and the following disclaimer. 

623# 

624# 2. Redistributions in binary form must reproduce the above copyright 

625# notice, this list of conditions and the following disclaimer in the 

626# documentation and/or other materials provided with the distribution. 

627# 

628# 3. Neither the name of Django nor the names of its contributors may be used 

629# to endorse or promote products derived from this software without 

630# specific prior written permission. 

631# 

632# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 

633# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 

634# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 

635# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 

636# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 

637# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 

638# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 

639# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 

640# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 

641# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 

642# --------------------------------------------------------------------------------- 

643class classproperty: # noqa: N801 

644 """ 

645 Decorator that converts a method with a single cls argument into a property 

646 that can be accessed directly from the class. 

647 """ 

648 

649 def __init__(self, method=None) -> None: # type: ignore[no-untyped-def] # noqa: ANN001 

650 self.fget = method 

651 

652 def __get__(self, instance, cls=None) -> Any: # type: ignore[no-untyped-def] # noqa: ANN001 

653 return self.fget(cls) 

654 

655 def getter(self, method) -> Self: # type: ignore[no-untyped-def] # noqa: ANN001 

656 self.fget = method 

657 return self 

658 

659 

660@dataclass 

661class File: 

662 from .generic import IndirectObject # noqa: PLC0415 

663 

664 name: str = "" 

665 """ 

666 Filename as identified within the PDF file. 

667 """ 

668 data: bytes = b"" 

669 """ 

670 Data as bytes. 

671 """ 

672 indirect_reference: IndirectObject | None = None 

673 """ 

674 Reference to the object storing the stream. 

675 """ 

676 

677 def __str__(self) -> str: 

678 return f"{self.__class__.__name__}(name={self.name}, data: {_human_readable_bytes(len(self.data))})" 

679 

680 def __repr__(self) -> str: 

681 return self.__str__()[:-1] + f", hash: {hash(self.data)})" 

682 

683 

684@functools.total_ordering 

685class Version: 

686 COMPONENT_PATTERN = re.compile(r"^(\d+)(.*)$") 

687 

688 def __init__(self, version_str: str) -> None: 

689 self.version_str = version_str 

690 self.components = self._parse_version(version_str) 

691 

692 def _parse_version(self, version_str: str) -> list[tuple[int, str]]: 

693 components = version_str.split(".") 

694 parsed_components = [] 

695 for component in components: 

696 match = Version.COMPONENT_PATTERN.match(component) 

697 if not match: 

698 parsed_components.append((0, component)) 

699 continue 

700 integer_prefix = match.group(1) 

701 suffix = match.group(2) 

702 parsed_components.append((int(integer_prefix), suffix)) 

703 return parsed_components 

704 

705 def __eq__(self, other: object) -> bool: 

706 if not isinstance(other, Version): 

707 return False 

708 return self.components == other.components 

709 

710 def __hash__(self) -> int: 

711 # Convert to tuple as lists cannot be hashed. 

712 return hash((self.__class__, tuple(self.components))) 

713 

714 def __lt__(self, other: Any) -> bool: 

715 if not isinstance(other, Version): 

716 raise ValueError(f"Version cannot be compared against {type(other)}") 

717 

718 for self_component, other_component in zip(self.components, other.components): 

719 self_value, self_suffix = self_component 

720 other_value, other_suffix = other_component 

721 

722 if self_value < other_value: 

723 return True 

724 if self_value > other_value: 

725 return False 

726 

727 if self_suffix < other_suffix: 

728 return True 

729 if self_suffix > other_suffix: 

730 return False 

731 

732 return len(self.components) < len(other.components) 

733 

734 

735@dataclass 

736class _TraversalState: 

737 """Sometimes we need mutable objects which just count something.""" 

738 entry_count: int = 0 

739 has_logged: bool = False