Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: Add += and -= operators to ArrayObject #2510

Merged
merged 4 commits into from
Mar 10, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions pypdf/generic/_data_structures.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@

import logging
import re
import sys
from io import BytesIO
from typing import (
Any,
Expand Down Expand Up @@ -70,6 +71,7 @@
from ..errors import STREAM_TRUNCATED_PREMATURELY, PdfReadError, PdfStreamError
from ._base import (
BooleanObject,
ByteStringObject,
FloatObject,
IndirectObject,
NameObject,
Expand All @@ -81,6 +83,11 @@
from ._fit import Fit
from ._utils import read_hex_string_from_stream, read_string_from_stream

if sys.version_info >= (3, 11):
from typing import Self
else:
from typing_extensions import Self
pubpub-zz marked this conversation as resolved.
Show resolved Hide resolved

logger = logging.getLogger(__name__)
NumberSigns = b"+-"
IndirectPattern = re.compile(rb"[+-]?(\d+)\s+(\d+)\s+R[^a-zA-Z]")
Expand Down Expand Up @@ -121,6 +128,43 @@
"""Emulate DictionaryObject.items for a list (index, object)."""
return enumerate(self)

def __to_lst(self, lst: Any) -> List[Any]:
pubpub-zz marked this conversation as resolved.
Show resolved Hide resolved
# Convert to list, internal
if isinstance(lst, (list, tuple, set)):
pass
elif isinstance(lst, PdfObject):
lst = [lst]
elif isinstance(lst, str):
if lst[0] == "/":
lst = [NameObject(lst)]
else:
lst = [TextStringObject(lst)]
elif isinstance(lst, bytes):
lst = [ByteStringObject(lst)]
else: # for numbers,...
lst = [lst]
return lst

def __add__(self, lst: Any) -> "ArrayObject":
"""Allow extend with any list format or append"""
return ArrayObject(self) + ArrayObject(self.__to_lst(lst))

Check warning on line 150 in pypdf/generic/_data_structures.py

View check run for this annotation

Codecov / codecov/patch

pypdf/generic/_data_structures.py#L150

Added line #L150 was not covered by tests

def __iadd__(self, lst: Any) -> Self:
"""Allow extend with any list format or append"""
for x in self.__to_lst(lst):
self.append(x)
pubpub-zz marked this conversation as resolved.
Show resolved Hide resolved
return self

def __isub__(self, lst: Any) -> Self:
"""Allow to remove items"""
for x in self.__to_lst(lst):
try:
x = self.index(x)
del self[x]
except ValueError:
pass
return self

def write_to_stream(
self, stream: StreamType, encryption_key: Union[None, str, bytes] = None
) -> None:
Expand Down
26 changes: 26 additions & 0 deletions tests/test_generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1278,3 +1278,29 @@ def test_indirect_object_page_dimensions():
reader = PdfReader(data, strict=False)
mediabox = reader.pages[0].mediabox
assert mediabox == RectangleObject((0, 0, 792, 612))


def test_array_operators():
a = ArrayObject(
[
NumberObject(1),
NumberObject(2),
NumberObject(3),
NumberObject(4),
]
)
assert a == [1, 2, 3, 4]
a -= 2
a += "abc"
a -= (3, 4)
a += ["d", "e"]
a += BooleanObject(True)
assert a == [1, "abc", "d", "e", True]
a += "/toto"
assert isinstance(a[-1], NameObject)
assert isinstance(a[1], TextStringObject)
a += b"1234"
assert a[-1] == ByteStringObject(b"1234")
la = len(a)
a -= 300
assert len(a) == la
Loading