Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pypdf/generic/_base.py: 46%

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

433 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. 

27import binascii 

28import codecs 

29import hashlib 

30import re 

31import sys 

32from collections.abc import Callable, Sequence 

33from math import log10 

34from struct import iter_unpack 

35from typing import Any, ClassVar, Optional, TypeGuard, Union, cast 

36 

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

38 from typing import Self 

39else: 

40 from typing_extensions import Self 

41 

42from .._codecs import _pdfdoc_encoding_rev 

43from .._protocols import PdfWriterProtocol 

44from .._utils import ( 

45 WHITESPACES, 

46 StreamType, 

47 logger_warning, 

48 read_non_whitespace, 

49 read_until_regex, 

50) 

51from ..errors import STREAM_TRUNCATED_PREMATURELY, PdfReadError, PdfStreamError 

52 

53__author__ = "Mathieu Fenniak" 

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

55 

56 

57class PdfObject: 

58 # function for calculating a hash value 

59 hash_func: Callable[..., "hashlib._Hash"] = hashlib.sha1 

60 indirect_reference: Optional["IndirectObject"] 

61 

62 def hash_bin(self) -> int: 

63 """ 

64 Used to detect modified object. 

65 

66 Returns: 

67 Hash considering type and value. 

68 

69 """ 

70 raise NotImplementedError( 

71 f"{self.__class__.__name__} does not implement .hash_bin() so far" 

72 ) 

73 

74 def hash_value_data(self) -> bytes: 

75 return f"{self}".encode() 

76 

77 def hash_value(self) -> bytes: 

78 return ( 

79 f"{self.__class__.__name__}:" 

80 f"{self.hash_func(self.hash_value_data()).hexdigest()}" 

81 ).encode() 

82 

83 def replicate( 

84 self, 

85 pdf_dest: PdfWriterProtocol, 

86 ) -> "PdfObject": 

87 """ 

88 Clone object into pdf_dest (PdfWriterProtocol which is an interface for PdfWriter) 

89 without ensuring links. This is used in clone_document_from_root with incremental = True. 

90 

91 Args: 

92 pdf_dest: Target to clone to. 

93 

94 Returns: 

95 The cloned PdfObject 

96 

97 """ 

98 return self.clone(pdf_dest) 

99 

100 def clone( 

101 self, 

102 pdf_dest: PdfWriterProtocol, 

103 force_duplicate: bool = False, 

104 ignore_fields: Sequence[str | int] | None = (), 

105 ) -> "PdfObject": 

106 """ 

107 Clone object into pdf_dest (PdfWriterProtocol which is an interface for PdfWriter). 

108 

109 By default, this method will call ``_reference_clone`` (see ``_reference``). 

110 

111 

112 Args: 

113 pdf_dest: Target to clone to. 

114 force_duplicate: By default, if the object has already been cloned and referenced, 

115 the copy will be returned; when ``True``, a new copy will be created. 

116 (Default value = ``False``) 

117 ignore_fields: List/tuple of field names (for dictionaries) that will be ignored 

118 during cloning (applies to children duplication as well). If fields are to be 

119 considered for a limited number of levels, you have to add it as integer, for 

120 example ``[1,"/B","/TOTO"]`` means that ``"/B"`` will be ignored at the first 

121 level only but ``"/TOTO"`` on all levels. 

122 

123 Returns: 

124 The cloned PdfObject 

125 

126 """ 

127 raise NotImplementedError( 

128 f"{self.__class__.__name__} does not implement .clone so far" 

129 ) 

130 

131 def _reference_clone( 

132 self, clone: "PdfObject", pdf_dest: PdfWriterProtocol, force_duplicate: bool = False 

133 ) -> "PdfObject": 

134 """ 

135 Reference the object within the _objects of pdf_dest only if 

136 indirect_reference attribute exists (which means the objects was 

137 already identified in xref/xobjstm) if object has been already 

138 referenced do nothing. 

139 

140 Args: 

141 clone: 

142 pdf_dest: 

143 

144 Returns: 

145 The clone 

146 

147 """ 

148 if not hasattr(self, "indirect_reference"): 

149 # Direct object: nothing to reference. 

150 # Returning early is much faster than handling the exceptions below. 

151 return clone 

152 try: 

153 if ( 

154 not force_duplicate 

155 and clone.indirect_reference is not None 

156 and clone.indirect_reference.pdf == pdf_dest 

157 ): 

158 return clone 

159 except MemoryError: # pragma: no cover # TODO: BLE001 

160 raise 

161 except Exception: 

162 pass 

163 ind = self.indirect_reference 

164 generation = 0 

165 if ( 

166 pdf_dest.incremental 

167 and ind is not None 

168 and ind.pdf == pdf_dest._reader 

169 and ind.idnum <= len(pdf_dest._objects) 

170 ): 

171 # Keep the number and generation the incremental source uses for this object. 

172 i = ind.idnum 

173 generation = ind.generation 

174 else: 

175 i = len(pdf_dest._objects) + 1 

176 if ind is not None: 

177 if id(ind.pdf) not in pdf_dest._id_translated: 

178 pdf_dest._id_translated[id(ind.pdf)] = {} 

179 pdf_dest._id_translated[id(ind.pdf)]["PreventGC"] = ind.pdf 

180 if ( 

181 not force_duplicate 

182 and ind.idnum in pdf_dest._id_translated[id(ind.pdf)] 

183 ): 

184 obj = pdf_dest.get_object( 

185 pdf_dest._id_translated[id(ind.pdf)][ind.idnum] 

186 ) 

187 assert isinstance(obj, PdfObject), "mypy" 

188 return obj 

189 pdf_dest._id_translated[id(ind.pdf)][ind.idnum] = i 

190 try: 

191 pdf_dest._objects[i - 1] = clone 

192 except IndexError: 

193 pdf_dest._objects.append(clone) 

194 i = len(pdf_dest._objects) 

195 clone.indirect_reference = IndirectObject(i, generation, pdf_dest) 

196 return clone 

197 

198 def get_object(self) -> Optional["PdfObject"]: 

199 """Resolve indirect references.""" 

200 return self 

201 

202 def write_to_stream(self, stream: StreamType) -> None: 

203 raise NotImplementedError 

204 

205 

206class NullObject(PdfObject): 

207 def clone( 

208 self, 

209 pdf_dest: PdfWriterProtocol, 

210 force_duplicate: bool = False, 

211 ignore_fields: Sequence[str | int] | None = (), 

212 ) -> "NullObject": 

213 """Clone object into pdf_dest.""" 

214 if not hasattr(self, "indirect_reference"): 

215 # Direct object: shortcut, as some arrays consist mostly of nulls 

216 return NullObject() 

217 return cast( 

218 "NullObject", self._reference_clone(NullObject(), pdf_dest, force_duplicate) 

219 ) 

220 

221 def hash_bin(self) -> int: 

222 """ 

223 Used to detect modified object. 

224 

225 Returns: 

226 Hash considering type and value. 

227 

228 """ 

229 return hash((self.__class__,)) 

230 

231 def write_to_stream(self, stream: StreamType) -> None: 

232 stream.write(b"null") 

233 

234 @staticmethod 

235 def read_from_stream(stream: StreamType) -> "NullObject": 

236 nulltxt = stream.read(4) 

237 if nulltxt != b"null": 

238 raise PdfReadError("Could not read Null object") 

239 return NullObject() 

240 

241 def __repr__(self) -> str: 

242 return "NullObject" 

243 

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

245 return isinstance(other, NullObject) 

246 

247 def __hash__(self) -> int: 

248 return self.hash_bin() 

249 

250 

251class BooleanObject(PdfObject): 

252 value: bool 

253 

254 def __init__(self, value: Any) -> None: 

255 self.value = value 

256 

257 def clone( 

258 self, 

259 pdf_dest: PdfWriterProtocol, 

260 force_duplicate: bool = False, 

261 ignore_fields: Sequence[str | int] | None = (), 

262 ) -> "BooleanObject": 

263 """Clone object into pdf_dest.""" 

264 return cast( 

265 "BooleanObject", 

266 self._reference_clone(BooleanObject(self.value), pdf_dest, force_duplicate), 

267 ) 

268 

269 def hash_bin(self) -> int: 

270 """ 

271 Used to detect modified object. 

272 

273 Returns: 

274 Hash considering type and value. 

275 

276 """ 

277 return hash((self.__class__, self.value)) 

278 

279 def __eq__(self, o: object, /) -> bool: 

280 if isinstance(o, BooleanObject): 

281 return self.value == o.value 

282 if isinstance(o, bool): 

283 return self.value == o 

284 return False 

285 

286 def __hash__(self) -> int: 

287 return self.hash_bin() 

288 

289 def __repr__(self) -> str: 

290 return "True" if self.value else "False" 

291 

292 def write_to_stream(self, stream: StreamType) -> None: 

293 if self.value: 

294 stream.write(b"true") 

295 else: 

296 stream.write(b"false") 

297 

298 @staticmethod 

299 def read_from_stream(stream: StreamType) -> "BooleanObject": 

300 word = stream.read(4) 

301 if word == b"true": 

302 return BooleanObject(True) 

303 if word == b"fals": 

304 stream.read(1) 

305 return BooleanObject(False) 

306 raise PdfReadError("Could not read Boolean object") 

307 

308 

309class IndirectObject(PdfObject): 

310 _MAXIMUM_PART_LENGTH = 64 

311 

312 def __init__(self, idnum: int, generation: int, pdf: Any) -> None: # PdfReader 

313 self.idnum = idnum 

314 self.generation = generation 

315 self.pdf = pdf 

316 

317 def __hash__(self) -> int: 

318 return hash((self.idnum, self.generation, id(self.pdf))) 

319 

320 def hash_bin(self) -> int: 

321 """ 

322 Used to detect modified object. 

323 

324 Returns: 

325 Hash considering type and value. 

326 

327 """ 

328 return hash((self.__class__, self.idnum, self.generation, id(self.pdf))) 

329 

330 def replicate( 

331 self, 

332 pdf_dest: PdfWriterProtocol, 

333 ) -> "PdfObject": 

334 return IndirectObject(self.idnum, self.generation, pdf_dest) 

335 

336 def clone( 

337 self, 

338 pdf_dest: PdfWriterProtocol, 

339 force_duplicate: bool = False, 

340 ignore_fields: Sequence[str | int] | None = (), 

341 ) -> "IndirectObject": 

342 """Clone object into pdf_dest.""" 

343 if self.pdf == pdf_dest and not force_duplicate: 

344 # Already duplicated and no extra duplication required 

345 return self 

346 if id(self.pdf) not in pdf_dest._id_translated: 

347 pdf_dest._id_translated[id(self.pdf)] = {} 

348 pdf_dest._id_translated[id(self.pdf)]["PreventGC"] = self.pdf 

349 

350 if self.idnum in pdf_dest._id_translated[id(self.pdf)]: 

351 dup = pdf_dest.get_object(pdf_dest._id_translated[id(self.pdf)][self.idnum]) 

352 if force_duplicate: 

353 assert dup is not None 

354 assert dup.indirect_reference is not None 

355 idref = dup.indirect_reference 

356 return IndirectObject(idref.idnum, idref.generation, idref.pdf) 

357 else: 

358 obj = self.get_object() 

359 # case observed : a pointed object can not be found 

360 if obj is None: 

361 # this normally 

362 obj = NullObject() 

363 assert isinstance(self, (IndirectObject,)) 

364 obj.indirect_reference = self 

365 dup = pdf_dest._add_object( 

366 obj.clone(pdf_dest, force_duplicate, ignore_fields) 

367 ) 

368 assert isinstance(dup, PdfObject), "mypy" 

369 assert dup.indirect_reference is not None, "mypy" 

370 return dup.indirect_reference 

371 

372 @property 

373 def indirect_reference(self) -> "IndirectObject": # type: ignore[override] 

374 return self 

375 

376 def get_object(self) -> Optional["PdfObject"]: 

377 obj: PdfObject | None = self.pdf.get_object(self) 

378 return obj 

379 

380 def __deepcopy__(self, memo: Any) -> "IndirectObject": 

381 return IndirectObject(self.idnum, self.generation, self.pdf) 

382 

383 def _get_object_with_check(self) -> Optional["PdfObject"]: 

384 o = self.get_object() 

385 # the check is done here to not slow down get_object() 

386 if isinstance(o, IndirectObject): 

387 raise PdfStreamError( 

388 f"{self.__repr__()} references an IndirectObject {o.__repr__()}" 

389 ) 

390 return o 

391 

392 def __getattr__(self, name: str) -> Any: 

393 # Attribute not found in object: look in pointed object 

394 try: 

395 return getattr(self._get_object_with_check(), name) 

396 except AttributeError as exception: 

397 raise AttributeError( 

398 f"No attribute {name} found in IndirectObject or pointed object" 

399 ) from exception 

400 

401 def __getitem__(self, key: Any) -> Any: 

402 # items should be extracted from pointed Object 

403 return self._get_object_with_check()[key] # type: ignore[index] 

404 

405 def __contains__(self, key: Any) -> bool: 

406 return key in self._get_object_with_check() # type: ignore[operator] 

407 

408 def __iter__(self) -> Any: 

409 return self._get_object_with_check().__iter__() # type: ignore[union-attr] 

410 

411 def __float__(self) -> str: 

412 # in this case we are looking for the pointed data 

413 return self.get_object().__float__() # type: ignore[union-attr, no-any-return] 

414 

415 def __int__(self) -> int: 

416 # in this case we are looking for the pointed data 

417 return self.get_object().__int__() # type: ignore[union-attr, no-any-return] 

418 

419 def __str__(self) -> str: 

420 # in this case we are looking for the pointed data 

421 return self.get_object().__str__() 

422 

423 def __repr__(self) -> str: 

424 return f"IndirectObject({self.idnum!r}, {self.generation!r}, {id(self.pdf)})" 

425 

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

427 return ( 

428 other is not None 

429 and isinstance(other, IndirectObject) 

430 and self.idnum == other.idnum 

431 and self.generation == other.generation 

432 and self.pdf is other.pdf 

433 ) 

434 

435 def __ne__(self, other: object) -> bool: 

436 return not self.__eq__(other) 

437 

438 def write_to_stream(self, stream: StreamType) -> None: 

439 stream.write(f"{self.idnum} {self.generation} R".encode()) 

440 

441 @staticmethod 

442 def read_from_stream(stream: StreamType, pdf: Any) -> "IndirectObject": # PdfReader 

443 def read_part(name: str, skip_leading_whitespace: bool) -> bytes: 

444 result = bytearray() 

445 while True: 

446 tok = stream.read(1) 

447 if not tok: 

448 raise PdfStreamError(STREAM_TRUNCATED_PREMATURELY) 

449 if tok.isspace() or tok in WHITESPACES: 

450 if skip_leading_whitespace and not result: 

451 continue 

452 break 

453 if len(result) >= IndirectObject._MAXIMUM_PART_LENGTH: 

454 raise PdfReadError(f"{name} exceeds maximum length limit of {IndirectObject._MAXIMUM_PART_LENGTH}.") 

455 result += tok 

456 return bytes(result) 

457 

458 idnum = read_part("Object ID", skip_leading_whitespace=False) 

459 generation = read_part("Generation number", skip_leading_whitespace=True) 

460 

461 r = read_non_whitespace(stream) 

462 if r != b"R": 

463 raise PdfReadError( 

464 f"Error reading indirect object reference at byte {hex(stream.tell())}" 

465 ) 

466 try: 

467 return IndirectObject(int(idnum), int(generation), pdf) 

468 except (ValueError, OverflowError) as exception: 

469 raise PdfReadError( 

470 f"Invalid indirect object reference ({idnum!r} {generation!r} R): {exception}" 

471 ) from exception 

472 

473 

474FLOAT_WRITE_PRECISION = 8 # shall be min 5 digits max, allow user adj 

475 

476 

477class FloatObject(float, PdfObject): 

478 def __new__( 

479 cls, value: Any = "0.0", context: Any | None = None 

480 ) -> Self: 

481 try: 

482 value = float(value) 

483 return float.__new__(cls, value) 

484 except MemoryError: # pragma: no cover # TODO: BLE001 

485 raise 

486 except Exception as exception: 

487 # If this isn't a valid decimal (happens in malformed PDFs) 

488 # fallback to 0 

489 logger_warning( 

490 "%(error)s : FloatObject (%(value)s) invalid; use 0.0 instead", 

491 source=__name__, 

492 error=exception, 

493 value=value, 

494 ) 

495 return float.__new__(cls, 0.0) 

496 

497 def clone( 

498 self, 

499 pdf_dest: Any, 

500 force_duplicate: bool = False, 

501 ignore_fields: Sequence[str | int] | None = (), 

502 ) -> "FloatObject": 

503 """Clone object into pdf_dest.""" 

504 return cast( 

505 "FloatObject", 

506 self._reference_clone(FloatObject(self), pdf_dest, force_duplicate), 

507 ) 

508 

509 def hash_bin(self) -> int: 

510 """ 

511 Used to detect modified object. 

512 

513 Returns: 

514 Hash considering type and value. 

515 

516 """ 

517 return hash((self.__class__, self.as_numeric())) 

518 

519 def myrepr(self) -> str: 

520 if self == 0: # type: ignore[comparison-overlap] 

521 return "0.0" 

522 nb = FLOAT_WRITE_PRECISION - int(log10(abs(self))) 

523 return f"{self:.{max(1, nb)}f}".rstrip("0").rstrip(".") 

524 

525 def __repr__(self) -> str: 

526 return self.myrepr() # repr(float(self)) 

527 

528 def as_numeric(self) -> float: 

529 return float(self) 

530 

531 def write_to_stream(self, stream: StreamType) -> None: 

532 stream.write(self.myrepr().encode("utf8")) 

533 

534 

535class NumberObject(int, PdfObject): 

536 NumberPattern = re.compile(b"[^+-.0-9]") 

537 _LENGTH_LIMIT = 64 

538 

539 def __new__(cls, value: Any) -> Self: 

540 try: 

541 return int.__new__(cls, int(value)) 

542 except ValueError: 

543 logger_warning("NumberObject(%(value)s) invalid; use 0 instead", source=__name__, value=value) 

544 return int.__new__(cls, 0) 

545 

546 def clone( 

547 self, 

548 pdf_dest: Any, 

549 force_duplicate: bool = False, 

550 ignore_fields: Sequence[str | int] | None = (), 

551 ) -> "NumberObject": 

552 """Clone object into pdf_dest.""" 

553 return cast( 

554 "NumberObject", 

555 self._reference_clone(NumberObject(self), pdf_dest, force_duplicate), 

556 ) 

557 

558 def hash_bin(self) -> int: 

559 """ 

560 Used to detect modified object. 

561 

562 Returns: 

563 Hash considering type and value. 

564 

565 """ 

566 return hash((self.__class__, self.as_numeric())) 

567 

568 def as_numeric(self) -> int: 

569 return int(repr(self).encode("utf8")) 

570 

571 def write_to_stream(self, stream: StreamType) -> None: 

572 stream.write(repr(self).encode("utf8")) 

573 

574 @staticmethod 

575 def read_from_stream(stream: StreamType) -> Union["NumberObject", "FloatObject"]: 

576 num = read_until_regex(stream=stream, regex=NumberObject.NumberPattern, length=NumberObject._LENGTH_LIMIT) 

577 if b"." in num: 

578 return FloatObject(num) 

579 return NumberObject(num) 

580 

581 

582class ByteStringObject(bytes, PdfObject): 

583 """ 

584 Represents a string object where the text encoding could not be determined. 

585 

586 This occurs quite often, as the PDF spec doesn't provide an alternate way to 

587 represent strings -- for example, the encryption data stored in files (like 

588 /O) is clearly not text, but is still stored in a "String" object. 

589 """ 

590 

591 def clone( 

592 self, 

593 pdf_dest: Any, 

594 force_duplicate: bool = False, 

595 ignore_fields: Sequence[str | int] | None = (), 

596 ) -> "ByteStringObject": 

597 """Clone object into pdf_dest.""" 

598 return cast( 

599 "ByteStringObject", 

600 self._reference_clone( 

601 ByteStringObject(bytes(self)), pdf_dest, force_duplicate 

602 ), 

603 ) 

604 

605 def hash_bin(self) -> int: 

606 """ 

607 Used to detect modified object. 

608 

609 Returns: 

610 Hash considering type and value. 

611 

612 """ 

613 return hash((self.__class__, bytes(self))) 

614 

615 @property 

616 def original_bytes(self) -> bytes: 

617 """For compatibility with TextStringObject.original_bytes.""" 

618 return self 

619 

620 def write_to_stream(self, stream: StreamType) -> None: 

621 stream.write(b"<") 

622 stream.write(binascii.hexlify(self)) 

623 stream.write(b">") 

624 

625 def __str__(self) -> str: 

626 charset_to_try = ["utf-16", *list(NameObject.CHARSETS)] 

627 for enc in charset_to_try: 

628 try: 

629 return self.decode(enc) 

630 except UnicodeDecodeError: 

631 pass 

632 raise PdfReadError("Cannot decode ByteStringObject.") 

633 

634 

635class TextStringObject(str, PdfObject): # noqa: SLOT000 

636 """ 

637 A string object that has been decoded into a real unicode string. 

638 

639 If read from a PDF document, this string appeared to match the 

640 PDFDocEncoding, or contained a UTF-16BE BOM mark to cause UTF-16 decoding 

641 to occur. 

642 """ 

643 

644 autodetect_pdfdocencoding: bool 

645 autodetect_utf16: bool 

646 utf16_bom: bytes 

647 _original_bytes: bytes | None = None 

648 

649 def __new__(cls, value: Any) -> Self: 

650 original_bytes = None 

651 if isinstance(value, bytes): 

652 original_bytes = value 

653 value = value.decode("charmap") 

654 text_string_object = str.__new__(cls, value) 

655 text_string_object._original_bytes = original_bytes 

656 text_string_object.autodetect_utf16 = False 

657 text_string_object.autodetect_pdfdocencoding = False 

658 text_string_object.utf16_bom = b"" 

659 if original_bytes is not None and original_bytes[:2] in {codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE}: 

660 # The value of `original_bytes` is only set for inputs being `bytes`. 

661 # If this is UTF-16 data according to the BOM (first two characters), 

662 # perform special handling. All other cases should not need any special conversion 

663 # due to already being a string. 

664 try: 

665 text_string_object = str.__new__(cls, original_bytes.decode("utf-16")) 

666 except UnicodeDecodeError as exception: 

667 logger_warning( 

668 "%(exception)s; initial string: %(initial_string)r", 

669 source=__name__, 

670 exception=exception, 

671 initial_string=exception.object, 

672 ) 

673 text_string_object = str.__new__(cls, exception.object[: exception.start].decode("utf-16")) 

674 text_string_object._original_bytes = original_bytes 

675 text_string_object.autodetect_utf16 = True 

676 text_string_object.utf16_bom = original_bytes[:2] 

677 else: 

678 try: 

679 encode_pdfdocencoding(text_string_object) 

680 text_string_object.autodetect_pdfdocencoding = True 

681 except UnicodeEncodeError: 

682 text_string_object.autodetect_utf16 = True 

683 text_string_object.utf16_bom = codecs.BOM_UTF16_BE 

684 return text_string_object 

685 

686 def clone( 

687 self, 

688 pdf_dest: Any, 

689 force_duplicate: bool = False, 

690 ignore_fields: Sequence[str | int] | None = (), 

691 ) -> "TextStringObject": 

692 """Clone object into pdf_dest.""" 

693 obj = TextStringObject(self) 

694 obj._original_bytes = self._original_bytes 

695 obj.autodetect_pdfdocencoding = self.autodetect_pdfdocencoding 

696 obj.autodetect_utf16 = self.autodetect_utf16 

697 obj.utf16_bom = self.utf16_bom 

698 return cast( 

699 "TextStringObject", self._reference_clone(obj, pdf_dest, force_duplicate) 

700 ) 

701 

702 def hash_bin(self) -> int: 

703 """ 

704 Used to detect modified object. 

705 

706 Returns: 

707 Hash considering type and value. 

708 

709 """ 

710 return hash((self.__class__, self.original_bytes)) 

711 

712 @property 

713 def original_bytes(self) -> bytes: 

714 """ 

715 It is occasionally possible that a text string object gets created where 

716 a byte string object was expected due to the autodetection mechanism -- 

717 if that occurs, this "original_bytes" property can be used to 

718 back-calculate what the original encoded bytes were. 

719 """ 

720 if self._original_bytes is not None: 

721 return self._original_bytes 

722 return self.get_original_bytes() 

723 

724 def get_original_bytes(self) -> bytes: 

725 # We're a text string object, but the library is trying to get our raw 

726 # bytes. This can happen if we auto-detected this string as text, but 

727 # we were wrong. It's pretty common. Return the original bytes that 

728 # would have been used to create this object, based upon the autodetect 

729 # method. 

730 if self.autodetect_utf16: 

731 if self.utf16_bom == codecs.BOM_UTF16_LE: 

732 return codecs.BOM_UTF16_LE + self.encode("utf-16le") 

733 if self.utf16_bom == codecs.BOM_UTF16_BE: 

734 return codecs.BOM_UTF16_BE + self.encode("utf-16be") 

735 return self.encode("utf-16be") 

736 if self.autodetect_pdfdocencoding: 

737 return encode_pdfdocencoding(self) 

738 raise Exception("no information about original bytes") # pragma: no cover 

739 

740 def get_encoded_bytes(self) -> bytes: 

741 # Try to write the string out as a PDFDocEncoding encoded string. It's 

742 # nicer to look at in the PDF file. Sadly, we take a performance hit 

743 # here for trying... 

744 try: 

745 if self._original_bytes is not None: 

746 return self._original_bytes 

747 if self.autodetect_utf16: 

748 raise UnicodeEncodeError("", "forced", -1, -1, "") 

749 bytearr = encode_pdfdocencoding(self) 

750 except UnicodeEncodeError: 

751 if self.utf16_bom == codecs.BOM_UTF16_LE: 

752 bytearr = codecs.BOM_UTF16_LE + self.encode("utf-16le") 

753 elif self.utf16_bom == codecs.BOM_UTF16_BE: 

754 bytearr = codecs.BOM_UTF16_BE + self.encode("utf-16be") 

755 else: 

756 bytearr = self.encode("utf-16be") 

757 return bytearr 

758 

759 def write_to_stream(self, stream: StreamType) -> None: 

760 bytearr = self.get_encoded_bytes() 

761 stream.write(b"(") 

762 for c_ in iter_unpack("c", bytearr): 

763 c = cast(bytes, c_[0]) 

764 if not c.isalnum() and c != b" ": 

765 # This: 

766 # stream.write(rf"\{c:0>3o}".encode()) 

767 # gives 

768 # https://github.com/davidhalter/parso/issues/207 

769 stream.write(b"\\%03o" % ord(c)) 

770 else: 

771 stream.write(c) 

772 stream.write(b")") 

773 

774 

775class NameObject(str, PdfObject): # noqa: SLOT000 

776 delimiter_pattern = re.compile(rb"\s+|[\(\)<>\[\]{}/%]") 

777 prefix = b"/" 

778 renumber_table: ClassVar[dict[str, bytes]] = { 

779 **{chr(i): f"#{i:02X}".encode() for i in b"#()<>[]{}/%"}, 

780 **{chr(i): f"#{i:02X}".encode() for i in range(33)}, 

781 } 

782 _LENGTH_LIMIT = 4096 

783 

784 def clone( 

785 self, 

786 pdf_dest: Any, 

787 force_duplicate: bool = False, 

788 ignore_fields: Sequence[str | int] | None = (), 

789 ) -> "NameObject": 

790 """Clone object into pdf_dest.""" 

791 return cast( 

792 "NameObject", 

793 self._reference_clone(NameObject(self), pdf_dest, force_duplicate), 

794 ) 

795 

796 def hash_bin(self) -> int: 

797 """ 

798 Used to detect modified object. 

799 

800 Returns: 

801 Hash considering type and value. 

802 

803 """ 

804 return hash((self.__class__, self)) 

805 

806 def write_to_stream(self, stream: StreamType) -> None: 

807 stream.write(self.renumber()) 

808 

809 def renumber(self) -> bytes: 

810 out = self[0].encode("utf-8") 

811 if out != b"/": 

812 raise PdfStreamError( 

813 f"Incorrect first char in NameObject, should start with '/': ({self})", 

814 ) 

815 parts = [out] 

816 for c in self[1:]: 

817 if c > "~": 

818 parts.extend(f"#{x:02X}".encode() for x in c.encode("utf-8")) 

819 else: 

820 try: 

821 parts.append(self.renumber_table[c]) 

822 except KeyError: 

823 parts.append(c.encode("utf-8")) 

824 return b"".join(parts) 

825 

826 def _sanitize(self) -> "NameObject": 

827 """ 

828 Sanitize the NameObject's name to be a valid PDF name part 

829 (alphanumeric, underscore, hyphen). The _sanitize method replaces 

830 spaces and any non-alphanumeric/non-underscore/non-hyphen with 

831 underscores. 

832 

833 Returns: 

834 NameObject with sanitized name. 

835 """ 

836 name = str(self).removeprefix("/") 

837 name = re.sub(r" ", "_", name) 

838 name = re.sub(r"[^a-zA-Z0-9_-]", "_", name) 

839 return NameObject("/" + name) 

840 

841 @staticmethod 

842 def unnumber(sin: bytes) -> bytes: 

843 if b"#" not in sin: 

844 return bytes(sin) 

845 result = bytearray() 

846 i = 0 

847 while i < len(sin): 

848 if sin[i:i + 1] == b"#": 

849 try: 

850 result.append(int(sin[i + 1 : i + 3], 16)) 

851 i += 3 

852 continue 

853 except (ValueError, IndexError): 

854 # if the 2 characters after # can not be converted to hex 

855 # we change nothing and carry on 

856 pass 

857 result.append(sin[i]) 

858 i += 1 

859 return bytes(result) 

860 

861 CHARSETS = ("utf-8", "gbk", "latin1") 

862 

863 @staticmethod 

864 def read_from_stream(stream: StreamType, pdf: Any) -> "NameObject": # PdfReader 

865 name = stream.read(1) 

866 if name != NameObject.prefix: 

867 raise PdfReadError("Name read error") 

868 name += read_until_regex(stream=stream, regex=NameObject.delimiter_pattern, length=NameObject._LENGTH_LIMIT) 

869 try: 

870 # Name objects should represent irregular characters 

871 # with a '#' followed by the symbol's hex number 

872 name = NameObject.unnumber(name) 

873 for enc in NameObject.CHARSETS: 

874 try: 

875 ret = name.decode(enc) 

876 return NameObject(ret) 

877 except MemoryError: # pragma: no cover # TODO: BLE001 

878 raise 

879 except Exception: 

880 pass 

881 raise UnicodeDecodeError("", name, 0, 0, "Code Not Found") 

882 except (UnicodeEncodeError, UnicodeDecodeError) as exception: 

883 if not pdf.strict: 

884 logger_warning( 

885 "Illegal character in NameObject (%(name)r), you may need to adjust NameObject.CHARSETS", 

886 source=__name__, 

887 name=name, 

888 ) 

889 return NameObject(name.decode("charmap")) 

890 raise PdfReadError( 

891 f"Illegal character in NameObject ({name!r}). " 

892 "You may need to adjust NameObject.CHARSETS.", 

893 ) from exception 

894 

895 

896def encode_pdfdocencoding(unicode_string: str) -> bytes: 

897 try: 

898 return bytes([_pdfdoc_encoding_rev[k] for k in unicode_string]) 

899 except KeyError as exception: 

900 raise UnicodeEncodeError( 

901 "pdfdocencoding", 

902 unicode_string, 

903 -1, 

904 -1, 

905 "does not exist in translation table", 

906 ) from exception 

907 

908 

909def is_null_or_none(x: Any) -> TypeGuard[NullObject | IndirectObject | None]: 

910 """ 

911 Returns: 

912 True if x is None or NullObject. 

913 

914 """ 

915 return x is None or ( 

916 isinstance(x, PdfObject) 

917 and (x.get_object() is None or isinstance(x.get_object(), NullObject)) 

918 )