Browse Source

LibPDF: Add Reader::try_read for easier error propagation

This will allow us to use TRY(reader.try_read) instead of having to
verify the result of reader.remaining() before calling read.read().
Rodrigo Tobar 2 years ago
parent
commit
c592b889bf
1 changed files with 11 additions and 0 deletions
  1. 11 0
      Userland/Libraries/LibPDF/Reader.h

+ 11 - 0
Userland/Libraries/LibPDF/Reader.h

@@ -12,6 +12,7 @@
 #include <AK/ScopeGuard.h>
 #include <AK/Span.h>
 #include <AK/Vector.h>
+#include <LibPDF/Error.h>
 
 namespace PDF {
 
@@ -59,6 +60,16 @@ public:
         return value;
     }
 
+    template<typename T = char>
+    PDFErrorOr<T> try_read()
+    {
+        if (sizeof(T) + m_offset >= m_bytes.size()) {
+            auto message = DeprecatedString::formatted("Cannot read {} bytes at offset {} of ReadonlyBytes of size {}", sizeof(T), m_offset, m_bytes.size());
+            return Error { Error::Type::Parse, message };
+        }
+        return read<T>();
+    }
+
     char peek(size_t shift = 0) const
     {
         auto offset = m_offset + shift * (m_forwards ? 1 : -1);