From 65ef82beff31b2d04edd4162044fb898ab32bf44 Mon Sep 17 00:00:00 2001 From: m-holger Date: Mon, 10 Nov 2025 10:08:51 +0000 Subject: [PATCH] Add `BaseHandle::at` method for accessing dictionary values by key safely. --- include/qpdf/ObjectHandle.hh | 1 + libqpdf/QPDF_Dictionary.cc | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 0 deletions(-) diff --git a/include/qpdf/ObjectHandle.hh b/include/qpdf/ObjectHandle.hh index 2e2295a..478efcb 100644 --- a/include/qpdf/ObjectHandle.hh +++ b/include/qpdf/ObjectHandle.hh @@ -83,6 +83,7 @@ namespace qpdf QPDFObjectHandle operator[](size_t n) const; QPDFObjectHandle operator[](int n) const; + QPDFObjectHandle& at(std::string const& key) const; bool contains(std::string const& key) const; size_t erase(std::string const& key); QPDFObjectHandle& find(std::string const& key) const; diff --git a/libqpdf/QPDF_Dictionary.cc b/libqpdf/QPDF_Dictionary.cc index d4eccd1..830956f 100644 --- a/libqpdf/QPDF_Dictionary.cc +++ b/libqpdf/QPDF_Dictionary.cc @@ -30,6 +30,27 @@ BaseHandle::operator[](std::string const& key) const return null_obj; } +/// Retrieves a reference to the QPDFObjectHandle associated with the given key in the +/// dictionary object contained within this instance. +/// +/// If the current object is not of dictionary type, a `std::runtime_error` is thrown. +/// According to the PDF specification, missing keys in the dictionary are treated as +/// keys with a `null` value. This behavior is reflected in this function's implementation, +/// where a missing key will still return a reference to a newly inserted null value entry. +/// +/// @param key The key for which the corresponding value in the dictionary is retrieved. +/// @return A reference to the QPDFObjectHandle associated with the specified key. +/// @throws std::runtime_error if the current object is not a dictionary. +QPDFObjectHandle& +BaseHandle::at(std::string const& key) const +{ + auto d = as(); + if (!d) { + throw std::runtime_error("Expected a dictionary but found a non-dictionary object"); + } + return d->items[key]; +} + /// @brief Checks if the specified key exists in the object. /// /// This method determines whether the given key is present in the object by verifying if the -- libgit2 0.21.4