Commit 65ef82beff31b2d04edd4162044fb898ab32bf44

Authored by m-holger
1 parent dff43b8f

Add `BaseHandle::at` method for accessing dictionary values by key safely.

include/qpdf/ObjectHandle.hh
@@ -83,6 +83,7 @@ namespace qpdf @@ -83,6 +83,7 @@ namespace qpdf
83 QPDFObjectHandle operator[](size_t n) const; 83 QPDFObjectHandle operator[](size_t n) const;
84 QPDFObjectHandle operator[](int n) const; 84 QPDFObjectHandle operator[](int n) const;
85 85
  86 + QPDFObjectHandle& at(std::string const& key) const;
86 bool contains(std::string const& key) const; 87 bool contains(std::string const& key) const;
87 size_t erase(std::string const& key); 88 size_t erase(std::string const& key);
88 QPDFObjectHandle& find(std::string const& key) const; 89 QPDFObjectHandle& find(std::string const& key) const;
libqpdf/QPDF_Dictionary.cc
@@ -30,6 +30,27 @@ BaseHandle::operator[](std::string const& key) const @@ -30,6 +30,27 @@ BaseHandle::operator[](std::string const& key) const
30 return null_obj; 30 return null_obj;
31 } 31 }
32 32
  33 +/// Retrieves a reference to the QPDFObjectHandle associated with the given key in the
  34 +/// dictionary object contained within this instance.
  35 +///
  36 +/// If the current object is not of dictionary type, a `std::runtime_error` is thrown.
  37 +/// According to the PDF specification, missing keys in the dictionary are treated as
  38 +/// keys with a `null` value. This behavior is reflected in this function's implementation,
  39 +/// where a missing key will still return a reference to a newly inserted null value entry.
  40 +///
  41 +/// @param key The key for which the corresponding value in the dictionary is retrieved.
  42 +/// @return A reference to the QPDFObjectHandle associated with the specified key.
  43 +/// @throws std::runtime_error if the current object is not a dictionary.
  44 +QPDFObjectHandle&
  45 +BaseHandle::at(std::string const& key) const
  46 +{
  47 + auto d = as<QPDF_Dictionary>();
  48 + if (!d) {
  49 + throw std::runtime_error("Expected a dictionary but found a non-dictionary object");
  50 + }
  51 + return d->items[key];
  52 +}
  53 +
33 /// @brief Checks if the specified key exists in the object. 54 /// @brief Checks if the specified key exists in the object.
34 /// 55 ///
35 /// This method determines whether the given key is present in the object by verifying if the 56 /// This method determines whether the given key is present in the object by verifying if the