Source code

Download source archive ↓

src/pypdf/_utils.py

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 inspect
34import logging
35import os
36import re
37import sys
38import warnings
39from collections.abc import Callable
40from dataclasses import dataclass
41from datetime import datetime, timezone
42from io import DEFAULT_BUFFER_SIZE
43from os import SEEK_CUR
44from re import Pattern
45from typing import (
46    IO,
47    Any,
48    NoReturn,
49    ParamSpec,
50    TypeAlias,
51    TypeVar,
52    cast,
53)
54
55if sys.version_info >= (3, 11):
56    from typing import Self
57else:
58    from typing_extensions import Self
59
60from .errors import (
61    STREAM_TRUNCATED_PREMATURELY,
62    DeprecationError,
63    LimitReachedError,
64    PdfStreamError,
65)
66
67TransformationMatrixType: TypeAlias = tuple[
68    tuple[float, float, float], tuple[float, float, float], tuple[float, float, float]
69]
70CompressedTransformationMatrix: TypeAlias = tuple[
71    float, float, float, float, float, float
72]
73
74StreamType = IO[Any]
75BinaryStreamType = IO[bytes]
76StrByteType = str | StreamType
77
78
79def parse_iso8824_date(text: str | None) -> datetime | None:
80    orgtext = text
81    if not text:
82        return None
83    if text[0].isdigit():
84        text = "D:" + text
85    if text.endswith(("Z", "z")):
86        text += "0000"
87    text = text.replace("z", "+").replace("Z", "+").replace("'", "")
88    i = max(text.find("+"), text.find("-"))
89    if i > 0 and i != len(text) - 5:
90        text += "00"
91    for f in (
92        "D:%Y",
93        "D:%Y%m",
94        "D:%Y%m%d",
95        "D:%Y%m%d%H",
96        "D:%Y%m%d%H%M",
97        "D:%Y%m%d%H%M%S",
98        "D:%Y%m%d%H%M%S%z",
99    ):
100        try:
101            d = datetime.strptime(text, f)  # noqa: DTZ007
102        except ValueError:
103            continue
104        else:
105            if text.endswith("+0000"):
106                d = d.replace(tzinfo=timezone.utc)
107            return d
108    raise ValueError(f"Can not convert date: {orgtext}")
109
110
111def format_iso8824_date(dt: datetime) -> str:
112    """
113    Convert a datetime object to PDF date string format.
114
115    Converts datetime to the PDF date format D:YYYYMMDDHHmmSSOHH'mm
116    as specified in the PDF Reference.
117
118    Args:
119        dt: A datetime object to convert.
120
121    Returns:
122        A date string in PDF format.
123    """
124    date_str = dt.strftime("D:%Y%m%d%H%M%S")
125    if dt.tzinfo is not None:
126        offset = dt.utcoffset()
127        assert offset is not None
128        total_seconds = int(offset.total_seconds())
129        hours, remainder = divmod(abs(total_seconds), 3600)
130        minutes = remainder // 60
131        sign = "+" if total_seconds >= 0 else "-"
132        date_str += f"{sign}{hours:02d}'{minutes:02d}'"
133    return date_str
134
135
136def _get_max_pdf_version_header(header1: str, header2: str) -> str:
137    versions = (
138        "%PDF-1.3",
139        "%PDF-1.4",
140        "%PDF-1.5",
141        "%PDF-1.6",
142        "%PDF-1.7",
143        "%PDF-2.0",
144    )
145    pdf_header_indices = []
146    if header1 in versions:
147        pdf_header_indices.append(versions.index(header1))
148    if header2 in versions:
149        pdf_header_indices.append(versions.index(header2))
150    if len(pdf_header_indices) == 0:
151        raise ValueError(f"Neither {header1!r} nor {header2!r} are proper headers")
152    return versions[max(pdf_header_indices)]
153
154
155WHITESPACES = (b"\x00", b"\t", b"\n", b"\f", b"\r", b" ")
156WHITESPACES_AS_BYTES = b"".join(WHITESPACES)
157WHITESPACES_AS_REGEXP = b"[" + WHITESPACES_AS_BYTES + b"]"
158
159
160def read_until_whitespace(stream: StreamType, max_bytes: int | None = None, strict: bool = False) -> bytes:
161    """
162    Read non-whitespace characters and return them.
163
164    Stops upon encountering whitespace or when max_bytes is reached.
165
166    Args:
167        stream: The data stream from which was read.
168        max_bytes: The maximum number of bytes which are considered valid. One more byte
169            will always be read from the stream.
170        strict: Whether to raise an exception if the token exceeds max_bytes.
171            If False, a warning is logged and only the first max_bytes are returned.
172
173    Returns:
174        The data which was read.
175
176    """
177    txt = bytearray()
178    while True:
179        tok = stream.read(1)
180        if tok.isspace() or tok in WHITESPACES or not tok:
181            break
182        if max_bytes is not None and len(txt) >= max_bytes:
183            if strict:
184                raise LimitReachedError(f"Token exceeds maximum length of {max_bytes} bytes.")
185            logger_warning(
186                "Token exceeds maximum length of %(max_bytes)d bytes.", source=__name__, max_bytes=max_bytes
187            )
188            break
189        txt += tok
190    return bytes(txt)
191
192
193def read_non_whitespace(stream: BinaryStreamType) -> bytes:
194    """
195    Find and read the next non-whitespace character (ignores whitespace).
196
197    Args:
198        stream: The data stream from which was read.
199
200    Returns:
201        The data which was read.
202
203    """
204    tok = stream.read(1)
205    while tok in WHITESPACES:
206        tok = stream.read(1)
207    return tok
208
209
210def skip_over_whitespace(stream: StreamType) -> bool:
211    """
212    Similar to read_non_whitespace, but return a boolean if at least one
213    whitespace character was read.
214
215    Args:
216        stream: The data stream from which was read.
217
218    Returns:
219        True if one or more whitespace was skipped, otherwise return False.
220
221    """
222    tok = stream.read(1)
223    cnt = 0
224    while tok in WHITESPACES:
225        cnt += 1
226        tok = stream.read(1)
227    return cnt > 0
228
229
230def check_if_whitespace_only(value: bytes) -> bool:
231    """
232    Check if the given value consists of whitespace characters only.
233
234    Args:
235        value: The bytes to check.
236
237    Returns:
238        True if the value only has whitespace characters, otherwise return False.
239
240    """
241    return all(b in WHITESPACES_AS_BYTES for b in value)
242
243
244NEUTRAL_CHARACTER_RANGES = (
245    ("\x00", "\x2F"),      # ASCII control codes, space, and early punctuation (!"#$%)
246    ("\x3A", "\x40"),      # ASCII operators and punctuation between digits & A (:;<=>?@)
247    ("\u0660", "\u066D"),  # Arabic-Indic digits and Arabic numeric separators
248    ("\u06F0", "\u06F9"),  # Extended Arabic-Indic (Persian) digits
249    ("\u2000", "\u206F"),  # General punctuation
250    ("\u20A0", "\u21FF"),  # Currency symbols, diacritical marks, letter-like symbols, number forms, arrows
251)
252
253
254def is_char_neutral(char: str, custom_special_characters: str = "") -> bool:
255    """Check if a character is part of neutral character ranges"""
256    if any(start <= char <= end for start, end in NEUTRAL_CHARACTER_RANGES):
257        return True
258
259    return bool(custom_special_characters and char in custom_special_characters)
260
261
262RTL_CHARACTER_RANGES = (
263    ("\u0590", "\u08FF"),  # Hebrew, Arabic, Syriac, Thaana, N'Ko, etc.
264    ("\uFB1D", "\uFDFF"),  # Hebrew & Arabic Presentation Forms-A
265    ("\uFE70", "\uFEFF"),  # Arabic Presentation Forms-B
266)
267
268
269def is_char_rtl(char: str, custom_rtl_min: str = "", custom_rtl_max: str = "") -> bool:
270    """Check if a character is part of RTL character ranges"""
271    if any(start <= char <= end for start, end in RTL_CHARACTER_RANGES):
272        return True
273
274    return bool(custom_rtl_min and custom_rtl_max and (custom_rtl_min <= char <= custom_rtl_max))
275
276
277def skip_over_comment(stream: StreamType) -> None:
278    tok = stream.read(1)
279    stream.seek(-1, 1)
280    if tok == b"%":
281        while tok not in (b"\n", b"\r"):
282            tok = stream.read(1)
283            if tok == b"":
284                raise PdfStreamError("File ended unexpectedly.")
285
286
287def skip_over_comments(stream: StreamType, *, limit: int | None = None) -> None:
288    """
289    Skip consecutive leading comments and the whitespace following each one.
290
291    The stream must be positioned at the first comment, if any. If the next
292    character is not ``%``, the stream position is unchanged. If only whitespace
293    follows the last comment before EOF, leave the stream at the last whitespace
294    byte, preserving the existing read_object behaviour for a missing object.
295
296    Args:
297        stream: The stream to read from.
298        limit: The maximum number of comments to skip, or ``None`` for no limit.
299
300    Raises:
301        LimitReachedError: If another comment follows after ``limit`` comments;
302            the stream remains at its ``%`` without reading its body.
303        PdfStreamError: If a comment ends before a line ending.
304
305    """
306    tok = stream.read(1)
307    stream.seek(-len(tok), 1)
308    comment_count = 0
309    while tok == b"%":
310        if limit is not None and comment_count >= limit:
311            raise LimitReachedError(f"Maximum number of leading comments reached: {limit}.")
312        skip_over_comment(stream)
313        tok = read_non_whitespace(stream)
314        stream.seek(-1, 1)
315        comment_count += 1
316
317
318def read_until_regex(*, stream: StreamType, regex: Pattern[bytes], length: int = sys.maxsize) -> bytes:
319    """
320    Read until the regular expression pattern matched (ignore the match).
321    Treats EOF on the underlying stream as the end of the token to be matched.
322
323    Args:
324        stream: The stream to read from.
325        regex: The pattern to search for.
326        length: The (approximated) maximum number of bytes to read before raising an exception.
327
328    Returns:
329        The read bytes.
330
331    """
332    parts: list[bytes] = []
333    total_length = 0
334    tail = b""
335    chunk_size = 16
336    while True:
337        token = stream.read(chunk_size)
338        if not token:
339            return b"".join(parts)
340        token_length = len(token)
341        if (current_length := total_length + token_length) >= length:
342            raise LimitReachedError(
343                f"Read stream length of {current_length} exceeds maximum allowed length of {length}."
344            )
345
346        # Search overlap of previous tail + new chunk to catch
347        # multi-byte regex matches spanning chunk boundaries.
348        current_buffer = tail + token
349        search_match = regex.search(current_buffer)
350        parts.append(token)
351        if search_match is not None:
352            overlap = len(tail)
353            actual_start = total_length - overlap + search_match.start()
354            stream.seek(actual_start - total_length - token_length, 1)
355            return b"".join(parts)[:actual_start]
356        total_length += token_length
357
358        # Fixed overlap: 16 bytes is sufficient for the short
359        # delimiter patterns used in PDF parsing.
360        tail = token[-16:]
361        if chunk_size < 8192:
362            chunk_size <<= 1
363
364
365def read_block_backwards(stream: BinaryStreamType, to_read: int) -> bytes:
366    """
367    Given a stream at position X, read a block of size to_read ending at position X.
368
369    This changes the stream's position to the beginning of where the block was
370    read.
371
372    Args:
373        stream:
374        to_read:
375
376    Returns:
377        The data which was read.
378
379    """
380    if stream.tell() < to_read:
381        raise PdfStreamError("Could not read malformed PDF file")
382    # Seek to the start of the block we want to read.
383    stream.seek(-to_read, SEEK_CUR)
384    read = stream.read(to_read)
385    # Seek to the start of the block we read after reading it.
386    stream.seek(-to_read, SEEK_CUR)
387    return read
388
389
390def read_previous_line(stream: StreamType) -> bytes:
391    """
392    Given a byte stream with current position X, return the previous line.
393
394    All characters between the first CR/LF byte found before X
395    (or, the start of the file, if no such byte is found) and position X
396    After this call, the stream will be positioned one byte after the
397    first non-CRLF character found beyond the first CR/LF byte before X,
398    or, if no such byte is found, at the beginning of the stream.
399
400    Args:
401        stream: StreamType:
402
403    Returns:
404        The data which was read.
405
406    """
407    line_content = []
408    found_crlf = False
409    if stream.tell() == 0:
410        raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY)
411    while True:
412        to_read = min(DEFAULT_BUFFER_SIZE, stream.tell())
413        if to_read == 0:
414            break
415        # Read the block. After this, our stream will be one
416        # beyond the initial position.
417        block = read_block_backwards(stream, to_read)
418        idx = len(block) - 1
419        if not found_crlf:
420            # We haven't found our first CR/LF yet.
421            # Read off characters until we hit one.
422            while idx >= 0 and block[idx] not in b"\r\n":
423                idx -= 1
424            if idx >= 0:
425                found_crlf = True
426        if found_crlf:
427            # We found our first CR/LF already (on this block or
428            # a previous one).
429            # Our combined line is the remainder of the block
430            # plus any previously read blocks.
431            line_content.append(block[idx + 1 :])
432            # Continue to read off any more CRLF characters.
433            while idx >= 0 and block[idx] in b"\r\n":
434                idx -= 1
435        else:
436            # Didn't find CR/LF yet - add this block to our
437            # previously read blocks and continue.
438            line_content.append(block)
439        if idx >= 0:
440            # We found the next non-CRLF character.
441            # Set the stream position correctly, then break
442            stream.seek(idx + 1, SEEK_CUR)
443            break
444    # Join all the blocks in the line (which are in reverse order)
445    return b"".join(line_content[::-1])
446
447
448def matrix_multiply(
449    a: TransformationMatrixType, b: TransformationMatrixType
450) -> TransformationMatrixType:
451    return tuple(  # type: ignore[return-value]
452        tuple(sum(float(i) * float(j) for i, j in zip(row, col)) for col in zip(*b))
453        for row in a
454    )
455
456
457def mark_location(stream: StreamType) -> None:
458    """Create text file showing current location in context."""
459    # Mainly for debugging
460    radius = 5000
461    stream.seek(-radius, 1)
462    with open("pypdf_pdfLocation.txt", "wb") as output_fh:
463        output_fh.write(stream.read(radius))
464        output_fh.write(b"HERE")
465        output_fh.write(stream.read(radius))
466    stream.seek(-radius, 1)
467
468
469def deprecate(msg: str, stacklevel: int = 3) -> None:
470    warnings.warn(msg, DeprecationWarning, stacklevel=stacklevel)
471
472
473def deprecation(msg: str) -> NoReturn:
474    raise DeprecationError(msg)
475
476
477def deprecate_with_replacement(old_name: str, new_name: str, removed_in: str) -> None:
478    """Issue a warning that a feature will be removed, but has a replacement."""
479    deprecate(
480        f"{old_name} is deprecated and will be removed in pypdf {removed_in}. Use {new_name} instead.",
481        4,
482    )
483
484
485def deprecation_with_replacement(old_name: str, new_name: str, removed_in: str) -> NoReturn:
486    """Raise an exception that a feature was already removed, but has a replacement."""
487    deprecation(
488        f"{old_name} is deprecated and was removed in pypdf {removed_in}. Use {new_name} instead."
489    )
490
491
492_P = ParamSpec("_P")
493_R = TypeVar("_R")
494
495
496def deprecate_positional_arguments(removed_in: str) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]:
497    """
498    Accept positional arguments for keyword-only parameters, but issue a warning.
499
500    Use it for a function whose parameters became keyword-only. The positional
501    arguments that exceed the positional parameters are passed to the
502    keyword-only parameters in the order of the signature.
503
504    Args:
505        removed_in: The version in which positional arguments will raise an error.
506
507    Returns:
508        The decorator.
509
510    """
511    def decorator(func: Callable[_P, _R]) -> Callable[_P, _R]:
512        parameters = inspect.signature(func).parameters.values()
513        positional_count = sum(
514            parameter.kind in (parameter.POSITIONAL_ONLY, parameter.POSITIONAL_OR_KEYWORD)
515            for parameter in parameters
516        )
517        keyword_only_names = [parameter.name for parameter in parameters if parameter.kind == parameter.KEYWORD_ONLY]
518
519        @functools.wraps(func)
520        def wrapper(*args: Any, **kwargs: Any) -> Any:
521            extra_args = args[positional_count:]
522            if extra_args:
523                if len(extra_args) > len(keyword_only_names):
524                    raise TypeError(
525                        f"{func.__qualname__}() takes {positional_count + len(keyword_only_names)} "
526                        f"positional arguments but {len(args)} were given"
527                    )
528                for name, value in zip(keyword_only_names, extra_args):
529                    if name in kwargs:
530                        raise TypeError(f"{func.__qualname__}() got multiple values for argument '{name}'")
531                    kwargs[name] = value
532                deprecate_with_replacement(
533                    f"Passing positional arguments to {func.__qualname__}()", "keyword arguments", removed_in
534                )
535            return func(*args[:positional_count], **kwargs)
536
537        return cast(Callable[_P, _R], wrapper)
538
539    return decorator
540
541
542def deprecate_no_replacement(name: str, removed_in: str) -> None:
543    """Issue a warning that a feature will be removed without replacement."""
544    deprecate(f"{name} is deprecated and will be removed in pypdf {removed_in}.", 4)
545
546
547def deprecation_no_replacement(name: str, removed_in: str) -> NoReturn:
548    """Raise an exception that a feature was already removed without replacement."""
549    deprecation(f"{name} is deprecated and was removed in pypdf {removed_in}.")
550
551
552def logger_error(message: str, *, source: str, **values: Any) -> None:
553    """
554    Use this instead of logger.error directly.
555
556    That allows people to overwrite it more easily.
557
558    See the docs on when to use which:
559    https://pypdf.readthedocs.io/en/latest/user/suppress-warnings.html
560    """
561    if values:
562        logging.getLogger(source).error(message, values)
563    else:
564        logging.getLogger(source).error(message)
565
566
567def logger_warning(message: str, *, source: str, **values: Any) -> None:
568    """
569    Use this instead of logger.warning directly.
570
571    That allows people to overwrite it more easily.
572
573    ## Exception, warnings.warn, logger_warning
574    - Exceptions should be used if the user should write code that deals with
575      an error case, e.g. the PDF being completely broken.
576    - warnings.warn should be used if the user needs to fix their code, e.g.
577      DeprecationWarnings
578    - logger_warning should be used if the user needs to know that an issue was
579      handled by pypdf, e.g. a non-compliant PDF being read in a way that
580      pypdf could apply a robustness fix to still read it. This applies mainly
581      to strict=False mode.
582    """
583    if values:
584        logging.getLogger(source).warning(message, values)
585    else:
586        # Keep parity with logger_error and support plain warning messages.
587        # Passing an empty dict to logging is not equivalent to passing no args:
588        # plain messages would fail while being formatted.
589        logging.getLogger(source).warning(message)
590
591
592def rename_kwargs(
593    func_name: str, kwargs: dict[str, Any], aliases: dict[str, str], fail: bool = False
594) -> None:
595    """
596    Helper function to deprecate arguments.
597
598    Args:
599        func_name: Name of the function to be deprecated
600        kwargs:
601        aliases:
602        fail:
603
604    """
605    for old_term, new_term in aliases.items():
606        if old_term in kwargs:
607            if fail:
608                raise DeprecationError(
609                    f"{old_term} is deprecated as an argument. Use {new_term} instead"
610                )
611            if new_term in kwargs:
612                raise TypeError(
613                    f"{func_name} received both {old_term} and {new_term} as "
614                    f"an argument. {old_term} is deprecated. "
615                    f"Use {new_term} instead."
616                )
617            kwargs[new_term] = kwargs.pop(old_term)
618            warnings.warn(
619                message=(
620                    f"{old_term} is deprecated as an argument. Use {new_term} instead"
621                ),
622                category=DeprecationWarning,
623                stacklevel=3,
624            )
625
626
627def _human_readable_bytes(bytes: int) -> str:
628    if bytes < 10**3:
629        return f"{bytes} Byte"
630    if bytes < 10**6:
631        return f"{bytes / 10**3:.1f} kB"
632    if bytes < 10**9:
633        return f"{bytes / 10**6:.1f} MB"
634    return f"{bytes / 10**9:.1f} GB"
635
636
637def get_stream_size(stream: StreamType) -> int:
638    if hasattr(stream, "getbuffer"):
639        with stream.getbuffer() as view:
640            return cast(int, view.nbytes)
641
642    position = stream.tell()
643    stream.seek(0, os.SEEK_END)
644    size = stream.tell()
645    stream.seek(position)
646    return size
647
648
649def get_stream_data(stream: StreamType) -> bytes:
650    if hasattr(stream, "getbuffer"):
651        with stream.getbuffer() as view:
652            return bytes(view)
653
654    position = stream.tell()
655    stream.seek(0, os.SEEK_SET)
656    data = stream.read(-1)
657    stream.seek(position)
658    return cast(bytes, data)
659
660
661# The following class has been copied from Django:
662# https://github.com/django/django/blob/adae619426b6f50046b3daaa744db52989c9d6db/django/utils/functional.py#L51-L65
663# It received some modifications to comply with our own coding standards.
664#
665# Original license:
666#
667# ---------------------------------------------------------------------------------
668# Copyright (c) Django Software Foundation and individual contributors.
669# All rights reserved.
670#
671# Redistribution and use in source and binary forms, with or without modification,
672# are permitted provided that the following conditions are met:
673#
674#     1. Redistributions of source code must retain the above copyright notice,
675#        this list of conditions and the following disclaimer.
676#
677#     2. Redistributions in binary form must reproduce the above copyright
678#        notice, this list of conditions and the following disclaimer in the
679#        documentation and/or other materials provided with the distribution.
680#
681#     3. Neither the name of Django nor the names of its contributors may be used
682#        to endorse or promote products derived from this software without
683#        specific prior written permission.
684#
685# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
686# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
687# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
688# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
689# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
690# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
691# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
692# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
693# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
694# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
695# ---------------------------------------------------------------------------------
696class classproperty:  # noqa: N801
697    """
698    Decorator that converts a method with a single cls argument into a property
699    that can be accessed directly from the class.
700    """
701
702    def __init__(self, method=None) -> None:  # type: ignore[no-untyped-def]  # noqa: ANN001
703        self.fget = method
704
705    def __get__(self, instance, cls=None) -> Any:  # type: ignore[no-untyped-def]  # noqa: ANN001
706        return self.fget(cls)
707
708    def getter(self, method) -> Self:  # type: ignore[no-untyped-def]  # noqa: ANN001
709        self.fget = method
710        return self
711
712
713@dataclass
714class File:
715    from .generic import IndirectObject  # noqa: PLC0415
716
717    name: str = ""
718    """
719    Filename as identified within the PDF file.
720    """
721    data: bytes = b""
722    """
723    Data as bytes.
724    """
725    indirect_reference: IndirectObject | None = None
726    """
727    Reference to the object storing the stream.
728    """
729
730    def __str__(self) -> str:
731        return f"{self.__class__.__name__}(name={self.name}, data: {_human_readable_bytes(len(self.data))})"
732
733    def __repr__(self) -> str:
734        return self.__str__()[:-1] + f", hash: {hash(self.data)})"
735
736
737@functools.total_ordering
738class Version:
739    COMPONENT_PATTERN = re.compile(r"^(\d+)(.*)$")
740
741    def __init__(self, version_str: str) -> None:
742        self.version_str = version_str
743        self.components = self._parse_version(version_str)
744
745    def _parse_version(self, version_str: str) -> list[tuple[int, str]]:
746        components = version_str.split(".")
747        parsed_components = []
748        for component in components:
749            match = Version.COMPONENT_PATTERN.match(component)
750            if not match:
751                parsed_components.append((0, component))
752                continue
753            integer_prefix = match.group(1)
754            suffix = match.group(2)
755            parsed_components.append((int(integer_prefix), suffix))
756        return parsed_components
757
758    def __eq__(self, other: object) -> bool:
759        if not isinstance(other, Version):
760            return False
761        return self.components == other.components
762
763    def __hash__(self) -> int:
764        # Convert to tuple as lists cannot be hashed.
765        return hash((self.__class__, tuple(self.components)))
766
767    def __lt__(self, other: Any) -> bool:
768        if not isinstance(other, Version):
769            raise ValueError(f"Version cannot be compared against {type(other)}")
770
771        for self_component, other_component in zip(self.components, other.components):
772            self_value, self_suffix = self_component
773            other_value, other_suffix = other_component
774
775            if self_value < other_value:
776                return True
777            if self_value > other_value:
778                return False
779
780            if self_suffix < other_suffix:
781                return True
782            if self_suffix > other_suffix:
783                return False
784
785        return len(self.components) < len(other.components)
786
787
788@dataclass
789class _TraversalState:
790    """Sometimes we need mutable objects which just count something."""
791    entry_count: int = 0
792    has_logged: bool = False