Commit dff43b8f8f48097507a417a9752faa929c005212

Authored by m-holger
1 parent 44bd9db1

Add `BaseHandle::find` method to retrieve values by key from dictionaries.

include/qpdf/ObjectHandle.hh
... ... @@ -85,6 +85,7 @@ namespace qpdf
85 85  
86 86 bool contains(std::string const& key) const;
87 87 size_t erase(std::string const& key);
  88 + QPDFObjectHandle& find(std::string const& key) const;
88 89 bool replace(std::string const& key, QPDFObjectHandle value);
89 90 QPDFObjectHandle const& operator[](std::string const& key) const;
90 91  
... ...
libqpdf/QPDF_Dictionary.cc
... ... @@ -2,6 +2,7 @@
2 2  
3 3 #include <qpdf/QPDFObject_private.hh>
4 4 #include <qpdf/QTC.hh>
  5 +#include <qpdf/Util.hh>
5 6  
6 7 using namespace std::literals;
7 8 using namespace qpdf;
... ... @@ -29,12 +30,49 @@ BaseHandle::operator[](std::string const&amp; key) const
29 30 return null_obj;
30 31 }
31 32  
  33 +/// @brief Checks if the specified key exists in the object.
  34 +///
  35 +/// This method determines whether the given key is present in the object by verifying if the
  36 +/// associated value is non-null.
  37 +///
  38 +/// @param key The key to look for in the object.
  39 +/// @return True if the key exists and its associated value is non-null. Otherwise, returns false.
32 40 bool
33 41 BaseHandle::contains(std::string const& key) const
34 42 {
35 43 return !(*this)[key].null();
36 44 }
37 45  
  46 +/// @brief Retrieves the value associated with the given key from dictionary.
  47 +///
  48 +/// This method attempts to find the value corresponding to the specified key for objects that can
  49 +/// be interpreted as dictionaries.
  50 +///
  51 +/// - If the object is a dictionary and the specified key exists, it returns a reference
  52 +/// to the associated value.
  53 +/// - If the object is not a dictionary or the specified key does not exist, it returns
  54 +/// a reference to a static uninitialized object handle.
  55 +///
  56 +/// @note Modifying the uninitialized object returned when the key is not found is strictly
  57 +/// prohibited.
  58 +///
  59 +/// @param key The key whose associated value should be retrieved.
  60 +/// @return A reference to the associated value if the key is found or a reference to a static
  61 +/// uninitialized object if the key is not found.
  62 +QPDFObjectHandle&
  63 +BaseHandle::find(std::string const& key) const
  64 +{
  65 + static const QPDFObjectHandle null_obj;
  66 + qpdf_invariant(!null_obj);
  67 + if (auto d = as<QPDF_Dictionary>()) {
  68 + auto it = d->items.find(key);
  69 + if (it != d->items.end()) {
  70 + return it->second;
  71 + }
  72 + }
  73 + return const_cast<QPDFObjectHandle&>(null_obj);
  74 +}
  75 +
38 76 std::set<std::string>
39 77 BaseDictionary::getKeys()
40 78 {
... ...